Generate a unique code - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Generate a unique code

PhacoidPhacoid Posts: 1Member
Hi all, just registered for this.

As a novice Pascal programmer I would like to generate a unique code within Pascal and put it into an array. The code has to exist out of 4 unique numbers ranging from 0 to 9.

It's easy to generate 4 numbers from 0 to 9 with the Random function but the problem is that a number can only be used once. So for example this would be good:

0 5 9 4

This would be wrong:

0 5 0 5

At first I was thinking along the lines of repeating the Random function until it no longer matches another number. That's very easy for the first two:

[code]a := Random(9)
b := Random(9);
UNTIL b <> a;[/code]
But this won't work for c: I can check to see if c is the same as a and if it is then Randomize again, after randomizing it it hopefully is no longer the same as a but then it's the same as b. Randomizing again might make it the same as a again.

I've tried:

c := Random(9);
UNTIL c <> a AND c <> b;[/code]
But that gives me type mismatch. It *could* be possible with nested If's but that would look like a mess.

Anyone have an idea for a simple solution to this?


  • ShadoWsaZShadoWsaZ Posts: 27Member
    Hi. It is simple when using sets.

    Program may be similar to this:
    program random_array;
    const nia = 4; // numbers in array (max 10)
    type digit = 0..9;
    var arr: array[1..nia] of digit;
    randomed: set of digit;
    i: 1..nia;
    Randomize; // To get different results every time
    randomed := [ ];
    for i := 1 to nia do
    arr[i] := Random(10) // 0..9
    until not (arr[i] in randomed); // if in set then repeat
    randomed := randomed + [arr[i]] // already randomed
    for i := 1 to nia do
    By the way, you get type mismatch "c <> a and c <> b" because "and" operation have a priority, so you have to write "(c <> a) and (c <> b)".
Sign In or Register to comment.