#!/usr/bin/env python import os, random def readpuzzle(): "Returns a random puzzle from Gordon Royle's list of minimum sudoku." filename = '/home/davidbau/public_html/sudoku/sudoku17' desc = file(filename) linelen = len(desc.readline()) or 82 filesize = os.stat(filename)[6] desc.seek(random.randrange(filesize // linelen) * linelen) line = desc.readline() while len(line) != linelen: line = desc.readline() return [int(x) for x in line.strip()] def blockrandom(): "Returns a random permutation of range(8) keeping blocks of 3 together." o = random.sample([random.sample(x, 3) for x in [[0,1,2], [3,4,5], [6,7,8]]], 3) return [item for sublist in o for item in sublist] def permuted(puzzle): "Returns a randomly permuted equivalent puzzle." rows, cols = blockrandom(), blockrandom() puzzle = [puzzle[cols[x] + 9 * rows[y]] for x in xrange(9) for y in xrange(9)] if random.randint(0, 1): puzzle = [puzzle[y + x * 9] for x in xrange(9) for y in xrange(9)] return puzzle def substituted(puzzle): "Returns a equivalent puzzle with randomly substituted numbers." num = [0] + random.sample(xrange(1, 10), 9) return [num[puzzle[x]] for x in xrange(len(puzzle))] puzzlestring = ''.join([str(n) for n in substituted(permuted(readpuzzle()))]) pathinfo = os.getenv('REQUEST_URI') or '' pdf = pathinfo.endswith('pdf') if pdf: print "Location: http://davidbau.com/generated/sudoku.pdf?" + puzzlestring else: print "Location: http://davidbau.com/sudoku/#" + puzzlestring print