# Thread: Fill array with random number, but elements cannot be duplicated

1. Member
Join Date
Oct 2010
Posts
13
Rep Power
0

## Fill array with random number, but elements cannot be duplicated

say we have,
int a[]=int a[5];

how do we fill 5 elements i.e 1,2,3,4,5 randomly in a[i](where i=0..4). using for loop.
example
a[0]=4
a[1]=2;
a[2]=3;
a[3]=5
a[4]=1

I was practicing arrays. I came up with this thought but i couldn't figure it out. I can fill random number using for loop, but random number generates duplicate number.I was trying to figure out without duplicate number..
Thank you

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
how do we fill 5 elements i.e 1,2,3,4,5 randomly in a[i](where i=0..4). using for loop.

What you need is a "plan of attack".

How would you do this by hand? I mean if you had a dice, a piece of paper, and a pencil how would go about generating a sequence of 5 numbers which lacked repetition?

Once you have such a plan try turning each of the steps into Java. If you get stuck, say what you have done and what you are trying to do: ie the plan of attack you are using.

3. Originally Posted by pbrockway2
What you need is a "plan of attack".

kind regards,

Jos

4. Member
Join Date
Oct 2010
Posts
13
Rep Power
0
Thank you Guys- pbrockways2 and Joash...
I had to several hours.. finally i got it to work!! :D

5. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
Well done. Did you try getting random numbers and throwing them away if you have already seen them? Or did you follow Jos' link (which is the way the Java shuffle() method does it)?

6. Member
Join Date
Oct 2010
Posts
13
Rep Power
0
@pbrock: whole day i was thinking about what u said..!! And I couldnt figure it out... So i i followed joash's link... imported Random class,
1. filled the arrays using for loop.. serially
2 used another for loop and used Durstenfeld's algorithm from joash;s link

took me several hours ,, to get the wanted result;
took even more hours too figure out the logic...

7. Originally Posted by John_shok
@pbrock: whole day i was thinking about what u said..!! And I couldnt figure it out... So i i followed joash's link... imported Random class,
1. filled the arrays using for loop.. serially
2 used another for loop and used Durstenfeld's algorithm from joash;s link

took me several hours ,, to get the wanted result;
took even more hours too figure out the logic...
Take a look at your JDK directory; there's a large file named src.zip stored there. Open it and read the file Collections.java and search for the shuffle algorithm. Check your own algorithm against it to see if you implemented it correctly.

kind regards,

Jos

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•