Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID
Please do not post the same thing multiple times. The board software automatically flags certain posts as needing moderator attention. This happens the most often for new users. I'm pretty sure this is made clear at the time you attempt to post. Posting the same thing over and over again just makes that many more posts the moderators have to weed through later. This makes us sad. Don't make us sad. If your post/thread doesn't appear, just wait a while. Don't post it again. If it hasn't shown up by the next day, then you can try again. I normally go through posts in the mornings, and try to check a few times throughout the day, but I'm not here 24/7. There will typically be a significant delay before posts are approved. Just be patient.

Why are random numbers so freaking difficult?

spuy767spuy767 Posts: 100Registered Users
Why in the hell can't the random number function in XCode work like every other random number function I've used?

I'm writing a game. I need to calculate random numbers every millisecond to calculate deviations from a predefined path. When I used every random number function in the cocoa library, i always get the same numbers no matter when or how I run the app. I've tried making my own random numbers by manipulating the various NSCalendarDate references. I've tried to seed srand() and srandom()with the date, but I always get a improper use of void something or other error. It's really starting to make me angry that I can write complex graphical apps and animations with no problem but a random number generator effectively kicks my butt. Maybe I'm missing something extremely simple.
Post edited by spuy767 on
«1

Replies

  • GrouchoGroucho Posts: 161Registered Users
    I use random(). I'm pretty sure it's still pseudo-random, but works for what I need. If you want a value between 0 and a number, just use the modulus (%).


    myNewFavoriteRandomNumber = random() % 50; //random number between 0 & 49

    Hope this helps!
    Bryan Duke

    acceleroto.com


  • spuy767spuy767 Posts: 100Registered Users
    Groucho;15912 said:
    I use random(). I'm pretty sure it's still pseudo-random, but works for what I need. If you want a value between 0 and a number, just use the modulus (%).


    myNewFavoriteRandomNumber = random() % 50; //random number between 0 & 49

    Hope this helps!
    That's what I've been using, and I've been coming up with the exact same numbers no matter what I do every time I run the app.
  • MDMstudiosMDMstudios Posts: 128Registered Users
    spuy767;15914 said:
    That's what I've been using, and I've been coming up with the exact same numbers no matter what I do every time I run the app.
    Use arc4random(), random() is usually used for debugging because it should keep on being the same, but arc4random() will produce a new random number time you use it.
    iphone.MDMstudios@gmail.com




  • spuy767spuy767 Posts: 100Registered Users
    MDMstudios;15915 said:
    Use arc4random(), random() is usually used for debugging because it should keep on being the same, but arc4random() will produce a new random number time you use it.
    I tried that too, and I've ben getting the exact same data sets over and over, but I'm testing every single line of code with traces and I'm going to find out what the heck is going on.
  • spuy767spuy767 Posts: 100Registered Users
    They coud have strived to make it a bit simpler to use, or at least made the documentation more clear.

    NSNUmber *rand1;
    rand1 = [NSNumber numberWithUnsignedInt:arc4random()];

    to set the range:
    fmod([rand1 floatValue], 1000.0); //random number from 0-1000;
  • GrouchoGroucho Posts: 161Registered Users
    Hmmmm...I now have the same comment you did in your original post. :(
    Bryan Duke

    acceleroto.com


  • trappertrapper Posts: 299Registered Users
    Seen this before on another forum - but haven't tried it out myself yet.
    I use these defines for random int's. I call RANDOM_SEED() once in my app, the call something lie RANDOM_INT(1,10) will return a random number between 1 and 10. Works great.


    #define RANDOM_SEED() srandom(time(NULL))
    #define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))
    Let us know how you go
    Black or Red - Possibly the first ever iPhone drinking game! Try it tonight.

    <a href="http://itunes.apple.com/WebObjects/MZStore.woa/
  • dasiendasien Posts: 6New Users
    You need to seed the random number generator first...

    try this..

    srand([[NSDate date] timeIntervalSince1970]);

    then you can call the generator and get different numbers...

    Cheers,
    brian
  • mooman576mooman576 Posts: 1New Users
    a specific set of numbers for game, like 123, to 321, 231, 213, etc.? Thanks.
    dasien;16004 said:
    You need to seed the random number generator first...

    try this..

    srand([[NSDate date] timeIntervalSince1970]);

    then you can call the generator and get different numbers...

    Cheers,
    brian
  • smashersmasher Posts: 3,858Registered Users
    To the original posters from last year: random() always returns the same set of numbers if you don't seed it. arc4random() is easier to use; it seeds itself on the first call. Just use arc4random()%10 to get a number from 0 to 9 inclusive.

    mooman576: Do you have your numbers in some sort of NSarray? Then you can shuffle them by sorting the array, but using a sort function that returns random results. Like this:


    NSArray *sortedArray;
    sortedArray = [anArray sortedArrayUsingFunction:shuffleSort context:NULL];
    The shuffleSort function would look like this:


    //this function gets called by sortedArrayUsingFunction:
    //when sorting the array
    NSInteger shuffleSort(id num1, id num2, void *context){

    int result = arc4random()%3; // pick a number 0,1,2

    if (result==0)
    return NSOrderedAscending;
    if (result==1)
    return NSOrderedDescending

    return NSOrderedSame;
    }
    [IMG]http://a5.mzstatic.com/us/r1000/042/Purple/2d/83/7d/mzm.cimuqibw.75x75-65.jpg[/IMG] <a href="http://itunes.apple.com/us/app/tiny-nightclub/id418478743?mt=8" ta
  • dasiendasien Posts: 6New Users
    mooman576;145814 said:
    a specific set of numbers for game, like 123, to 321, 231, 213, etc.? Thanks.
    Well to do that, you might want to put that list of numbers in an array, then randomize the access to the array, so that you get a different number by its position in the array.. Make sense?

    Cheers,
    brian
  • suejbsuejb Posts: 9New Users
    smasher;145840 said:
    To the original posters from last year: random() always returns the same set of numbers if you don't seed it. arc4random() is easier to use; it seeds itself on the first call. Just use arc4random()%10 to get a number from 0 to 9 inclusive.

    mooman576: Do you have your numbers in some sort of NSarray? Then you can shuffle them by sorting the array, but using a sort function that returns random results. Like this:


    NSArray *sortedArray;
    sortedArray = [anArray sortedArrayUsingFunction:shuffleSort context:NULL];
    The shuffleSort function would look like this:


    //this function gets called by sortedArrayUsingFunction:
    //when sorting the array
    NSInteger shuffleSort(id num1, id num2, void *context){

    int result = arc4random()%3; // pick a number 0,1,2

    if (result==0)
    return NSOrderedAscending;
    if (result==1)
    return NSOrderedDescending

    return NSOrderedSame;
    }
    hi man im trying to do a quiz. my questions are in this array.

    NSArray *quizArray = [[NSArray alloc] initWithObjects:
    @"Question number one? (correct A) ",@"A",@"B",@"C",@"D",@"1",
    @"Question number two? (correct B) ",@"A",@"B",@"C",@"D",@"2",
    @"Question number three? (correct C) ",@"A",@"B",@"C",@"D",@"3",
    @"Question number four? (correct D) ",@"A",@"B",@"C",@"D",@"4",
    @"Question number five? (correct A) ",@"A",@"B",@"C",@"D",@"1",
    nil];
    self.theQuiz = quizArray;
    [quizArray release];

    how can i shuffle this array to get questions everytime with different orders
  • smashersmasher Posts: 3,858Registered Users
    That's not a great way to store you data; as you've seen already it makes it hard to do operations at the question level. You'd be better off with a "Question" object that has properties for the question, answer1, answer2, answer3, and correct. Then you can shuffle an array of those objects with the method above.

    If you really don't want a custom object (even though you really do, trust me) then you could make an array of five arrays - The master array will have five items, each of those items will be an array representing a single question / answer set. Like so:


    NSArray *quizArray = [[NSArray alloc] initWithObjects:

    [NSArray arrayWithObjects: @\"Question number one? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    [NSArray arrayWithObjects: @\"Question number two? (correct B) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"2\", nil],

    [NSArray arrayWithObjects: @\"Question number three? (correct C) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"3\", nil],

    [NSArray arrayWithObjects: @\"Question number four? (correct D) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number five? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    nil];



    You get the idea? Now you can shuffle quizArray using the code above without losing the connection between questions and answers.
    [IMG]http://a5.mzstatic.com/us/r1000/042/Purple/2d/83/7d/mzm.cimuqibw.75x75-65.jpg[/IMG] <a href="http://itunes.apple.com/us/app/tiny-nightclub/id418478743?mt=8" ta
  • suejbsuejb Posts: 9New Users
    smasher;203655 said:
    That's not a great way to store you data; as you've seen already it makes it hard to do operations at the question level. You'd be better off with a "Question" object that has properties for the question, answer1, answer2, answer3, and correct. Then you can shuffle an array of those objects with the method above.

    If you really don't want a custom object (even though you really do, trust me) then you could make an array of five arrays - The master array will have five items, each of those items will be an array representing a single question / answer set. Like so:


    NSArray *quizArray = [[NSArray alloc] initWithObjects:

    [NSArray arrayWithObjects: @\"Question number one? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    [NSArray arrayWithObjects: @\"Question number two? (correct B) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"2\", nil],

    [NSArray arrayWithObjects: @\"Question number three? (correct C) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"3\", nil],

    [NSArray arrayWithObjects: @\"Question number four? (correct D) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number five? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    nil];



    You get the idea? Now you can shuffle quizArray using the code above without losing the connection between questions and answers.
    do you have any msn or yahoo email contact? just want to briefly explain my problem, and i have an idea how to do it but i need help on writing codes. thnx
  • smashersmasher Posts: 3,858Registered Users
    suejb;203665 said:
    do you have any msn or yahoo email contact? just want to briefly explain my problem, and i have an idea how to do it but i need help on writing codes. thnx
    If you post here I'll probably see it and I'll answer - otherwise I'm sure someone else will help out. It's easier than trying to catch me on IM, and I'd rather post answers where everyone can benefit.
    [IMG]http://a5.mzstatic.com/us/r1000/042/Purple/2d/83/7d/mzm.cimuqibw.75x75-65.jpg[/IMG] <a href="http://itunes.apple.com/us/app/tiny-nightclub/id418478743?mt=8" ta
  • suejbsuejb Posts: 9New Users
    smasher;203655 said:
    That's not a great way to store you data; as you've seen already it makes it hard to do operations at the question level. You'd be better off with a "Question" object that has properties for the question, answer1, answer2, answer3, and correct. Then you can shuffle an array of those objects with the method above.

    If you really don't want a custom object (even though you really do, trust me) then you could make an array of five arrays - The master array will have five items, each of those items will be an array representing a single question / answer set. Like so:


    NSArray *quizArray = [[NSArray alloc] initWithObjects:

    [NSArray arrayWithObjects: @\"Question number one? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    [NSArray arrayWithObjects: @\"Question number two? (correct B) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"2\", nil],

    [NSArray arrayWithObjects: @\"Question number three? (correct C) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"3\", nil],

    [NSArray arrayWithObjects: @\"Question number four? (correct D) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number five? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    nil];



    You get the idea? Now you can shuffle quizArray using the code above without losing the connection between questions and answers.
    ok, im trying to explain my problem in details. i have to use this method, because i have written a lot of codes, where from my array get the right answer the question and the four answers. ill describe how it is done:
    example my array is like this:
    "
    NSArray *quizArray = [[NSArray alloc] initWithObjects:
    @"Question number one? (correct A) ",@"A",@"B",@"C",@"D",@"1",
    @"Question number two? (correct B) ",@"A",@"B",@"C",@"D",@"2",
    @"Question number three? (correct C) ",@"A",@"B",@"C",@"D",@"3",
    @"Question number four? (correct D) ",@"A",@"B",@"C",@"D",@"4",
    @"Question number five? (correct A) ",@"A",@"B",@"C",@"D",@"1",
    nil];
    self.theQuiz = quizArray;
    [quizArray release];
    "

    and im describing how the objects are sorted: example
    @"Question number one? (correct A) ",@"A",@"B",@"C",@"D",@"1",
    @"Question number one? (correct A) ",@" - this is the question(the index for this is 0;)
    @"A",@"B",@"C",@"D, - those are choices (the index for this is 1,2,3,4;)
    ",@"1", - this is the right answer (it could be 1,2,3,4 variuosly from the right answer)


    so this is simple done, but i want this array to shuffle resort.
    Is this way possible to be done or i MUST change my way of doing quizarray?
  • smashersmasher Posts: 3,858Registered Users
    All things are possible.

    You could write code to convert your data into my data (an array of arrays,) shuffle that, and convert it back. It seems inefficient and it is -- you're creating a lot of temporary arrays -- but a custom shuffle method is going to use a lot of temporary arrays too.

    A custom shuffle will be a little hairy and hard to debug, but not too bad. Try this. I have not compiled or tested it, sorry.


    NSMutableArray *shuffledArray = [[NSMutableArray alloc] init];

    int numQuestions = [quizArray count]/6;

    for (int i=numQuestions; i>0; i--){
    //get a random question
    NSUInteger random = arc4random()%i;
    NSRange questionRange = NSMakeRange(i*6, 6);
    NSArray *questionItems = [quizArray subarrayWithRange:questionRange];

    //insert into new array, delete from old
    [shuffledArray addObjectsFromArray:questionItems];
    [quizArray removeObjectsInRange:questionRange];
    }



    This assumes that quizArray is a mutable array; if it isn't then make a mutableCopy first and use that as the "old" array. It would also be good style to #define constant instead of using "6" everywhere.

    EDIT: I fixed an error - I had the number of questions wrong. Told you it would be hairy.
    [IMG]http://a5.mzstatic.com/us/r1000/042/Purple/2d/83/7d/mzm.cimuqibw.75x75-65.jpg[/IMG] <a href="http://itunes.apple.com/us/app/tiny-nightclub/id418478743?mt=8" ta
  • Robert PaulsonRobert Paulson Posts: 492Registered Users
    i have to use this method, because i have written a lot of codes, where from my array get the right answer the question and the four answers.
    Of course I don't know about the details of your project but smasher's suggestion would make your code a lot easier to read, maintain, and extend. Maybe it's worth re-writing your code using a custom class. (Just my two cents.)

    Cheers,
    Bob
    We are God’s middle children, according to Tyler Durden, with no special place in history and no special attention.



    Consider saying thanks by buying my app. :]
  • suejbsuejb Posts: 9New Users
    smasher;203655 said:
    That's not a great way to store you data; as you've seen already it makes it hard to do operations at the question level. You'd be better off with a "Question" object that has properties for the question, answer1, answer2, answer3, and correct. Then you can shuffle an array of those objects with the method above.

    If you really don't want a custom object (even though you really do, trust me) then you could make an array of five arrays - The master array will have five items, each of those items will be an array representing a single question / answer set. Like so:


    NSArray *quizArray = [[NSArray alloc] initWithObjects:

    [NSArray arrayWithObjects: @\"Question number one? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    [NSArray arrayWithObjects: @\"Question number two? (correct B) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"2\", nil],

    [NSArray arrayWithObjects: @\"Question number three? (correct C) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"3\", nil],

    [NSArray arrayWithObjects: @\"Question number four? (correct D) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number five? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    nil];



    You get the idea? Now you can shuffle quizArray using the code above without losing the connection between questions and answers.
    Hi smasher, ill give you a simple of my code, and please try to do my array in this form as yours.
    Quiz_Game.zip

    ill wait for an answer. thnx
  • smashersmasher Posts: 3,858Registered Users
    I gave an example of my array format before.



    //in the future it'll be easy to load this format from a plist with
    // NSArray initWithContentsOfFile

    NSArray *quizArray = [[NSArray alloc] initWithObjects:

    [NSArray arrayWithObjects: @\"The Daily Show blah blah blah?\",@\"1994\",@\"1996\",@\"1998\",@\"2001\",@\"2\", nil],

    [NSArray arrayWithObjects: @\"What were the blah blah blah?\", @\"R2D2 and C3PO\", @\"Steve and Earl\", @\"Han and Chewie\", @\"Mickey and Minnie\", @\"1\", nil],

    [NSArray arrayWithObjects: @\"Who was the blah blah blah?\", @\"Cliff\", @\"Sam\", @\"Woody\", @\"Norm\", @\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number four? (correct D) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number five? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    nil];


    Now you can pull an individual question by saying:

    //pull 3rd question
    NSArray *question = [quizArray objectAtIndex:2];


    And you can get the parts of the question like so:

    // Set the question string, and set the buttons the the answers
    NSString *activeQuestion= [question objectAtIndex:0];

    answerOne.title = [question objectAtIndex:1];
    answerTwo.title = [question objectAtIndex:2];
    answerThree.title = [question objectAtIndex:3];
    answerFour.title = [question objectAtIndex:4];

    rightAnswer = [[question objectAtIndex:5] intValue];

    // Set theQuestion label to the active question
    theQuestion.text = activeQuestion;


    Very pretty, right?
    [IMG]http://a5.mzstatic.com/us/r1000/042/Purple/2d/83/7d/mzm.cimuqibw.75x75-65.jpg[/IMG] <a href="http://itunes.apple.com/us/app/tiny-nightclub/id418478743?mt=8" ta
  • suejbsuejb Posts: 9New Users
    smasher;210157 said:
    I gave an example of my array format before.



    //in the future it'll be easy to load this format from a plist with
    // NSArray initWithContentsOfFile

    NSArray *quizArray = [[NSArray alloc] initWithObjects:

    [NSArray arrayWithObjects: @\"The Daily Show blah blah blah?\",@\"1994\",@\"1996\",@\"1998\",@\"2001\",@\"2\", nil],

    [NSArray arrayWithObjects: @\"What were the blah blah blah?\", @\"R2D2 and C3PO\", @\"Steve and Earl\", @\"Han and Chewie\", @\"Mickey and Minnie\", @\"1\", nil],

    [NSArray arrayWithObjects: @\"Who was the blah blah blah?\", @\"Cliff\", @\"Sam\", @\"Woody\", @\"Norm\", @\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number four? (correct D) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"4\", nil],

    [NSArray arrayWithObjects: @\"Question number five? (correct A) \",@\"A\",@\"B\",@\"C\",@\"D\",@\"1\", nil],

    nil];


    Now you can pull an individual question by saying:

    //pull 3rd question
    NSArray *question = [quizArray objectAtIndex:2];


    And you can get the parts of the question like so:

    // Set the question string, and set the buttons the the answers
    NSString *activeQuestion= [question objectAtIndex:0];

    answerOne.title = [question objectAtIndex:1];
    answerTwo.title = [question objectAtIndex:2];
    answerThree.title = [question objectAtIndex:3];
    answerFour.title = [question objectAtIndex:4];

    rightAnswer = [[question objectAtIndex:5] intValue];

    // Set theQuestion label to the active question
    theQuestion.text = activeQuestion;


    Very pretty, right?
    Hi smasher, thnx for replys, one more question. Im done with shufling array but my problem now is that i cant go to next question. please if you have time give me some helpful infos for doing that.
  • smashersmasher Posts: 3,858Registered Users
    suejb;210203 said:
    Hi smasher, thnx for replys, one more question. Im done with shufling array but my problem now is that i cant go to next question. please if you have time give me some helpful infos for doing that.
    You get a question like this, right?


    //get a question from the array
    NSArray *question = [quizArray objectAtIndex:questionNumber];


    then you can move to the next question like so:

    // Go to the next question
    questionNumber = questionNumber + 1;


    You don't need your code for "row" anymore, because we use the questionNumber directly.
    [IMG]http://a5.mzstatic.com/us/r1000/042/Purple/2d/83/7d/mzm.cimuqibw.75x75-65.jpg[/IMG] <a href="http://itunes.apple.com/us/app/tiny-nightclub/id418478743?mt=8" ta
  • suejbsuejb Posts: 9New Users
    smasher;210221 said:
    You get a question like this, right?


    //get a question from the array
    NSArray *question = [quizArray objectAtIndex:questionNumber];


    then you can move to the next question like so:

    // Go to the next question
    questionNumber = questionNumber + 1;


    You don't need your code for "row" anymore, because we use the questionNumber directly.
    it wont work, i dont know why? try to compile it and you will see the problem
  • suejbsuejb Posts: 9New Users
    suejb;210274 said:
    it wont work, i dont know why? try to compile it and you will see the problem
    i Just fixed my problem.
    THNX Smasher
  • Jaxen66Jaxen66 Posts: 85Registered Users
    Hi, i have followed this thread but i just seems to run in circles could anyone of you, who made it work. Make a small tutorial where you show what you have done, even post the source code so i could see what i am doing wrong? :) Thanks.
    Danish dynamite!
Sign In or Register to comment.