| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

C-ORM: docs, API.

Last 100 entries

The Davalos Affair For Idiots; Not The Onion: Google Fireside Chat w Kissinger; Bicycle Wheels, Inertia, and Energy; Another Tax Fraud; Google's Borg; A Verion That Redirects To Local HTTP Server; Spanish Accents For Idiots; Aluminium Cans; Advice on Spray Painting; Female View of Online Chat From a Male; UX Reading List; S4 Subgroups - Geometric Interpretation; Fucking Email; The SQM Affair For Idiots; Using Kolmogorov Complexity; Oblique Strategies in bash; Curses Tools; Markov Chain Monte Carlo Without all the Bullshit; Email Para Matias Godoy Mercado; The Penta Affair For Idiots; Example Code To Create numpy Array in C; Good Article on Bias in Graphic Design (NYTimes); Do You Backup github?; Data Mining Books; SimpleDateFormat should be synchronized; British Words; Chinese Govt Intercepts External Web To DDOS github; Numbering Permutations; Teenage Engineering - Low Price Synths; GCHQ Can Do Whatever It Wants; Dublinesque; A Cryptographic SAT Solver; Security Challenges; Word Lists for Crosswords; 3D Printing and Speaker Design; Searchable Snowden Archive; XCode Backdoored; Derived Apps Have Malware (CIA); Rowhammer - Hacking Software Via Hardware (DRAM) Bugs; Immutable SQL Database (Kinda); Tor GPS Tracker; That PyCon Dongle Mess...; ASCII Fluid Dynamics; Brandalism; Table of Shifter, Cassette and Derailleur Compatability; Lenovo Demonstrates How Bad HTTPS Is; Telegraph Owned by HSBC; Smaptop - Sunrise (Music); Equation Group (NSA); UK Torture in NI; And - A Natural Extension To Regexps; This Is The Future Of Religion; The Shazam (Music Matching) Algorithm; Tributes To Lesbian Community From AIDS Survivors; Nice Rust Summary; List of Good Fiction Books; Constructing JSON From Postgres (Part 2); Constructing JSON From Postgres (Part 1); Postgres in Docker; Why Poor Places Are More Diverse; Smart Writing on Graceland; Satire in France; Free Speech in France; MTB Cornering - Where Should We Point Our Thrusters?; Secure Secure Shell; Java Generics over Primitives; 2014 (Charlie Brooker); How I am 7; Neural Nets Applied to Go; Programming, Business, Social Contracts; Distributed Systems for Fun and Profit; XML and Scheme; Internet Radio Stations (Curated List); Solid Data About Placebos; Half of Americans Think Climate Change Is a Sign of the Apocalypse; Saturday Surf Sessions With Juvenile Delinquents; Ssh, tty, stdout and stderr; Feathers falling in a vacuum; Santiago 30m Bike Route; Mapa de Ciclovias en Santiago; How Unreliable is UDP?; SE Santiago 20m Bike Route; Cameron's Rap; Configuring libxml with Eclipse; Reducing Combinatorial Complexity With Occam - AI; Sentidos Comunes (Chilean Online Magazine); Hilary Mantel: The Assassination of Margaret Thatcher - August 6th 1983; NSA Interceptng Gmail During Delivery; General IIR Filters; What's happening with Scala?; Interesting (But Largely Illegible) Typeface; Retiring Essentialism; Poorest in UK, Poorest in N Europe; I Want To Be A Redneck!; Reverse Racism; The Lost Art Of Nomography; IBM Data Center (Photo); Interesting Account Of Gamma Hack; The Most Interesting Audiophile In The World; How did the first world war actually end?; Ky - Restaurant Santiago; The Black Dork Lives!

© 2006-2015 Andrew Cooke (site) / post authors (content).

Solving Grid Puzzle in Python

From: andrew cooke <andrew@...>

Date: Thu, 30 Aug 2012 06:22:42 -0400

A neat little puzzle I spent some rainy holiday time on is described at 
http://stackoverflow.com/questions/12177600

[This post has been updated since first posting]

The code below is my final attempt, which solves the puzzle in under 3
secs.  I'm posting it here rather than updating the SO post as it's
more complex and not going to help people trying to understand the
basic idea.

One new feature here is that I restrict the search over all solutions
to a single symmetry (so there are four times as many solutions as
found, which can be generated by flipping the solution vertically,
horizontally, or both).  Finding the best way to enforce this was the
hardest part of the entire problem - I finally hit upon requiring the
largest value to be at a certain corner.

Andrew


#!/usr/bin/python3

nx, ny = 4, 5
values = [1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,35,36,40]
# grid[x][y] so it is a list of columns (prints misleadingly!)
grid = [[0 for _ in range(ny)] for _ in range(nx)]
# cache these to avoid re-calculating
xy_moves = {}
debug = False

def edges(grid, x, y):
    'coordinates of vertical/horizontal neighbours'
    return [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]

def corners(grid, x, y):
    'coordinates of vertical/horizontal neighbours'
    return [(x-1,y-1),(x+1,y-1),(x-1,y+1),(x+1,y+1)]

def inside(coords):
    'filter coordinates inside the grid'
    return ((x, y) for (x, y) in coords 
            if x > -1 and x < nx and y > -1 and y < ny)

def filled(grid, coords):
    'filter coords to give only filled cells'
    return filter(lambda xy: grid[xy[0]][xy[1]], coords)

def count_neighbours(grid, x, y):
    '''use this to find most-constrained location
    including corners makes the global search with symmetry removal slightly
    slower (2m40s v 2m20s), but the (2,2)=10 search faster (2s v 6s),
    presumably because edges alone hits the symmetry test sooner.'''
#    return sum(1 for _ in filled(grid, inside(edges(grid, x, y))))
    return sum(1 for _ in filled(grid, inside(edges(grid, x, y)))) + \
        sum(0.5 for _ in filled(grid, inside(corners(grid, x, y))))

def cluster(grid, depth):
    '''given a certain depth in the search, where should we move next?  
       choose a place with lots of neighbours so that we have good 
       constraints (and so can reject bad moves)'''
    if depth not in xy_moves:
        best, x, y = 0, 0, 0 # default matches symmetry check
        for xx in range(nx):
            for yy in range(ny):
                if not grid[xx][yy]:
                    count = count_neighbours(grid, xx, yy)
                    if count > best:
                        best, x, y = count, xx, yy
        xy_moves[depth] = (x, y)
        if debug: print('next move for %d is %d,%d' % (depth, x, y))
    return xy_moves[depth]

def to_corners(grid, depth):
    '''alternative move sequence, targetting corners first.
    much slower - 110m for all values.'''
    if depth not in xy_moves:
        if depth >= 2*(nx+ny) - 4:
            cluster(grid, depth)
        else:
            d = depth
            if d < nx: xy_moves[depth] = (d, 0)
            else:
                d -= nx
                if d+1 < ny: xy_moves[depth] = (0, 1+d)
                else:
                    d -= ny-1
                    if d+1 < nx: xy_moves[depth] = (1+d, ny-1)
                    else:
                        d -= nx-1
                        xy_moves[depth] = (nx-1, d+1)
            if debug: 
                print('next move for %d is %s' % (depth, xy_moves[depth])) 
    return xy_moves[depth]

def drop_value(value, values):
    'remove value from the values'
    return [v for v in values if v != value]

def copy_grid(grid, x, y, value):
    'copy grid, replacing the value at x,y'
    return [[value if j == y else grid[i][j] for j in range(ny)]
            if x == i else grid[i]
            for i in range(nx)]

def move_ok(grid, x, y, value):
    'are all neighbours multiples?'
    for (xx, yy) in filled(grid, inside(edges(grid, x, y))):
        g = grid[xx][yy]
        if (g > value and g % value) or (g < value and value % g):
            if debug: 
                print('fail: %d at %d,%d in %s' % (value, x, y, grid))
            return False
    return True

def always_ok(grid):
    'dummy test to allow all solutions'
    return True

def check_corners(grid):
    '''remove symmetrically-identical solutions by requiring the largest
    corner to be top right (took a long time to think of this constraint)'''
    return grid[0][0] >= max(grid[0][ny-1], grid[nx-1][0], grid[nx-1][ny-1])

def search(grid, values, next_xy=cluster, symmetry_ok=always_ok, depth=0):
    'search over all values, backtracking on failure'
    if symmetry_ok(grid):
        if values:
            (x, y) = next_xy(grid, depth)
            for value in values:
                if move_ok(grid, x, y, value):
                    if debug: print('add %d to %d,%d' % (value, x, y))
                    for result in search(copy_grid(grid, x, y, value),
                                         drop_value(value, values), 
                                         next_xy, symmetry_ok, depth+1):
                        yield result
        else:
            yield grid


# run the search, knowing that (2,2) (which is (1,1) for zero-indexing)
# has the value 10.
for result in search(copy_grid(grid, 1, 1, 10), drop_value(10, values)):
    print(result)

# how many solutions in total?
xy_moves = {} # reset cache
for (n, solution) in enumerate(search(grid, values, next_xy=to_corners,
for (n, solution) in enumerate(search(grid, values, next_xy=cluster,
                                      symmetry_ok=check_corners)):
    print('%d: %s' % (n, solution))

Comment on this post