Results 1 to 4 of 4

Thread: Random Number

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2006
    Posts
    208

    Random Number

    Code:
    packet[siz] = (char)(rand()%255);
    I want it to randomise a number between 1-255 that will ALWAYS have atleast a diffrence of 10. So it will NEVER generate a number thats 1-10 above or below the number it generated before.

    e.g: generates 86 the next number has to be below 76 or above 96.

    any help?

  2. #2
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403

    Re: Random Number

    You just need to keep track of the old number, then do something like this:

    Code:
    char new_rand = (old_rand - 20) + rand() % 21
    old_rand = new_rand;
    What I do is subtract 20 from the old value, then add a random number from 0-20 to it. IE, if you generated 10 previously, the new value will be (10-10) + rand(0, 20) => rand(0, 20) and so on.

    hope this helps
    Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Aug 2006
    Posts
    208

    Re: Random Number

    char new_rand = (old_rand - 20) + rand() % 21
    old_rand = new_rand;

    dont understand where i put my int... ***? old_rand? = new_rand?

    packet[siz] = new_rand;

    ?

  4. #4
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403

    Re: Random Number

    In that code "old_rand" is the number you generated previously. new_rand is the number you are generating currently. old_rand = new_rand implies that next time around, this time's number will be the old number.

    Code:
    char new_rand = (old_rand - 20) + rand() % 21
    packet[siz] = new_rand;
    old_rand = new_rand;
    Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width