Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hanabokuro
Created July 26, 2014 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanabokuro/450513ac2d6ed3e98c62 to your computer and use it in GitHub Desktop.
Save hanabokuro/450513ac2d6ed3e98c62 to your computer and use it in GitHub Desktop.
これだと偏る
#! /usr/bin/env ruby
require 'pp'
def shuffle(array)
i = array.length
while 0 < i
i = i - 1
j = (Random.rand * i).to_i
array[i], array[j] = array[j], array[i]
end
array
end
N = 10
M = 10_000
sum_array = Array.new(N, 0)
M.times do
ret = shuffle((1..N).to_a)
sum_array = sum_array.zip(ret).map { |x,y| x+y}
end
avg = ((1 + N) * N / 2).to_f / N
sum_array.map! {|n| n.to_f / M / avg}
pp sum_array
__END__
[1.0824181818181817,
1.0727454545454547,
1.0495818181818182,
1.0350727272727271,
1.0113454545454545,
0.9922727272727272,
0.9672727272727273,
0.9484727272727272,
0.9301636363636363,
0.9106545454545455]
@hanabokuro
Copy link
Author

#! /usr/bin/env ruby

require 'pp'

def shuffle(array)
  i = array.length
  while 1 < i
    i = i - 1
    j = (Random.rand * (i+1)).to_i
    array[i], array[j] = array[j], array[i]
  end

  array
end

N = 10
M = 10_000

sum_array = Array.new(N, 0)
M.times do
  ret = shuffle((1..N).to_a)
  sum_array = sum_array.zip(ret).map { |x,y| x+y}
end

avg = ((1 + N) * N / 2).to_f / N
sum_array.map! {|n| n.to_f / M / avg}
pp sum_array

__END__

[0.9967636363636363,
 0.9968,
 1.0102363636363636,
 0.9960181818181819,
 0.9953454545454545,
 1.0029272727272727,
 1.0000909090909091,
 0.9993090909090909,
 1.0014727272727273,
 1.0010363636363637]

while loop も一回少なくできる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment