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

前端 未结 30 3189
一个人的身影
一个人的身影 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:27

    Why not do it simple?

    int random7() {
      return random5() + (random5() % 3);
    }
    

    The chances of getting 1 and 7 in this solution is lower due to the modulo, however, if you just want a quick and readable solution, this is the way to go.

提交回复
热议问题