How to prevent random #'s from being re-generated

Discussion in 'Trading Software' started by bungrider, Oct 30, 2003.

  1. Hi all,

    I'm writing code to generate a small number of random integers between 1 and 10 using C#'s Random.Next function, and I do not want each number called more than once.

    I can't find anything in the literature about how to prevent the random function from repeating a number.

    Should I work around it by doing something like putting each number in an array and checking to see if the number has already been stored in the array??

    Thanks in advance,
    -b
     
  2. I dont believe the function itself has that capability. After all it is generating a random number (which certainly can duplicate themselves). Why not just generate the random number and create an array of the unique numbers generated after the fact (disregarding any number that you've already encountered).
     
  3. "Should I work around it by doing something like putting each number in an array and checking to see if the number has already been stored in the array??"


    YES.


    Or you could try the reverse approach.

    Put the numbers 1 through 10 into a list.

    Then call the random function and remove the number
    in the list which occupies space # ( nextRandomNumber % lengthOfTheList ).

    Pseudo code below:

    list = (1,2,3,4,5,6,7,8,9,10); // list of the numbers 1 thru 10
    nextChoice = list.removeElementAt( abs(rand()) % list.size() )

    ---------------------------------------

    abs = absolute function, since most random function calls also return negative numbers.
    % = the mod operator



    peace

    axeman



     
  4. word.

    thank you gentlemen.

    -b