How to generate random string without repetition in Pascal

1 Answer

0 votes
program RandomStringGenerator;

procedure Swap(var a, b: Char);
var
  temp: Char;
begin
  temp := a;
  a := b;
  b := temp;
end;

function GenerateRandStringWithoutRepetition(size: Integer): string;
const
  characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()';
var
  charArr: array[1..Length(characters)] of Char;
  randString: string;
  i, j: Integer;
begin
  // Populate charArr with characters
  for i := 1 to Length(characters) do
    charArr[i] := characters[i];

  // Shuffle the character array
  for i := Length(characters) downto 2 do
  begin
    j := Random(i) + 1;
    Swap(charArr[i], charArr[j]);  // Corrected Swap function usage
  end;

  // Build the random string from the shuffled array
  randString := '';
  for i := 1 to size do
    randString := randString + charArr[i];

  GenerateRandStringWithoutRepetition := randString;
end;

begin
  Randomize;  // Seed the random number generator
  Writeln(GenerateRandStringWithoutRepetition(10));
end.



(*
run:

k5%oT@1wrK

*)

 



answered Apr 15, 2025 by avibootz
...