Last active
August 29, 2015 14:01
-
-
Save lbarasti/1625abc54f1b32e45f64 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # in-place shuffle | |
| def wrong_shuffle arr | |
| arr.size.times { | |
| i, j = rand(arr.size), rand(arr.size) | |
| arr[i], arr[j] = arr[j], arr[i] | |
| } | |
| arr | |
| end | |
| # in-place shuffle | |
| def wrong_shuffle2 arr | |
| (1...arr.size).to_a.reverse.each{|i| | |
| j = rand(arr.size) | |
| arr[i], arr[j] = arr[j], arr[i] | |
| } | |
| arr | |
| end | |
| def benchmark(arr,samples,target,&shuffle) | |
| (1..samples).map{ | |
| shuffled = yield arr.clone | |
| shuffled.find_index target | |
| }.group_by{|idx| idx}.map{|idx,l| [idx,l.count]}.sort_by(&:first).each{|a,b|puts [a,'.'*(b*100/samples)].join(': ')} | |
| end | |
| # benchmark((?a..?f).to_a, 10000, ?a, &method(:wrong_shuffle)) | |
| # 0: ....................... | |
| # 1: ............... | |
| # 2: ............... | |
| # 3: ............... | |
| # 4: ............... | |
| # 5: ............... | |
| # => [[0, 23961], [1, 15265], [2, 15048], [3, 15236], [4, 15169], [5, 15321]] | |
| # benchmark((?a..?f).to_a, 10000, ?a, &method(:wrong_shuffle2)) | |
| # 0: ........................................ | |
| # 1: ................ | |
| # 2: ............. | |
| # 3: ........... | |
| # 4: .......... | |
| # 5: ........ | |
| # => [[0, 4012], [1, 1639], [2, 1340], [3, 1149], [4, 1024], [5, 836]] | |
| # fair shuffling algorithm | |
| # benchmark((?a..?f).to_a, 100000, ?a) {|arr| | |
| # (1...arr.size).to_a.reverse.each{|i| j = rand(i+1); arr[i], arr[j] = arr[j], arr[i]} | |
| # arr | |
| # } | |
| # 0: ................ | |
| # 1: ................ | |
| # 2: ................ | |
| # 3: ................ | |
| # 4: ................ | |
| # 5: ................ | |
| # => [[0, 16676], [1, 16577], [2, 16640], [3, 16850], [4, 16732], [5, 16525]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment