java - Algorithm/function that returns random number in array in O(1) and creates single permutation -
this question has answer here:
- random shuffling of array 18 answers
intro: interview question had couldn't solve. code solution (in language), algorithm/pseudocode great.
the problem: problem designing algorithm solves following problem:
given function int getrand(int x) gets int x , returns int in range 0 x randomly (exclusively -> [0, k) ). each call getrand() performed in o(1) time. given array int[] arr of size k containing integers.
write function getrandunique() when called return random member arr such after k requests have full permutation of members of arr (this means getrandunique() return different member of arr each call). each call getrandunique() has performed in o(1) time.
allowed use/store global variables etc...
e.g.: assume arr = [2, 3, 5 , 1]. call getrandunique() return either 2, 3, 5, 1 in 1/4 probability. consequent call getrandunique() return on of remaining 3 members in 1/3 probability , on...
attempt: solved myself (after trial , error) , posted solution "q&a style". love other possible ideas/solutions. accept solution works correct answer (i don't want accept own)!
question: how can achieved above restrictions?
edit: aware problem corresponds fisher–yates shuffle, though specifications little different/more strict here.
my solution follows:
define
index = 0.call , assign
index = getrand(k)(rememberksize ofarr).swap
arr[index]arr[k].- now call , assign
index = getrand(k-1). can won't indexkagain won't have remove it. - swap
arr[index]arr[k-1] - continue doing until call last
getrand(1).
now have array arr random permutation of requested (don't need additional array).
Comments
Post a Comment