Home > front end >  How to generate random numbers without duplicates
How to generate random numbers without duplicates

Time:10-05

Simple Question:

I want to generate random numbers from 1 to 15 including 15, but I keep getting duplicates in the resulting serie.

I want to be able to get a random order of every number from 1 to 15. In the Delphi programming language.

CodePudding user response:

That (as mentioned in comments) is easily achieved using the Fisher-Yates algorithm:

TYPE TIntArr = TArray<Integer>;

FUNCTION RandomList(Min,Max : Integer) : TIntArr;
  VAR
    I,J,K : Integer;

  BEGIN
    SetLength(Result,SUCC(Max-Min));
    FOR I:=Min TO Max DO Result[I-Min LOW(Result)]:=I;
    FOR I:=HIGH(Result) DOWNTO SUCC(LOW(Result)) DO BEGIN
      J:=RANDOM(I);
      K:=Result[I]; Result[I]:=Result[J]; Result[J]:=K
    END
  END;

The above function will give you a dynamic integer array containing a random order of numbers between Min and Max (both inclusive).

Remember to call RANDOMIZE in your main form's FormCreate to initialize the PRNG (Pseudo-Random Number Generator) to a fairly random value. If you don't, you'll get the same list returned every time...

  • Related