Computer Science Canada Random numbers from 1-10 |
Author: | shalenzi [ Tue Mar 18, 2014 10:44 am ] |
Post subject: | Random numbers from 1-10 |
Could somebody please help me in printing the entire whole numbers ffrom 1-10 randomly. I tried the below code, but its not giving me the entire numbers.Instead getting repeated numbers also in o/p . Please somebody help me ASAP. import java.util.Random; class random { public static void main(String[] args) { Random rn = new Random(); for(int i =0; i <10; i++) { int answer = rn.nextInt(10) + 1; System.out.println(answer); } } } |
Author: | Panphobia [ Tue Mar 18, 2014 11:15 am ] |
Post subject: | RE:Random numbers from 1-10 |
Personally I would store the numbers in an array and then check if they have been generated yet, if yes then keep generating if no stop and add to array. |
Author: | Raknarg [ Tue Mar 18, 2014 11:39 am ] | ||
Post subject: | RE:Random numbers from 1-10 | ||
Even better would be to start with an array from numbers 1 to 10 and just randomly swap them
I wrote a test program, this will randomize an array with an even distribution (the number will be in the right position 10% of the time) |
Author: | Tony [ Tue Mar 18, 2014 1:54 pm ] |
Post subject: | Re: RE:Random numbers from 1-10 |
Raknarg @ Tue Mar 18, 2014 11:39 am wrote: this will randomize an array with an even distribution (the number will be in the right position 10% of the time)
It will not. http://blog.codinghorror.com/the-danger-of-naivete/ |
Author: | Raknarg [ Tue Mar 18, 2014 2:51 pm ] |
Post subject: | RE:Random numbers from 1-10 |
Fair enough, but I tested it out again a little differently and the distribution is still fairly even, with a greater chance of being on it's original section or a couple slots down, and if you go through the list more than once it essentially disappears, although I suppose the Knuth-Fisher-Yates shuffle is still better |