• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

Dealing with random numbers and arrays in Java


I am creating a program that generates 6 random numbers between 1 and 48; however, the 6 numbers must not match.  For example (4, 26, 5, 9, 47, 2);

I had success in generating random numbers, but at times my numbers would come out matching like so ( 4, 34, 5, 4, 32, 1).  In C programming I know you could simply use "srand(Time(NULL))" to eradicate this problem, but in Java I can't find a way to do this.  I want to avoid using many if statements.  

I was told to use two for loops, first one to generate my numbers, and the second one to check them.  My numbers are stored in an array, if that helps.  

If you have any suggestions I would appreciate them.  
0
ocha033
Asked:
ocha033
  • 2
  • 2
1 Solution
 
bobbit31Commented:
easy way:
ArrayList al = new ArrayList();
for (int i=1;i<=48;i++) {
     al.add(new Integer(i));
}
Collections.shuffle(al);
for (int i=1;i<=6;i++) {
     System.out.print(((Integer) al.get(i)).toString() + " ");
}
0
 
bobbit31Commented:
what it does:

loads the numbers from 1 to 48 into an arraylist.
Shuffles the list.
prints out the first 6 items
0
 
CEHJCommented:
That's a good way. You can write

>>System.out.print(((Integer) al.get(i)).toString() + " ");
       
as

>>System.out.print(al.get(i) + " ");
0
 
ocha033Author Commented:
Thanks a lot.  I never would have thought to use an array with all my numbers and then simply displaying some of them.  That comes from the card shuffling programs too.  

Thanks.  
0
 
CEHJCommented:
If you wanted to conserve resources, this redundancy wouldn't be a good thing of course ;-)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now