Thread: how to: Non repeated random #s

  1. #1
    Registered User
    Join Date
    Mar 2006

    Angry how to: Non repeated random #s

    I am trying to generate random numbers to fill in a 2-D array but they can not repeat within the array

    for example I have a 10*10 array and i want to fill array with 1-100 randomly, without repeating elements (So I will have to use all 1-100#s)

    Please can anybody help

  2. #2
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Cambridge, UK
    well, u got have a if statmnet in between to check that it don't repeat again. thats the only way u can do that. make sure u call srand() fucntion before calling the random() fucntion. otherwise u get the same sequence of numbers all the time where u call it.


  3. #3
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Banks of the River Styx
    Here's what I did with my calculator:

    Make a list of your numbers, 1-100, in order. Keep a number that says how many are in that list, I'll call it 'ltotal'. Set ltotal to 100 to start with. Now, loop through your array in order, like myarray[0][0], myarray[0][1], etc. For each space in that array, generate a random number from 0 to ltotal - 1. (_not_ from 1 to 100) Use the random number you've just got as an index to select a number out of your list, like ordered_numbers[random_number(0, ltotal - 1)]. Save that number to the 2D array. Then, swap that number with the number at the end of the list. Shrink the list (ltotal) by 1. Repeat.

    Essentially, your picking a number from a list of 1 - 100 at random, swapping it with the last item, and shrinking the list. (To remove the number you just picked from the list) (Since there is no point in keeping the list in order.) This keeps you from checking if you've already generated the number, since you haven't.

    Hope that helps!
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lesson #3 - Math
    By oval in forum C# Programming
    Replies: 2
    Last Post: 04-27-2006, 08:16 AM
  2. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  3. How do I restart a random number sequence.
    By jeffski in forum C Programming
    Replies: 6
    Last Post: 05-29-2003, 02:40 PM
  4. repeated random
    By xdeath in forum C++ Programming
    Replies: 5
    Last Post: 04-10-2003, 03:52 PM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 04:11 PM