Random Integer Generator

Discussion in 'iOS Programming' started by iphoneSDKid, Dec 23, 2009.

  1. iphoneSDKid macrumors newbie

    Joined:
    Dec 23, 2009
    #1
    Hi-
    I need a random number generator that creates numbers between 2 numbers, like 10-20, or 20-30, etc.
    Thanks!
     
  2. gr8tfly macrumors 603

    gr8tfly

    Joined:
    Oct 29, 2006
    Location:
    ~119W 34N
    #2
    You should try Google "random number generator" for something like this, but:

    I don't know Obj-c, but in C++ it would be:

    Code:
    nRandomInteger = (rand() % nMax) + nLower; 
    If nMax = 10 and nLower = 1, you will get a random number between 1 and 10.

    Usually you seed by using
    Code:
    srand((unsigned)time(0));
     
  3. iphoneSDKid thread starter macrumors newbie

    Joined:
    Dec 23, 2009
    #3
    dont get it

    sorry im very new to this where would i seed the number?
     
  4. Matthew Yohe macrumors 68020

    Joined:
    Oct 12, 2006
    #4
    int num = (arc4random() % 10) + 9;

    No seeding required.
     
  5. gr8tfly macrumors 603

    gr8tfly

    Joined:
    Oct 29, 2006
    Location:
    ~119W 34N
    #5
    Anywhere prior to using "rand". Or use the OS-X function arc4random as Matthew Yohe posted (I haven't done much OS-X dev - most of the time I've been developing for the "dark side".)
     
  6. Matthew Yohe macrumors 68020

    Joined:
    Oct 12, 2006
    #6
    Keep in mind that ObjC is a strict superset of C. Whatever works in C works in ObjC.
     
  7. gr8tfly macrumors 603

    gr8tfly

    Joined:
    Oct 29, 2006
    Location:
    ~119W 34N
    #7
    Yep. I was just assuming the OP was learning ObjC. For me (if I ever get around to Mac/iPhone development), I'd probably naturally resist the transition and use C/C++, which I also used for embedded systems. Old habits dying young and all that... ;)
     
  8. iphoneSDKid thread starter macrumors newbie

    Joined:
    Dec 23, 2009
    #8
    i tried that but i still ocasionally get a number below 10
     
  9. Matthew Yohe macrumors 68020

    Joined:
    Oct 12, 2006
    #9
    Yeah, as expected. That range would be 9-18.
     
  10. iphoneSDKid thread starter macrumors newbie

    Joined:
    Dec 23, 2009
    #10
    my bad

    my bad was typing in the wrong view controller lol sry
     

Share This Page