Results 1 to 4 of 4
Thread: Unrepated random numbers
- 12-07-2010, 04:24 AM #1
Member
- Join Date
- Nov 2010
- Posts
- 12
- Rep Power
- 0
Unrepated random numbers
I want to get a randomly sorted list of integers between 0 and n, and I want each value to appear only once. Also, I want it to be performed efficiently -- preferably in O(NlogN) rather than O(N2).
The original idea I had was to create an array of size n, use Random's nextInt(arr.length) to get an index in the array, return the value at that index, and then remove that element from the array (by shifting remaining cells to the left and reducing the array size by one). However, this takes O(N2).
Any suggestion with example code is appreciated.
- 12-07-2010, 04:56 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 18
You don't say it but your algorithm is picking a random index from a range that's getting smaller and smaller as the array elements get chosen.
Java Code:1 2 3 4 5 6 7 8 ^ 3 1 2 4 5 6 7 8 ^ 3 7 1 2 4 5 6 8 ^ 3 6 2 1 4 5 6 8 etc
It's all of those shifts that are taking time and effort. (10 in the example above to get the first three numbers.)
Consider a minor variation without the shifting. (The random index is chosen as before, but now it's swapped with the end of the array)
Java Code:1 2 3 4 5 6 7 8 ^ (swap 3 with end==8) 1 2 8 4 5 6 7 [i]3[/i] ^ (swap 6 with end==7) 1 2 8 4 5 7 [i]6 3[/i] ^ (swap 2 with end==7) 1 7 8 4 5 [i]2 6 3[/i]
It's a standard inplace shuffle as used by java.util
- 12-11-2010, 10:18 PM #3
Member
- Join Date
- Nov 2010
- Posts
- 12
- Rep Power
- 0
Thanks for your reply. I was actually looking for an in-place shuffle. I just didn't know the name of it!
- 12-12-2010, 12:02 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 18
You're welcome. It is also known as a Fisher-Yates shuffle. Wikipedia has an article under that name.
Similar Threads
-
How do I generate random numbers in a certain range using the random class?
By frasifrasi in forum New To JavaReplies: 8Last Post: 04-19-2009, 06:50 PM -
Help with random numbers
By checkmylongboarding in forum New To JavaReplies: 2Last Post: 01-12-2009, 06:47 AM -
Random numbers
By jithan in forum Advanced JavaReplies: 3Last Post: 06-14-2008, 03:04 PM -
random numbers without random class`
By carlos123 in forum New To JavaReplies: 4Last Post: 01-17-2008, 11:44 PM -
random numbers
By carlos123 in forum New To JavaReplies: 1Last Post: 12-22-2007, 03:56 AM
Bookmarks