0

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.

jpmarinier
  • 4,427
  • 1
  • 10
  • 23
Danielo16
  • 5
  • 2
  • 2
    How about having all possible elements in an array. [Pick a random element](https://stackoverflow.com/questions/19601262/random-value-in-array-with-delphi) (remember "randomize"), and remove the chosen element from array. – MyICQ Oct 02 '22 at 18:55
  • 7
    Put your numbers into an array. Then shuffle them. https://stackoverflow.com/a/14006825/505088 – David Heffernan Oct 02 '22 at 19:15
  • 1
    Random numbers by definition are random, which means that they can repeat. There's nothing to stop a random number from duplicating, because they're random. Are you talking about shuffling them into a random order instead? – Ken White Oct 03 '22 at 01:05
  • You want a random permutation of the [1..15] interval. This is generally done using some variant of the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). – jpmarinier Oct 03 '22 at 08:49

1 Answers1

1

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...

HeartWare
  • 7,464
  • 2
  • 26
  • 30