Skip to content

Instantly share code, notes, and snippets.

@ajpen
Created June 26, 2015 16:07
Show Gist options
  • Save ajpen/f1de59950a92b2991aa5 to your computer and use it in GitHub Desktop.
Save ajpen/f1de59950a92b2991aa5 to your computer and use it in GitHub Desktop.
/*---------------------------------------------------------
* Program: shuffle.cpp
* Usage: ./shuffle
*---------------------------------------------------------
* Description: Prints a random permutation of the string
* "helloworld" alongside the source string
*_________________________________________________________
*/
/* INCLUDES */
#include <iostream>
#include <stdlib.h>
/* NAMESPACE FUNCTIONS */
// allows "free" use of string class, endl and cout from the namespace std
using std::string;
using std::cout;
using std::endl;
/* FUNCTIONS */
/*---------------------------------------------------------
* Function: stringrand()
* Usage: stringrand(string source, string &result)
*---------------------------------------------------------
* Description: Converts the empty string "result" into
* a random permutation of the string "source" by
* shuffling the contents of the prevous string. Source
* remains untouched while result is modified and must
* be passed by reference
*_________________________________________________________
*/
void stringrand(string source, string &result) {
// seed rand
srand(time(NULL));
// stores random index
int index;
for (int i=0, j = source.length(); i<j; j--) {
// retrieves random index
index = rand() % j;
// appends the random char to new string
result += source[index];
// remove char from source
source.erase(index,1);
}
}
int main () {
string s = "helloworld";
string random = "";
// converts string random into a permutaton of the string s
stringrand(s, random);
// prints results and length of both strings
cout << "Source String: " << s << endl << "New String: " << random << endl;
cout << "Length of source: " << s.length() << endl << "Length of result: " << random.length() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment