Reputation: 23780
I want to write a code that generates an array of random integers in Java which should hold 256 integers and where the values of integers are somewhere between 0 - 512(It could be 0 - 256 or 0 - 1024 but not 0 - 1 million something.. ) . However, every time I run this code, I should get the same randomized array.
This is what I have:
int k = 256;
for(int t=0;t<k;t++){
Random rn = new Random(t);
int randomNumber = rn.nextInt();
arrayToBeSorted[t] = randomNumber;
}
However, this gives me values like:
-1155484576 -1155869325 -1154715079 -1155099828 -1157023572
which I do not like at all.
So I change my code to this: ( I add k*2 as a paramter to nextInt method )
for(int t=0;t<k;t++){
Random rn = new Random(t);
int randomNumber = rn.nextInt(k*2);
arrayToBeSorted[t] = randomNumber;
}
And now this is what I get:
374 374 374 374 374 374 374 374 373 373 373 373 373 373 373 373 374 374 375 375 374 374 374 374 374 374 374 374 374 374 374 374 372 372 372 372 372 372 372 372 372 372 372 372 372 372 372 372 373 373 373 373 373 373 373 373 373 373 373 373 372 372 373 373 371 371 371 371 371 371 371 371 370 370 371 370 370 370 370 370 372 372 372 372 371 371 371 371 371 371 371 371 371 371 371 371 369 369 369 369 369 369 369 369 369 369 369 369 369 369 369 369 370 370 370 370 370 370 370 370 370 370 370 370 370 369 370 370 380 380 380 380 379 379 380 379 379 379 379 379 379 379 379 379 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 378 378 378 378 378 378 378 378 378 378 378 378 378 378 378 378 379 379 379 379 379 379 379 379 379 378 379 379 378 378 378 378 377 377 377 377 377 376 377 377 376 376 376 376 376 376 376 376 377 377 378 377 377 377 377 377 377 377 377 377 377 377 377 377 375 375 375 375 375 375 375 375 375 375 375 375 375 375 375 375 376 376 376 376 376 376 376 376 376 376 376 376 375 375 375 375
What I do not like about this is, there are way to many values that are repeating. So what should I do?
*Note: I also need to this 10 times actually. So;
Thank you.
Upvotes: 2
Views: 189
Reputation: 59273
You could do something like this:
int k = 256;
Random rn = new Random(seed); // use a single Random object, you choose a seed
// to get the same sequence, use the same seed
for (int t = 0; t < k; t++) {
// Random rn = new Random(t); // commented out from your original code
// you only need one Random object
int randomNumber = rn.nextInt(256); // 256, or whatever you want the max
// value to be
arrayToBeSorted[t] = randomNumber;
}
Note: I also need to this 10 times actually
Then just repeat the for
loop 10 times, and using the same Random
object, like this:
int k = 256;
Random rn = new Random(seed);
for (int c = 0; c < 10; c++) {
for (int t = 0; t < k; t++) {
int randomNumber = rn.nextInt(256);
someArrayOfTenArrays[c][t] = randomNumber;
}
}
Upvotes: 6