Expand a random range from 1–5 to 1–7

前端 未结 30 2835
一个人的身影
一个人的身影 2020-11-22 07:29

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

  1. What is a simple so
30条回答
  •  忘了有多久
    2020-11-22 08:13

    int ans = 0;
    while (ans == 0) 
    {
         for (int i=0; i<3; i++) 
         {
              while ((r = rand5()) == 3){};
              ans += (r < 3) >> i
         }
    }
    

提交回复
热议问题