Created
June 26, 2015 16:05
-
-
Save ajpen/b032210ae5422e221152 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*--------------------------------------------------------- | |
* Program: recshuffle.cpp | |
* Usage: ./recshuffle | |
*--------------------------------------------------------- | |
* Description: Prints a random permutation of the string | |
* "helloworld" alongside the source string. This program | |
* uses a recursive approach instead of an iterative one | |
*_________________________________________________________ | |
*/ | |
/* 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: stringrandr() | |
* Usage: string result = stringrandr(string source, string &result, int len, int curlen) | |
*---------------------------------------------------------------------------------------- | |
* 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. This function is recursive. | |
*________________________________________________________________________________________ | |
*/ | |
string stringrandr(string source, string &result, int len, int curlen) { | |
// base case; If this runs, the function ends. | |
if (source == "" && curlen == 0) | |
return result; | |
// stores random index generated | |
int index; | |
// seed rand | |
srand(time(NULL)); | |
// retrieves random index | |
index = rand() % curlen; | |
// appends the random char to new string | |
result += source[index]; | |
// remove char from source | |
source.erase(index,1); | |
// recursive call | |
return stringrandr(source, result, len, curlen-1); | |
} | |
int main () { | |
// source and result strings used | |
string s = "helloworld"; | |
string random = ""; | |
// length of source string used | |
int slen = s.length(); | |
// produces a permutation of the string s | |
random = stringrandr(s, random, slen, slen); | |
// prints results and length of both strings | |
cout << "Source String: " << s << endl << "New String: " << random << endl; | |
cout << "Length of source: " << slen << endl << "Length of result: " << random.length() << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment