Ruby - select an element in the array with a probability of 50% for [0], a 25% chance for [1]

Nothing complicated, basically I just want to select an element from the array, as if I were making coins for each index and choosing the index when I first get the head. There are also no goals, this means that I select the last bit.

I came up with the following and wondered if there is a better / more efficient way to do this.

def coin_toss(size)
  random_number = rand(2**size)
  if random_number == 0
    return size-1
  else
    return (0..size-1).detect { |n| random_number[n] == 1 }
  end
end
+3
source share
2 answers

First guess ... choose a random number between 1 and 2**size, find the base 2 of the journal and select the number that remains from the set of elements.

Forgive my terrible ruby ​​skill.

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

rand 0, . 1 2, . 3, 4, 5 6, . .. , .

Edit: , , log2, log/log (2).

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

, ,

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

String. , , .:)

: , , +1 -1. , . ( , .)

Edit: ** -, ( Ruby , ).

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

, :

def coin_toss( arr )
  arr.detect{ rand(2) == 0 } || arr.last
end
+5

All Articles