Fill array with random number, but elements cannot be duplicated

• 10-02-2010, 09:07 AM
John_shok
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
• 10-02-2010, 09:21 AM
pbrockway2
Quote:

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.
• 10-02-2010, 10:44 AM
JosAH
Quote:

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

kind regards,

Jos
• 10-03-2010, 03:21 AM
John_shok
Thank you Guys- pbrockways2 and Joash...
I had to several hours.. finally i got it to work!! :D
• 10-03-2010, 03:44 AM
pbrockway2
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)?
• 10-03-2010, 08:20 AM
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...
• 10-03-2010, 08:25 AM
JosAH
Quote:

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