#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ()
{
srand(time(NULL));
string word[40437];
ifstream list("dictionary.txt");
int n = 0;
while(n < 40437 && list >> word[n])
{
++n;
}
int r= rand() % 40437;
cout << word[r] << '\n';
system("pause");
}
Easy randomizer issue
Page 1 of 12 Replies - 313 Views - Last Post: 18 March 2013 - 06:12 PM
#1
Easy randomizer issue
Posted 08 March 2013 - 06:52 PM
Ive been working on a little program that goes through a .txt file called dictionary that contains 40k+ words (actually number is in code below) and prints out a random word. This program works semi-fine because it does initially does give me a random word from the dictionary but if I run it again the next "random" word will not exactly be random but a word that is relatively close to the last word the was printed from the previous compilation.My question is what can I change to make this program print out a word that is truly random every time, and if you can give me pointers on why the code I have here does not give me truly random values each time I compile it would be greatly appreciated. Thanks for the help!
Replies To: Easy randomizer issue
#2
Re: Easy randomizer issue
Posted 08 March 2013 - 08:11 PM
I was able to duplicate this problem when my list had 7 items in it, but if I use 6 or 8 it generates a new initial word. It always generates new random second words, so it seems that the random seed is always generating a first random number that % 7 == 3.
dictionary.txt:
My advice would be to generate a random number right after using srand() but not use it, as below:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ()
{
string word[40437];
ifstream list("dictionary.txt");
srand((unsigned int)time(NULL));
int n = 0;
while(n < 40437 && list >> word[n])
{
n++;
}
int r;
int test = rand();
//cout << rand() << endl;
r = test % n;
cout <<test << " " << n << " " << r << "\nword: " << word[r] << '\n';
r = rand() % n;
cout << "word: " << word[r] << '\n';
}
dictionary.txt:
a b c d e f g
My advice would be to generate a random number right after using srand() but not use it, as below:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ()
{
string word[40437];
ifstream list("dictionary.txt");
srand((unsigned int)time(NULL));
rand();
int n = 0;
while(n < 40437 && list >> word[n])
{
n++;
}
int r;
int test = rand();
//cout << rand() << endl;
r = test % n;
cout <<test << " " << n << " " << r << "\nword: " << word[r] << '\n';
r = rand() % n;
cout << "word: " << word[r] << '\n';
}
#3
Re: Easy randomizer issue
Posted 18 March 2013 - 06:12 PM
thank you so much for helping!!! I really appreciate you taking your time to help. Sorry I didnt react sooner
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|