Efficient Generation of Binary Magic Squares
Alain Riou
TL;DR
This work introduces an efficient, provably correct method to generate Binary Magic Squares, i.e. $n\times n$ binary matrices with uniform row and column sums $k$. It develops a column-by-column randomized construction that maintains a per-row invariant and uses a partition-based selection to guarantee exactly $k$ ones per column and per-row sums of $k$, achieving $\mathcal{O}(n^2)$ time. The method extends to non-square $m\times n$ matrices under an am=bn feasibility condition, with a constructive replication approach guided by gcd decompositions. The authors provide open-source Python and PyTorch (GPU) implementations, enabling fast, parallel generation and broad applicability to problems in combinatorial optimization and graph constructions.
Abstract
We propose a simple algorithm for generating Binary Magic Squares (BMS), i.e., square binary matrices where the sum of all rows and all columns are equal. We show by induction that our algorithm always returns valid BMS with optimal theoretical complexity. We then extend our study to non-square Binary Magic Squares, formalize conditions on the sum of rows and columns for these BMS to exist, and show that a slight variant of our first algorithm can generate provably generate them. Finally, we publicly release two implementations of our algorithm as Python packages, including one that can generate several BMS in parallel using GPU acceleration.
