來offer算法旗艦班
rand4生成rand6
給定一個(gè) 0-4隨機(jī)數(shù)生成器 如何生成0-6隨機(jī)數(shù)
這個(gè)題的難點(diǎn)在于如何保證數(shù)字出現(xiàn)的概率都是相等的。
0-6通過對(duì)7取余可以得到,那么就想辦法湊對(duì)7取余的場(chǎng)景。
public class Frequency { ? ?public static int rand7(){ ? ? ? ?while(true){ ? ? ? ? ? ?int num=5*rand5()+rand5();//0-24 ? ? ? ? ? ?if(num<21) ? ? ? ? ? ? ? ?return num % 7; ? ? ? ?} ? ?} }//變形:如果用0-6隨機(jī)生成器生成0-9隨機(jī)數(shù)public class Frequency { ? ?public static int rand10(){ ? ? ? ?while(true){ ? ? ? ? ? ?int num=7*rand7()+rand7(); ? ? ? ? ? ?if(num<41) ? ? ? ? ? ?//排除41-48,因?yàn)樗麄儾荒苌?,會(huì)造成各個(gè)數(shù)字出現(xiàn)的概率不同 ? ? ? ? ? ? ? ?return num % 10; ? ? ? ?} ? ?} }
標(biāo)簽: