Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to generate a series of unique HEX colors in Pascal

1 Answer

0 votes
program UniqueHexColors;

{$mode delphi}{$H+}

{
    Generate unique HEX colors using randomness in Pascal.

    Notes:
    - Randomize ensures different results each run.
    - Random(256) produces values in [0..255].
    - Colors are stored in an array of fixed-length strings.
    - Duplicate checking is done with a simple loop.
}

uses
    SysUtils; // IntToHex

const
    MAX_COLORS = 12;

type
    THexColor = string[7];  { "#RRGGBB" }

{ Convert an integer (0–255) to a two-digit HEX string. }
function ToHex(Value: Integer): string;
begin
    Result := LowerCase(IntToHex(Value, 2));
end;

{ Check if a HEX color already exists in the array. }
function Exists(const Colors: array of THexColor; Count: Integer; const Hex: THexColor): Boolean;
var
    i: Integer;
begin
    Result := False;
    for i := 0 to Count - 1 do
        if Colors[i] = Hex then
        begin
            Result := True;
            Exit;
        end;
end;

{ Generate N unique random HEX colors. }
procedure GenerateRandomUniqueHexColors(var Colors: array of THexColor; Count: Integer);
var
    Generated: Integer;
    R, G, B: Integer;
    Hex: THexColor;
begin
    Generated := 0;

    while Generated < Count do
    begin
        R := Random(256);
        G := Random(256);
        B := Random(256);

        Hex := '#' + ToHex(R) + ToHex(G) + ToHex(B);

        if not Exists(Colors, Generated, Hex) then
        begin
            Colors[Generated] := Hex;
            Inc(Generated);
        end;
    end;
end;

var
    Colors: array[0..MAX_COLORS - 1] of THexColor;
    i: Integer;

begin
    Randomize;  { different results each run }

    GenerateRandomUniqueHexColors(Colors, MAX_COLORS);

    WriteLn('Generated HEX colors:');
    for i := 0 to MAX_COLORS - 1 do
        WriteLn(Colors[i]);
end.


{
run:

Generated HEX colors:
#1d8f81
#4b340d
#dd3ed8
#bdabdd
#744a73
#28ea48
#eaaa41
#044feb
#9beb66
#b2ecd4
#776b8a
#2a9623

}

 



answered Aug 23 by avibootz
...