Skyscrapers puzzle generator in Python: the edge numbers are rarely enough
All 20 edge numbers of a 5 x 5 skyscrapers grid fix the answer for only 42 % of grids, and only 8 % of our random 6 x 6 grids. A generator then has to print some heights. Printing one where two answers differ needs about a third as many as printing random ones.
A skyscrapers puzzle is a Latin square of building heights: in an n x n grid, every row and column holds the heights 1 to n once. Numbers on the four edges say how many buildings you see from that side, since a taller building hides every shorter one behind it. A row 2 1 4 3 5 shows 3 buildings from the left (2, 4 and 5) and 1 from the right. Some puzzles also print a few heights in the grid.
A Python generator draws a Latin square, works out its edge numbers, and then has to answer one question: do those numbers allow exactly one grid? On 1 November 2026 we measured that at 5 x 5, 6 x 6 and 7 x 7, the sizes of our easy, medium and hard books.
The short version#
- The edge numbers alone are rarely enough. We listed all 161,280 Latin squares of size 5 and grouped them by their 20 edge numbers: only 42 % of them have edge numbers that no other square shares. On random grids: one answer from the edge numbers alone in 45 % at 5 x 5, 8 % at 6 x 6 and 0 of 60 at 7 x 7.
- So the generator prints some heights. Random squares needed 4.9 heights on average at 5 x 5 to settle the answer, 8.8 at 6 x 6 and 15.1 at 7 x 7. Heights printed where two answers differ: 1.5, 2.9 and 5.7.
- Then most edge numbers can go: removing them one by one, as long as the answer stays unique, left 6.5 of 20 at 5 x 5, 9.3 of 24 at 6 x 6 and 11.7 of 28 at 7 x 7.
- The check is fast: 1 ms on a median 5 x 5 grid, 9 ms at 6 x 6 and 67 ms at 7 x 7.
The code#
latin_square() comes from our futoshiki generator.
import random
from itertools import permutations
from futoshiki import latin_square # from our futoshiki generator post
def seen(line):
"""Buildings seen from the start of the line: each one taller than all before it."""
count, tallest = 0, 0
for h in line:
if h > tallest:
count, tallest = count + 1, h
return count
def edges(square):
"""All 4 n edge numbers: ('top', c), ('bottom', c), ('left', r), ('right', r)."""
n = len(square)
cols = [[square[r][c] for r in range(n)] for c in range(n)]
out = {}
for i in range(n):
out["top", i], out["bottom", i] = seen(cols[i]), seen(cols[i][::-1])
out["left", i], out["right", i] = seen(square[i]), seen(square[i][::-1])
return out
def count_answers(n, clues, givens=None, stop=2, keep=None):
"""How many grids fit the edge numbers and starting heights (stops at `stop`; grids found go into `keep`).
Every row and column keeps only the orders of its heights that its own edge numbers and heights allow; then
lines drop orders that clash with the squares' remaining heights, until nothing changes; then guess the line
with the fewest orders left."""
givens = givens or {}
orders = list(permutations(range(1, n + 1)))
def fits(order, first, last, cells):
return ((first is None or seen(order) == first) and (last is None or seen(order[::-1]) == last)
and all(givens.get(cell) in (None, h) for cell, h in zip(cells, order)))
lines = []
for i in range(n):
row, col = [(i, c) for c in range(n)], [(r, i) for r in range(n)]
lines.append((row, [o for o in orders if fits(o, clues.get(("left", i)), clues.get(("right", i)), row)]))
lines.append((col, [o for o in orders if fits(o, clues.get(("top", i)), clues.get(("bottom", i)), col)]))
found = [0]
def go(lines):
while True:
can = {}
for cells, opts in lines:
for k, cell in enumerate(cells):
heights = {o[k] for o in opts}
can[cell] = can.get(cell, heights) & heights
new = [(cells, [o for o in opts if all(o[k] in can[cell] for k, cell in enumerate(cells))])
for cells, opts in lines]
if any(not opts for cells, opts in new):
return False
if sum(map(len, (o for c, o in new))) == sum(map(len, (o for c, o in lines))):
break
lines = new
if all(len(opts) == 1 for cells, opts in lines):
found[0] += 1
if keep is not None:
keep.append({cell: opts[0][k] for cells, opts in lines for k, cell in enumerate(cells)})
return found[0] >= stop
i = min((k for k, (cells, opts) in enumerate(lines) if len(opts) > 1), key=lambda k: len(lines[k][1]))
cells, opts = lines[i]
return any(go(lines[:i] + [(cells, [o])] + lines[i + 1:]) for o in opts)
go(lines)
return found[0]
def make(n, rng=random, most_heights=6):
"""A grid, edge numbers and starting heights with exactly one answer: while the edge numbers allow two grids,
print the height of a square where those two differ; then take edge numbers away in random order while the
answer stays unique."""
square = latin_square(n, rng)
clues, givens = edges(square), {}
while True:
two = []
if count_answers(n, clues, givens, keep=two) == 1:
break
if len(givens) == most_heights:
return make(n, rng, most_heights) # too many heights needed: a new grid
r, c = rng.choice([cell for cell in two[0] if two[0][cell] != two[1][cell]])
givens[r, c] = square[r][c]
for key in rng.sample(sorted(clues), len(clues)):
keep = clues.pop(key)
if count_answers(n, clues, givens) != 1:
clues[key] = keep
return square, clues, givenssquare, clues, givens = make(5, random.Random(7))
top = " ".join(str(clues.get(("top", c), ".")) for c in range(5))
print(" ", top)
for r in range(5):
row = " ".join(str(givens.get((r, c), ".")) for c in range(5))
print(clues.get(("left", r), "."), " ", row, " ", clues.get(("right", r), "."))
print(" ", " ".join(str(clues.get(("bottom", c), ".")) for c in range(5)))
print("edge numbers:", len(clues), "| starting heights:", len(givens), "| answers:", count_answers(5, clues, givens))It printed a 5 x 5 puzzle with 9 edge numbers and one printed height, a 1 in the middle square, and the counter found exactly one answer. A whole 7 x 7 puzzle took 2.6 s on a median run and kept 11.7 edge numbers and 4.2 heights on average.
Why the counter works line by line#
A row of a 5 x 5 grid has 120 orders of its heights. Its two edge numbers keep only some of them: a 1 puts the tallest building next to that edge, and a 5 puts the whole row in order. count_answers() keeps for every row and column only the orders that fit its own edge numbers and printed heights. A square's possible heights are then those that some order of its row and some order of its column both allow, and orders that need anything else are dropped, again and again until nothing changes. Only then does it guess, on the line with the fewest orders left.
To check it apart from itself, we grouped all 161,280 squares of size 5 by their edge numbers and compared: on 300 random squares, count_answers() found exactly as many grids as the list held for those edge numbers.
Print the height that splits two answers#
When the edge numbers allow two grids, a random printed height often does not tell them apart, because the two grids agree on most squares. make() asks the counter for the two grids it found and prints the true height of a square where they differ. That rules out at least one of them every time. At 5 x 5 it needed 1.5 heights on average against 4.9 for random squares, and at most 5 against 15.
Keep every edge number if you like#
make() ends by taking away every edge number it can, which gives the fewest clues. If you want all edge numbers on the page, skip that last loop: the printed heights alone already make the answer unique.
Books#
Our skyscrapers book maker checks every puzzle twice: a separate search, apart from the steps that make the puzzles, finds exactly one finished grid for its edge numbers and starting heights, and each puzzle is solved again step by step with no guessing. Easy books use 5 x 5 grids with all 20 edge numbers shown, medium 6 x 6 with at least 18 of 24, hard 7 x 7 with at least 21 of 28, and the book is checked against KDP's paperback specs before you can download it. One skyscrapers book costs 500 credits, from $3.30 in the big pack.
written
7 min readJigsaw sudoku generator in Python: odd shapes need fewer digits
The same generator that leaves 24 starting digits in a plain sudoku left 17 when the boxes became irregular shapes. The catch: for some shapes the search found no grid at all, and making a puzzle took over 100 times longer.
5 min readFill-in puzzle generator in Python: why one word starts in place
We built 500 fill-in grids from 60 Christmas themes. Without a word printed in place, 22 to 29 % could be filled in two ways, with HOPE and LOVE trading places. One starting word fixes almost all of them.
5 min readKDP margins and gutter: check your PDF before you upload it
KDP's inside margin grows with the page count, and a book of 151 pages needs more than one of 150. The table from KDP's help, and forty lines of Python that find the text too close to an edge.