Random Number

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

  1. larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    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.

    Thanks
     
  2. Hansr macrumors 6502a

    Joined:
    Apr 1, 2007
    #2
    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

    Joined:
    Sep 8, 2006
    #3
    That is what I thought but not 100% sure.

    Thanks!

    -Lars
     
  4. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    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.

    -Lee
     
  5. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #5
    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.

    -Lars
     
  6. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #6
    One of many possibilities include

    Code:
    u_int64_t random_in_range(u_int32_t low, u_int32_t high)
    {
        return (low + (arc4random() % (high - low)));
    }
    
     

Share This Page