Jose Martinez
Jose Martinez

Reputation: 313

generate three characters in console delphi

Some time ago I had helped make a program that generated three different letters, the problem is that when I use visual form goes well but when I use it in a program console program always generates the 3 letters equal in this case I always returns AAW

Code.

program Project1;
{$APPTYPE CONSOLE}

uses
  SysUtils;

function gen(): string;

var
  aleatorio: Integer;
  iz: Integer;

var
  finalr: string;
begin

  finalr := '';

  finalr := finalr + Chr(ord('A') + Random(26));
  finalr := finalr + Chr(ord('A') + Random(26));
  finalr := finalr + Chr(ord('A') + Random(26));

  Result := finalr;

end;

begin
  try
    Writeln(gen());
    readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.

What's the problem?

Upvotes: 2

Views: 281

Answers (2)

David Heffernan
David Heffernan

Reputation: 613013

Delphi's random number generator is pseudo-random based on a linear congruential generator. Such generators produce deterministic output. When you start from the same state, or seed, the same series of values will be generated. Unless you supply a seed, a default seed is used. This explains why repeated runs give identical output - the RNG starts with the same seed each time you run.

To deal with this you should give the RNG a different seed for each run. For instance, simply add a call to Randomize at the start of your program. This will seed the RNG based on the system time. This is not always the best way to seed an RNG, but it may well be sufficient for your needs.

When should you seed your RNG? Usually you seed it once at process start and that's it. You deviate from that policy when you need to reproduce pseudo-random sequences. In other words, there are scenarios when you actually desire the behaviour that you observed. In such scenarios you need to capture the state of the RNG and then every time you need to reproduce a particular sequence, you restore that state.

Upvotes: 3

Sertac Akyuz
Sertac Akyuz

Reputation: 54812

Forgetting to call Randomize

begin
  try
    Randomize;
    Writeln(gen());
    ..

Upvotes: 10

Related Questions