Random Number

Discussion in 'Mac Programming' started by larswik, Aug 17, 2010.

  1. larswik macrumors 68000

    Sep 8, 2006
    If I write...

    guess = arc4random() %3;

    Will it select 0,1,2,3 or will it just pick 0,1,2?

    I did test this but since the number is random I thought I would check.

  2. Hansr macrumors 6502a

    Apr 1, 2007
    You'll get 0,1,2 not 3 since it's essentially from 0 to x-1 where x is the modulus number.
  3. larswik thread starter macrumors 68000

    Sep 8, 2006
    That is what I thought but not 100% sure.


  4. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    You already got your answer, but don't seem to know what modulus is doing. It is the remainder of integer division of the left operand by the right operand. Knowing this, it's obvious that you'll never get the right hand operand as a result.

  5. larswik thread starter macrumors 68000

    Sep 8, 2006
    Lee.... I did know what modulus was. I covered that in the book a few weeks ago and use it to find Prime numbers. That begin said, I did miss the % in this line of code and it's meaning.

    Now that being said, I am confused why you need the Modulus to find the remainder when you are trying to get a random number? When I learned Python it was simple "random.randrange(1,10)"

    So why do you need to use the Modulus? and how then would you select a random number from say 5 to 10?

    Thanks again for pointing that out Lee so I can understand it.

  6. lloyddean macrumors 6502a

    May 10, 2009
    Des Moines, WA
    One of many possibilities include

    u_int64_t random_in_range(u_int32_t low, u_int32_t high)
        return (low + (arc4random() % (high - low)));

Share This Page