Ruby - Picking an element in an array with 50% chance for a[0], 25% chance for a[1]

大城市里の小女人 提交于 2019-12-05 20:08:39

First guess...pick a random number between 1 and 2**size, find the log base 2 of that, and pick the number that many elements from the end.

Forgive my horrible ruby skillz.

return a[-((Math.log(rand(2**size-1)+1) / Math.log(2)).floor) - 1]

if rand returns 0, the last element should be chosen. 1 or 2, the next to last. 3, 4, 5, or 6, third from the end. Etc. Assuming an even distribution of random numbers, each element has twice as much chance of being picked as the one after it.

Edit: Actually, it seems there's a log2 function, so we don't have to do the log/log(2) thing.

return a[-(Math.log2(rand(2**size - 1)+1).floor) - 1]

You may be able to get rid of those log calls altogether like

return a[-((rand(2**size-1)+1).to_s(2).length)]

But you're creating an extra String. Not sure whether that's better than complicated math. :)

Edit: Actually, if you're going to go the string route, you can get rid of the +1 and -1 altogether. It'd make the probabilities more accurate, as the last two elements should have an equal chance of being chosen. (If the next-to-last value isn't chosen, the last value would always be.)

Edit: We could also turn the ** into a bit shift, which should be a little faster (unless Ruby was smart enough to do that already).

return a[-(rand(1<<size).to_s(2).length)]

A non-smart, simple way is:

def coin_toss( arr )
  arr.detect{ rand(2) == 0 } || arr.last
end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!