Problem Statement:
Shuffle Deck of Cards
Solution:
Knuth Shuffle :
In Iteration i, pick Integer 'rand' between 0 and i uniformly at random, swap arr[i] and arr[rand]
Knuth Shuffling algorithm produces a uniformly random permutation of the input array in linear time.
Key Note: Shuffling element should be between 0 to i or between i to N-1 for uniformly random result.
Source Code : LINK
Please comment and post your suggestions.
Happy Coding !! :)
Shuffle Deck of Cards
Solution:
Knuth Shuffle :
In Iteration i, pick Integer 'rand' between 0 and i uniformly at random, swap arr[i] and arr[rand]
Knuth Shuffling algorithm produces a uniformly random permutation of the input array in linear time.
Key Note: Shuffling element should be between 0 to i or between i to N-1 for uniformly random result.
Source Code : LINK
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** * Shuffle subroutine */ public void shuffle(){ Random randomGenerator = new Random(); for(int i=0;i<arr.length;i++){ int rand =randomGenerator.nextInt(i+1); swap(i,rand); } System.out.print("After Shuffling: "); print(); } |
Please comment and post your suggestions.
Happy Coding !! :)
No comments:
Post a Comment