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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to generate a random 4×4 binary magic square (using only 0 and 1) in Pascal

1 Answer

0 votes
program RandomBinaryMagicSquare;

{
    ============================================================
    Generate a random 4×4 binary magic square (0/1 only).

    A valid square must satisfy:
      • All rows have the same sum.
      • All columns have the same sum.
      • Both diagonals have that same sum.

    This program:
      1. Represents each 4×4 grid as a 16‑bit integer.
      2. Converts each mask into a 4×4 square.
      3. Checks whether it is magic.
      4. Collects all valid squares.
      5. Chooses one uniformly at random.
    ============================================================
}

type
    TSquare = array[0..15] of Integer;

{ Build a square from a 16‑bit mask }
procedure BuildSquareFromMask(mask: Word; var sq: TSquare);
var
    i: Integer;
begin
    for i := 0 to 15 do
        sq[i] := (mask shr i) and 1;
end;

{ Check whether a square is magic }
function IsMagic(const sq: TSquare; var magicSum: Integer): Boolean;
var
    rowSum, colSum: array[0..3] of Integer;
    r, c, v: Integer;
    mainDiag, antiDiag: Integer;
begin
    for r := 0 to 3 do rowSum[r] := 0;
    for c := 0 to 3 do colSum[c] := 0;

    mainDiag := 0;
    antiDiag := 0;

    for r := 0 to 3 do
        for c := 0 to 3 do
        begin
            v := sq[r * 4 + c];
            rowSum[r] := rowSum[r] + v;
            colSum[c] := colSum[c] + v;

            if r = c then
                mainDiag := mainDiag + v;

            if r = 3 - c then
                antiDiag := antiDiag + v;
        end;

    magicSum := rowSum[0];

    for r := 0 to 3 do
        if rowSum[r] <> magicSum then
        begin
            IsMagic := False;
            Exit;
        end;

    for c := 0 to 3 do
        if colSum[c] <> magicSum then
        begin
            IsMagic := False;
            Exit;
        end;

    IsMagic := (mainDiag = magicSum) and (antiDiag = magicSum);
end;

{ Collect all magic squares }
function CollectAllMagicSquares(var outList: array of TSquare): Integer;
var
    mask: Word;
    sq: TSquare;
    sum: Integer;
    count, i: Integer;
begin
    count := 0;

    for mask := 0 to 65535 do
    begin
        BuildSquareFromMask(mask, sq);
        if IsMagic(sq, sum) then
        begin
            for i := 0 to 15 do
                outList[count][i] := sq[i];
            Inc(count);
        end;
    end;

    CollectAllMagicSquares := count;
end;

{ Print a square }
procedure PrintSquare(const sq: TSquare);
var
    r, c: Integer;
    sum: Integer;
begin
    for r := 0 to 3 do
    begin
        for c := 0 to 3 do
            Write(sq[r * 4 + c], ' ');
        Writeln;
    end;

    IsMagic(sq, sum);
    Writeln('Magic sum: ', sum);
end;

var
    allSquares: array[0..4095] of TSquare;
    count, idx: Integer;

begin
    Randomize;

    count := CollectAllMagicSquares(allSquares);

    if count = 0 then
    begin
        Writeln('No magic squares found.');
        Halt(1);
    end;

    idx := Random(count);

    Writeln('Found ', count, ' valid 4×4 binary magic squares.');
    Writeln('Randomly selected one:');
    Writeln;

    PrintSquare(allSquares[idx]);
end.


{
run:

Found 34 valid 4×4 binary magic squares.
Randomly selected one:

1 1 0 0 
1 0 1 0 
0 1 0 1 
0 0 1 1 
Magic sum: 2

}

 



answered Aug 6 by avibootz

Related questions

...