所以这是一个面试问题。
提供了一个函数rand5(),该函数生成范围为[0-5]的随机整数,即{0,1,2,3,4,5}
a)您可以使用该函数生成范围为[0-7]的随机整数吗?
b)您可以使用该函数生成范围为[0-7]的随机整数,每个数字具有相等的概率吗?
您可以多次使用该功能。
a部分的解决方案之一,((rand5() +rand5())*7)//10其中// represents integer division的范围为[0-7],但是概率不相等。
希望看到您的答案和思考过程。
$one = rand5();
$two = rand5();
$four = rand5();
return (($four < 3)? 4 : 0) + (($two < 3)? 2 : 0) + ($one < 3)? 1 : 0);
Run Code Online (Sandbox Code Playgroud)