-
String Scrambler :)
Hello,
I know that algorithm has a shuffle function. Someone told me when I was making my program in a chat room lol. but I wanted to make it anways to see if I can do it. Please leave feed back and tell me what you think :D and improvements and stuff. Thanks. BYebye :D
Code:
#include <iostream>
#include <time.h>
using namespace std;
void Scramble(string &s){
int scram_num=s.size()*s.size();
srand(time(NULL));
for(int a=0;a<scram_num;a++){
int i=rand()%s.size();
char c=s[i];
s.erase(i,1);
int ii=rand()%s.size();
s.insert(ii,1,c);
}
}
int main(){
string s="Country";
Scramble(s);
for(unsigned int i=0;i<s.size();i++){
cout<<s[i];
}
system("PAUSE");
return 0;
}
-
Here's a few you may want to think about: Code:
#include <iostream>
#include <string> //include this - I'm not sure how I compiled without it.
//#include <time.h> //don't include this - .h standard headers have everything
//in the global namespace which could lead to name collision
#include <ctime> //include this one instead of <time.h>
//using namespace std; //why bring the whole std namespace in?
//You're only using two (soon to be three) things out of it
using std::string;
using std::cout;
using std::endl;
void Scramble(string &s)
{
int size = s.size(); //create a temp variable for size
//instead of calling the function multiple times inside the for loop
int scram_num=size*size;
srand(time(NULL));
for(int a=0;a<scram_num;a++)
{
int i=rand()%size;
char c=s[i];
s.erase(i,1);
int ii=rand()%size;
s.insert(ii,1,c);
}
}
int main()
{
string s="Country";
Scramble(s);
cout << s << endl; //you can cout a string; make sure to flush the output
return 0;
}
I once wrote a shuffle like this: Code:
#include <algorithm>
void Shuffle(string &s)
{
int size = s.size();
srand(time(NULL));
for(int a=0;a<size-1;a++)
{
int i = rand()%(size-a)+a;
while(i==a)
i = rand()%(size-a)+a;
std::swap(s[a],s[rand()%(size-a)+a]);
}
}
It keeps from erasing and inserting so much. It also cuts down on the number of times through the scramble loop.
-
Oh I saw you using Swap :P That is clever didnt think about that :) I was just thinking about inserting without changing any other places. Thanks for the insights :D