Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Random numbers from 1-10
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
shalenzi




PostPosted: 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);
}
}
}
Sponsor
Sponsor
Sponsor
sponsor
Panphobia




PostPosted: 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.
Raknarg




PostPosted: 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

code:

for i = 1 to 10:
   array[i] = i

for i in 1 to 10:
   swap array[i] with array[random]


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)
Tony




PostPosted: 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/
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Raknarg




PostPosted: 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
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: