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,596 questions

55,330 answers

573 users

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

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
    ============================================================
    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 class:
      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.
    ============================================================
*/

public class RandomBinaryMagicSquare {

    // A square is stored as 16 cells in row-major order: index = row*4 + col
    static class Square {
        int[] cells = new int[16];
    }

    // Builds a 4×4 square from a 16-bit mask
    static Square buildSquareFromMask(int mask) {
        Square sq = new Square();
        for (int i = 0; i < 16; i++) {
            sq.cells[i] = (mask >> i) & 1;
        }
        return sq;
    }

    // Checks whether a square is magic
    static boolean isMagic(Square sq, int[] magicSumOut) {
        int[] rowSum = new int[4];
        int[] colSum = new int[4];
        int mainDiag = 0;
        int antiDiag = 0;

        // Compute row sums, column sums, and diagonals
        for (int r = 0; r < 4; r++) {
            for (int c = 0; c < 4; c++) {
                int v = sq.cells[r * 4 + c];
                rowSum[r] += v;
                colSum[c] += v;

                if (r == c) mainDiag += v;
                if (r == 3 - c) antiDiag += v;
            }
        }

        int magicSum = rowSum[0];
        magicSumOut[0] = magicSum;

        // All rows must match the magic sum
        for (int r = 0; r < 4; r++)
            if (rowSum[r] != magicSum) return false;

        // All columns must match the magic sum
        for (int c = 0; c < 4; c++)
            if (colSum[c] != magicSum) return false;

        // Both diagonals must match the magic sum
        return mainDiag == magicSum && antiDiag == magicSum;
    }

    // Scans all 65,536 possible 4×4 binary grids and collects the magic ones
    static List<Square> collectAllMagicSquares() {
        List<Square> results = new ArrayList<>(4096);

        for (int mask = 0; mask < 65536; mask++) {
            Square sq = buildSquareFromMask(mask);
            int[] sum = new int[1];
            if (isMagic(sq, sum)) {
                results.add(sq);
            }
        }

        return results;
    }

    // Prints a square in a readable grid layout
    static void printSquare(Square sq) {
        int[] sum = new int[1];
        isMagic(sq, sum);

        for (int r = 0; r < 4; r++) {
            for (int c = 0; c < 4; c++) {
                System.out.print(sq.cells[r * 4 + c] + " ");
            }
            System.out.println();
        }

        System.out.println("Magic sum: " + sum[0]);
    }

    public static void main(String[] args) {
        // Step 1: collect all valid magic squares
        List<Square> allMagicSquares = collectAllMagicSquares();

        if (allMagicSquares.isEmpty()) {
            System.out.println("No magic squares found.");
            return;
        }

        // Step 2: pick one uniformly at random
        Random rng = new Random();
        Square chosen = allMagicSquares.get(rng.nextInt(allMagicSquares.size()));

        System.out.println("Found " + allMagicSquares.size() + " valid 4×4 binary magic squares.");
        System.out.println("Randomly selected one:\n");

        printSquare(chosen);
    }
}



/*
run:

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

1 0 1 1 
1 1 1 0 
1 1 0 1 
0 1 1 1 
Magic sum: 3

*/

 



answered 1 day ago by avibootz

Related questions

...