I have been tasked with implementing a simple substitution encryption scheme for which I am given an encoder.
The program below is for the Mac even though I have been instructed to make the program compile and run in Visual Studio for Windows.
My reason is that I own a Mac and thought it would be just as well to write the program on whichever machine I like, then make the adjustments where necessary. It's only a console mode app after all.
I didn't expect is how the program behaves on a Mac:
On the Mac the seed quite simply appears not to work. It keeps on producing new permutations even though I have only used two different seeds.
Visual Studio on Windows generated the expected result of producing a permutation unique to each seed value. Does srand simply mean nothing with respect to the random_shuffle function on a Mac, unlike on a PC?
Code below, followed by output cut and paste. Both from Mac X-Code 7.2 compilation.
So, basically, why doesn't srand(seed) do what's expected?
/code
#include <string>
#include <cstdlib>
#include "algorithm"
#include <iostream>
using namespace std;
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,í ";
string cp(unsigned seed) {
srand(seed);
string permutation = ALPHABET;
// using built-in random generator:
random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
int main(int argc, char** argv) {
unsigned seedy = 100;
string what = cp(seedy);
cout << what << endl;
seedy = 200;
what = cp(seedy);
cout << what << endl;
seedy = 100;
what = cp(seedy);
cout << what << endl;
seedy = 100;
what = cp(seedy);
cout << what << endl;
getchar();
return 0;
}
/code
Console output:
'XQACKHSLOJ,TRBZNGV.W FIUEYDMP
OILQPNSWBAHYGTD'EFKV,XMR. CJZU
J,DKXTHP'RQOEZCYG. SMFIULABVNW
WNJTCYA EHSDPQLKO.ZURGF,'VMIBX