Showing posts with label Puzzles. Show all posts
Showing posts with label Puzzles. Show all posts

Sunday, January 14, 2018

Egressors - those who escape

Charlene and I have really gotten into escape rooms lately.  I mean, really gotten into them.  We did our first room in September of 2016, and since then we've been playing as many as we can.  So far we've done about 26 rooms in 5 states and 3 countries.  If you haven't tried them yet, I just can't recommend them enough.

We started a spreadsheet to track which rooms we've visited, and it wasn't long before I thought there ought to be a website for that.  I've seen at least one (escapetalk.nl), but it's mostly in Dutch and doesn't cover our area.  After a while I decided this was something I could do.  So after a few months of on-and-off coding while the kids were asleep, I'm finally ready to launch:

EGRESSORS.COM
Egressors Logo

Egressors is a directory of escape rooms in the New England area, and a place where you can sign in and track your own escapes.  We're starting simple and planning to build up features over time.  For instance, right now you can track your escapes but you can't see anyone else's.

Fancy graphics.
One of the first updates I plan for the site will be to see how many users have logged plays at each room, and see the escape rates.  I'm holding back on reviews and comments and other judgement-y features at first, because I don't want the site to impact any of the venues in a negative way.

Another early update I hope to include will be a tailored news system - so that users can sign up to hear about new rooms and events, but specifically ones in their area or for rooms they are "watching".  Some rooms have their own mailing lists, but you have to sign up to those one at a time.  There are mailing lists out there for general escape room info, but they don't have any way to filter to local information.

The other escape-room-related project we're working on is a "passport" for rooms in the North Shore area.  There's a great concentration of rooms along I-95 north of Boston, and if other "egressors" are like me, then once you're hooked you want to escape them all.  This passport provides a physical way to track where you've gone, and a goal greater than just one room.

Not valid for travel to foreign countries.
Plus, and of course, there's a puzzle on it.  To solve the puzzle you need to visit enough of the rooms (not necessarily all of them).  Each room will write something different that will get you one step closer to the solution.  Nine venues in the North Shore area have signed up to distribute the passport, all fine places to get out of:
At some point I might add a feature to egressors.com where you can enter the solution to the passport and thus get some internet points.  If the passport goes well I could see expanding it to other areas.

So if you're in New England and like escape rooms, check out the site and consider signing up for an account.  And if you're near the North Shore then keep an eye out for the passport.

Thursday, July 13, 2017

Tower of Hanoi Variations

A long, long time ago (1993) I spent a few weeks at a summer residential governor’s school, hosted by the college of William and Mary.  I remember only fragments of that time:  Playing capture-the-flag across the campus.  Some kind of fancy asteroids game.  Recording professors' answering machine messages and editing them to make them say funny things.

During one programming class, I remember the professor describing a linear congruential generator for pseudorandom numbers.  I thought to myself, "That can't be the best way, I came up with that on my own at home."  Then, being young, I said that out loud.  I think the professor said something to the effect of "Yes, you're very smart, now shut up."

I also remember helping to solve a variation of the Tower of Hanoi, and getting my name in a published paper.

You should already know what the Tower of Hanoi puzzle is.  If not, you know how to use Google: I'm not going to describe it to you here.

You probably didn't need a diagram for how to swap something.
This variation was pretty simple: As in the classic puzzle you can move the smallest disk to any other peg.  But the other disks can only be moved by swapping them with the next-smallest disk (and only when the two swapped disks are at the tops of their stacks).  This variation was introduced in 1944, and as far as Professor Stockmeyer could determine no algorithmic solution had been published (and he has looked around pretty thoroughly).  You can try it out at this demo site I made, by choosing the variation called "Swapping".

I hadn't thought about this for years, and then I go and watch two 3blue1brown videos about the Tower (part 1 and part 2) and the whole thing comes trickling back.

We were given a challenge: if we could produce a correct algorithm to solve this variation, then the professor would put our names on the paper he was going to publish.  It wasn't easy, but after some days we managed to find the solution.  The rest, as they say, is in the International Journal of Computer Mathematics.

Classic Tower of Hanoi solution
The classic Tower has a simple recursive solution:  Consider the biggest disk.  You want to get it from peg A to peg C, so first move everything else off of it and onto peg B.  Now you can move the big one to C, then move everything else from B to C.  The "move everything else" steps are where the recursion comes in, because doing that is just solving the puzzle again but with a slightly smaller tower.

Here's a notation that will help:  We'll list the positions of the disks from biggest to smallest, in a single string.  So we start out at "AAAA..." and we want to end up at "CCCC...".  The classic solution is to first go from AAAA... to ABBB... (by recursion), then to CBBB..., then to CCCC....




There's another variation, mentioned in the 3blue1brown videos, where you can only move disks to the right, except that you can also move a disk from the last peg to the first.  This might be called the Cyclic Tower of Hanoi, and it has a solution that's different from, but similar to, the classic Tower.  The difference is that here you can't just move the big disk from A to C.  It has to go to B first.  So you move everything else to C, move the big disk to B, move everything else to A, move the big disk to C, then move everything else to C.  This involves "move everything else" three times, so overall it takes more moves.  Using our notation, this means we go from AAAA... to ACCC... to BCCC... to BAAA... to CAAA... to CCCC....

Our variation involved swapping, and was a little more complicated.  Suppose we're going to implement a function "solve", which moves a tower from A to C.  To move the big disk to C you can't just get "everything else" out of the way.  You need the second-biggest disk to be on C, for the swap to work.  That is, we need to get from AAAA... to ACBB....  Let's ignore how to do that for a moment, and just say we have a function that does that, called "unfold".  Basically the function "unfold" takes a stack "AAAA..." and moves to "CBBB...", where the biggest disk of that stack is on one peg, and the rest of that stack is on another.  Suppose we also have the reverse function, "fold".


So the overall solution function, "solve", can work by first calling "unfold" to set up the big-disk swap (ACBB...), then doing that swap (CABB...), then calling "fold" to tidy everything up (CCCC...).  This is a good start, but unlike with the classic and cyclic variations, our "unfold" function isn't just a smaller version of the overall solution.  We still need to define it.

To implement "unfold", how do we get from AAAA... to CBBB...?  As before we've got to move the big disk from A to C.  So we start by going from AAAA... to ACBB..., then swap to CABB..., then somehow get from CABB... to CBBB....  The first part is easy, we call "unfold" on the sub-tower.  This last part is new, though.  Now we need some algorithm that can insert a disk underneath a stack.  That is, it needs to get from something like ABBB... to BBBB.... This requires another function, let's call that "insert".  We'll also need "extract", the inverse of this function (so we can implement "fold").


To implement "insert", how do we get from ABBB... to BBBB...?  The big disk needs to get from A to B, so we need to set things up for that swap.  This means we need to go from ABBB... to ABCC..., swap to BACC..., and then go from BACC... to BBBB....  Finally we have all the tools we need:  The first step there is just moving a whole tower (BB... to CC...), which is the "solve" function we're ultimately building.  The last step is "fold" (ACC... to BBB...).

How the five functions call each other.
So our solution involves five functions: "solve", "unfold", "fold", "insert", and "extract".  The paper rigorously describes why this solution is optimal, but I prefer to simply note that there aren't really any other options.  For the implementation of each function, the biggest disk really does need to move to the right place, and it can only get there if every other disk is set up just right.  It seems to me that it's optimal because it only makes necessary moves.

I made a site that demonstrates this and a few other variations of the Tower of Hanoi, at the link below.

Sunday, November 27, 2016

Word Search Generator

Here's a quickly-slapped-together little project that generates word search puzzles.

I've been kicking around an idea for a kind of "evil" word search, in which there are tons of letter combinations that almost spell words, but don't.  The trick would be to see how distracting the almost-words are, and whether that makes the correctly-spelled words harder to find.  That's not what this one is, though.  This one is just a regular, non-evil word search generator.

The core generator code is at this githib repo, or on npm as @sbj42/word-search-generator.

Friday, October 14, 2016

Maze generators

I'm working on another game for the kids, called "Mr. Floppypants", of which I'll say no more in this article, except that I'm using node.js, and that for it I required some code to generate a maze.  For once not wanting to write my own code for that particular subfeature, I searched around npm for "maze generator" packages.  There were a few.

Watch out for bull-men!
I set about looking into each one in turn to see if it would suffice, but I discovered for each one a reason not to use it.  One of them simply didn't run, another used Ecmascript 6 (and so wouldn't work in some browsers without being transpiled), one only worked for square mazes, and some (and I admit I was a bit picky) just weren't written to my taste.  Maze generation is a fun little project, and it's natural that many people have made their own generators, in varying degrees of quality.  Yes, I gave up and wrote my own.

Here's what I learned about mazes... wait, no.  Instead let me point you at some much better sources of information:

Jamis Buck writes a mostly-programming blog, and wrote a great series on maze generators in 2010 and 2011.  This in-browser presentation sums up the whole maze generation concept very nicely, and this recap of the blog series is a great place to get more details.  He describes how to implement a handful of algorithms, and provides in-browser demos so you can watch the algorithm run.

Walter Pullen has such a variety of interests that I refuse to summarize his site, in one part of it you can find a very thorough maze generator program he wrote, and he has written extensively about maze generation.  Also I just can't keep myself from mentioning his extensive files about the movie Labyrinth.

Now you know everything about mazes.  But just in case you didn't spend hours reading through all that stuff, here are some highlights:

A maze is basically equivalent to a spanning tree of a graph based on a rectangular grid.  Consequently, algorithms that compute spanning trees can be adapted to make mazes.  Kruskal's algorithm is like this, and builds mazes in an seemingly magical way:  It connects random adjacent cells, taking care not to create a loop, until a maze basically appears out of the noise.

Speaking of Kruskal's, the hardest part is quickly deciding whether two adjacent cells are already connected.  It can be done with a disjoint-set forest, and the tricks they use to make that fast (union by rank and path compression) are neat.

One of the simplest algorithms, recursive-backtracking, is my pick for making the best-looking mazes.  While generators like Kruskal's tend to make lots of clustered dead-ends, recursive-backtracking prefers meandering passages.  It works as basically a randomized depth-first-search of the grid.

Eller's algorithm can generate the maze one entire row at a time.  It works by keeping track of which cells connected to the previous row have already been connected (possibly by an earlier, now forgotten row).  On the very last row, it patches up any not-yet-connected regions of the maze.  In doing so, it may end up with a long straight passage along the bottom.

The Aldous-Broder algorithm generates all possible mazes with equal probibility, but you probably don't want to use it because it's very slow.  It's interesting to think about though: Start in a random cell and perform the well-named  "drunkard's walk", digging a passage when (and only when) you walk into a cell you've never visited before.  Assuming you have enough patience, you'll eventually visit every cell and oh hey, there's a maze!

It's not a generator, but "dead end filler" is an amusing way to solve some mazes without ever visiting cells in the solution path.  Find all the dead ends in the maze and fill them in.  Then find any new dead ends you created, and fill those in too.  Repeat until there are no more dead ends.  The remaining unfilled spaces are the solution.

Back to my project:  I implemented three algorithms (recursive-backtracking, modified Prim's, and Kruskal's).  I also used this as an opportunity to learn about node and npm, so the algorithm packages also have unit tests, benchmarks, and demos, and I spent some time trying to optimize them for speed and also make them easy to plug in to another project without needing to bring a lot of dependencies along.


@sbj42/maze-generator npm package

Update (10/15): I added a maze "puzzle" to Probably Puzzles.
Update (6/17): Added a link to Mr. Floppypants

Saturday, August 27, 2016

Generating Shikaku-like puzzles

A very small
Shikaku
in progress.
In my last post, I talked about adding Nonograms to Probably Puzzles.  Now let's talk Shikaku.

In Shikaku your task is to divide a grid into rectangular regions, such that every cell is assigned to a region, every region has exactly one number in it, and that number is the area of the region.

This one turned out to be harder to generate than Hidato, though maybe I haven't found the right algorithm.  The first step was to generate a random division of the grid into rectangles (i.e. to generate the solution).  I didn't find a good algorithm for that, so I made up a mediocre one:
  1. Choose a random cell that isn't yet in a rectangle
  2. Randomly decide on a major axis (horizontal or vertical)
  3. See how far we can stretch from that cell along the major axis (e.g. for horizontal we see how many empty cells there are to the left and right)
  4. Choose a random range from that span, with length no greater than 8
  5. See how far a rectangle of that width can go along the minor axis
  6. Choose a random range from that span, no longer than 8, where the rectangle's area is no bigger than 16
  7. If we were able to pick a rectangle bigger than 1x1, then go back to 1 and repeat until all cells are consumed.
  8. If not, then pick a random rectangle adjacent to the cell and remove it, then go back to 1.
That last step was the key to speed.  At first I had it just give up and start over if it hit an isolated cell, but it had to do a lot of resetting before it randomly ended up perfectly dividing the grid.  The last step allows it to make a small adjustment and try from there, rather than losing all the work it put into the earlier rectangles.

A grid, divided.
 This gives us a divided grid.  A solution in search of a problem.  So now we choose a random cell from each rectangle to use as the hint.  Here things get a little tricky.  To make sure there is only one unique solution for a given puzzle, we need to go ahead and solve it.

I wrote a brute force solver, but it was taking far too much time for puzzles of moderately-large size.  One trick I used to speed it up was to do a first pass on each hint, seeing how many possible rectangles could go there at the beginning of the puzzle.  Then we sort the hints from fewest to most possible rectangles, ensuring that we try all the "forced" ones first.

I suspect I can make the solver even faster if I resort at each decision in the solver tree, because placing one rectangle frequently reduces the number of options for another, and I find that for most of the Shikaku I'm generating, every rectangle is forced at some point or another, leaving the best kind of brute-force tree ever: a straight line to the solution.

There was another problem.  Too often the generator would put two 2x1 rectangles next to each other, and too often the hint-picker would select kitty-corner hints from those rectangles, giving the puzzle multiple solutions.
An ambiguous Shikaku.
When this happens, the solver takes longer to run, and in the end we have to throw all that work away because we won't accept a puzzle with multiple solutions.  So I threw in a pass to detect when this was happening and auto-correct it (by moving one of the hints).

That left me with a fast-enough generator and a not-so-fast-but-maybe-ok solver to verify the puzzles.

A generated Shikoku-like puzzle.
For the other puzzle types, I have a feature that allows you to adjust the "difficulty" of the puzzle, but so far I don't have that for Shikaku.  I could go by the number of choices made in the solver (which is what I did for Numbrix and Hidato), or I might even be able to use "number of initially-forced regions".  However I would need to speed up the solver before I attempted that.  At the highest grid-size setting, 15x15, it currently takes a while just to generate one puzzle, and if it started getting picky about difficulty it might take way too long.

Solving in progress.
The UI is pretty straightforward.  You click and drag to make rectangles.  It colors a rectangle red if it's invalid (i.e. if it contains no number, or more than one number, or doesn't have the right area for the number it contains).

Generating Nonograms

In my last post, I discussed a generator for Numbrix-like puzzles.  Since then I've extended Probably Puzzles with three more puzzle types.

Hidato is very similar to Numbrix.  The only difference is that the path can move diagonally.  To get that I had to drop the Hamiltonian path generator I scrounged up, and replace it with one that generalizes to accept the diagonal connections.  The new path generator is based on this stackoverflow answer.  Hidato is interesting, the path can cross itself and that seems to lead to some surprises while I'm solving it.

Another puzzle type I added is Nonogram (a.k.a. "Paint by Numbers", "Griddler", and lots of other names).  This one is the most popular of the ones I've done so far (but will certainly drop to second place if I add Sudoku).  In this puzzle you color in the cells of a grid to draw a "picture".  There are numbers along the left and top of the grid which constrain which cells you can fill in.  They tell you how many sequences there are on each row and column, and the lengths of those sequences, but not exactly where those sequences go.

A randomly-generated 9x9 nonogram.
On the one hand, generating these is easier than Numbrix/Hidato.  We don't need to pick a subset of the hints that leaves the puzzle uniquely solvable, we just need to generate a picture.  The hints are determined directly from that.  On the other hand, how do we generate "a picture"?  I considered pulling from a library of images, or scattering various geometric shapes around, but I though it would be better for this particular site if the puzzles were completely random.  In the end, I decided to use simplex noise, which generates basically a bunch of random blobs.  At low difficulty, you get very big blobs, and a high likelihood that some rows or columns are completely determined by the hints.  At the highest difficulty, each cell is independently random, and it ensures that no rows or columns are completely determined.
Nonogram in progress.
For the play interface, I took some advice from my wife, who is an avid nonogram puzzler.  You left click to fill the cells, and right-click to place little dots in the cells which you can use as a reminder to yourself that you've decided that particular cell must be empty.

The third puzzle type I added was Shikaku, which I'll describe in the next post.


Sunday, August 21, 2016

Generating Numbrix-like Puzzles

Very tiny
Numbrix-like
 example.
We got the kids interested in a simple kind of logic puzzle called Numbrix.  I showed my son a multiplication table and he became obsessed for a time with filling out more and more tables with bigger and bigger numbers.  Since he seemed to like writing numbers into boxes, we looked around for a puzzle we could print off the web that he could do, and found some kids' Numbrix at this "Math in English" site.

Numbrix is apparently a puzzle published in Parade magazine, developed by Marilyn vos Savant, who had the Guinness Book of World Records "Highest IQ" in the late eighties and also a serendipitous surname.  The goal is to complete a Hamiltonian path on a grid with consecutive numbers.  If you've heard of Hidato, it's like that but you can't move diagonally.  The ones at Math in English seem to be randomly generated, but the ones made by vos Savant are cleverly constructed by hand.

Either way, there are a limited number of Numbrices at both places.  I haven't found anything that generates them "while u wait", so I set about writing some code to do that.

A randomly generated Numbrix-like puzzle.
The first step is to generate a random-ish Hamiltonian path.  With a little googling I came across this "HamPath" library, which does the trick well enough.  Next we need to take away random numbers until we have a puzzle we like.  The puzzle has to have a unique solution, so each time we take away a number we have to check to see if there's another solution, so we need a solver.  The solver just runs all the possibilities and stops early if it finds a second solution.

I wanted it to have a difficulty knob, so we need some kind of measurement of difficulty and then we need to make sure when we take a number away we haven't made it too difficult.  I use two measures of difficulty: "choice count" and "stretch".

Choice count is a measure of how many branches were encountered in the solver.  This vaguely represents the number of ways you can go wrong if you just jot down numbers without thinking or looking ahead.  It's not perfect, because sometimes the path forward is obvious to a human but not to the solver.  It measures a choice at each number, but it would be better if it considered sequences of numbers that link two given cells.  For instance, starting with 1 in the above picture, you need to reach the 6.  There are a few ways to get to the 6, and the solver counts those, but it also counts ridiculous choices that never reach the 6, and I don't think humans would count those as making the puzzle more difficult.

The other measure is stretch.  Stretch is just the maximum distance between two given numbers.  A smaller stretch generally means you need to look ahead a smaller distance to find the next number, and it tends to mean fewer paths between one number and the next.  This one also has the benefit that it speeds up the solver; a very large gap in the numbers causes the solver to consider a large number of possible paths and while that might make an interesting puzzle, we need the solver to finish in a reasonable amount of time.

So we take away numbers, making sure the solution is unique and keeping the difficulty in check, and then stop after a certain number of tries, and now we have a puzzle.  The rest is user interface.

Puzzle in progress.

I tried to keep the interface simple.  The Parade site requires you to type the numbers, which I found annoying.  Instead I wanted to just click to place the next number.  There are some edge cases to consider, however.  The user should be able to start at any number, and go in both directions.  Also, the user needs to be able to remove numbers they've entered.  And when you hit a sequence you've already placed, it should skip over that to set you up to put the next number after the sequence.

As you'll guess from the intro menu, I'm thinking of adding more puzzle types later.

Monday, August 15, 2016

It's EELectric! (Junior)

My kids really wanted to play It's EELectric!, but it's way too hard for them.  So I made a new version with simpler rules and easier levels.  You know, for kids.  Or adults who couldn't stand the punishment of the previous version.



Monday, July 18, 2016

It's EELectric!

Do you like eel-based puzzle games?  Ready for some mind-bending diagonal-moving action?  No?  Nevertheless, let me introduce you to It's EELectric!, an original puzzle game I've been working on.

In this game you star as an apex predator, the deadly Electrophorus electricus, better known as the electric eel. This is not a realistic eel simulation. In fact, I looked it up: electric eels don't look like this thing at all.

Plus, I don't think there starfish in the same... you know what, just swim with it.  Your job is to eat all the fish on the level, but before you chow down on the unsuspecting prey you have to kill it with your electric shock attack.  And you're hungry and getting hungrier, so you'll have to be careful not to waste any moves.  Otherwise you'll perish and have to press R to go back in time to try again.  I already mentioned it's not realistic.  SHOCKING.

Enjoy 37 fiendfishly difficult pools of funderwater puzzling!  Sound sea-ffects?  It's um, reel.. something.  Hmm.

Anyway here it is:

Wednesday, May 25, 2016

Callooh Callay, World!

I wrote some puzzles for the 2014 MIT Mystery Hunt.  For one of them, Callooh Callay, World!, I invented a new esoteric programming language called Wonderlang.


It's frabjous.

I imagine this is how one would program computers in Wonderland, if there were any.  It's not meant to be particularly difficult to use, but it has a different perspective.  It requires a few characters not found in the ASCII character set: I suspect keyboards in Wonderland would have a great deal more keys than ours.

Wonderlang hasn't made it onto esolangs.org (yet).  To be fair, I haven't written a proper specification for it, which seems likely to be a requirement.  But then that's probably another natural characteristic of programming in Wonderland - why should they need to write this stuff down, or if they did, despite needing to, why should they go and actually do it?  After all, they're all mad there.


Wednesday, May 11, 2016

Hexfold

Here is HEXFOLD, a web-based puzzle game inspired by the puzzle toy Cool Circuits.  For some background, see my post analyzing Cool Circuits, and the one describing how to extend Cool Circuits to a hexagonal board.

Level 7: "Lucid Sitar"
TL;DR: The object of the game is to place the pieces on the board to create a loop, using every piece and obeying certain constraints that are different for each level.  I made 36 levels (the 37th and final one is randomly generated) which more or less increase in difficulty from hand-holding tutorial to absurdly hard.

I should warn you, this isn't an easy, kid game like Robot Quest or a simple, casual game like Logoplex.  Oh, sure, it starts out easy enough.  But that doesn't last.

If you give it a try, please provide feedback in the comments below.

Before you ask: the level names are just arbitrary adjective-noun combinations.  I generated a bunch using The Sillifier, and picked out the ones that amused me.

HEXFOLD (Web)

It's also available as a Chome App:

HEXFOLD (Chrome Store)

Thursday, May 5, 2016

Cool Circuits: Hexagons

If you haven't read my previous post about Cool Circuits, better go read that first.

What if Cool Circuits was made with a hexagonal grid instead of a square one?  More precisely, what if the turns in each piece were 60 degrees instead of 90?

We'll use the same pattern for generating the pieces: Each piece is a path composed of five turns either clockwise or counterclockwise, and each piece is uniquely described by a sequence of four bits, where each bit indicates whether the next turn is in a different direction than the previous turn.  Here's what the pieces would look like:

"JUVENILSQ"
Compared to the 90-degree pieces, these new ones are a little more stretched out.  If you've been paying attention you'll notice there's a new one.  The last piece in that image corresponds to the bit sequence 0001, which wasn't possible in the original Cool Circuits because it would have intersected itself.  I'm going to call it "Q".

Can we make a circuits with all of these pieces?  Nope.  In 90-degree-land, each piece contributed a single 90-degree turn (either way) to the overall path, and since there were an even number of pieces that meant we could end up with the complete 360-degree turn necessary for a circuit.  But with these new pieces, 6 of them contribute a 60-degree turn, and 3 of them contribute a 180-degree turn.  That means if we use all the pieces we'll always end up 180 degrees off. Here's a tabular summary:

LetterDescriptionFlippedContribution
J00111100180
U1001(same)±60
V10111101±60
E0110(same)180
N01011010±60
I1111(same)±60
L01111110±60
S00100100±60
Q00011000180

So we'll have to drop at least one piece.  For now, just to be true to the original puzzle, we're going to have to let Q go.  Sorry Q.  Maybe we'll find a job for you later.

Behold!  Hexagons!
Because the turns are 60 degrees, the pegs on the board will be arranged in a hexagonal grid.  Clearly, the overall shape of the board should also be a hexagon, but what size?  Five seems like a nice diameter - it would have almost the same number of points as the original puzzle.  I modified my solver from the original puzzle for these new parameters, kicked it off, and sat back to watch the solutions roll in.  Sadly, there are none.

Cool Circuits has a neat property that every solution leaves behind 6 untouched pegs.  In "Cool Circuits, Jr" they add 6 rings that you can use to wrap those pegs.  Once you've done that, there is no position left untouched.  This hexagonal version doesn't have that feature.  For each turn you make, you make it impossible for the path to later hit the point you didn't turn towards.  Near the edges, that can cascade and make other points untouchable as well.  I suspect this is a clue to why there aren't any solutions in the 5-board.

Before we give up on this board though, what if we had even fewer pieces?  I tried dropping J and E (leaving us with only pieces that contribute 60 degree turns), and I found that there are solutions to that variant.  Exactly four of them (ignoring solutions that are equivalent via rotation and reflection).  Here they are:

Four unique solutions for the 5-board, using the UVNILS pieces.
Note how the V and N pieces can be swapped (and flipped and rotated) to convert one solution into another.  That's also true in some of the solutions to Cool Circuits, though in both cases it depends on how tightly-packed the circuit is.

To me, this doesn't seem like enough solutions for an interesting puzzle game.  Sure, with rotation and reflection we could make more circuits, but they would all end up feeling the same.

Time to raise the diameter to 7.  You can probably guess going into this one that there will be too much space on the board.  Going back to 8 pieces, I let the solver run overnight, and it says there are 1503 circuits.

Alternative boards.
So with lots of space (A) we have lots of solutions.  I also considered removing the six outer-most pegs (B: 474 solutions) and removing four pegs from each of three edges, forming a somewhat triangular board (C: 130 solutions), but the bigger hexagonal board seems more thematic to me.  The large number of solutions does mean that we'll need to have plenty of constraints in each puzzle to make it uniquely solvable.

Overall, while not as elegant, I think this configuration works pretty well as a variant of Cool Circuits.  I'm working on a web-based playable version called HEXFOLD, which I'll post here once I've finished the levels and had some people play-test it.

Monday, April 25, 2016

Cool Circuits

I came across a particular kind of puzzle, the design of which is really fascinating to me.

I wanted to get my son some electronics toys for his last birthday.  I had one of those 100-in-1 electronics kits when I was a kid but he's still a bit young for the complex wiring, or at least that's what I thought.  I ended up picking Snap Circuits, which he loves.  I had to pick one more thing because you never know with kids, it's safer to get a couple of smaller things than one big one, so I tossed in Cool Circuits, because it had a similar name, and I think Amazon suggested it or something.  He also loved that one.  It's not really about electronics, it's just a puzzle game, but I've come to realize it's a very cleverly-made one.
A cool circuit in progress.

Here's how it works: the board has 25 pegs, arranged in a kind of diagonal grid.  There are 8 serpentine pieces which can fit in between the pegs, and each has a unique shape.  For each puzzle you are given some constraints (e.g. part of the circuit must travel along this path) and you must put the pieces on the board in a way that meets the constraints.  The one universal constraint is that the pieces must form a single loop.  In the toy, that triggers some mechanism which lights up the board and plays some music, but I've found that feature to be pretty finicky.

It's pretty tough to make a circuit from scratch, so the constraints tend to help more than hurt, and the more of them there are the easier the puzzle.

At first I thought the shapes of the pieces were arbitrary, but there's a mathematical beauty and completeness to them that took some pondering to discover.

As a font, it would not be easy to read.
Each piece is made of a sequence of five quarter-circles.  The manual describes them as "J", "U", "V", "E", "N", "I", "L", and "S".  So if you're looking at a given piece, starting from one end, you might describe it by listing the chirality of each segment.  For instance the "V" piece would be: turn right, left, left, right, left.  Or maybe clockwise, counter-clockwise, etc..  But that's a terrible description because the same piece would be described differently if you started from the other end, or flipped it over.

Math!
We can normalize the description for flipping by listing not the turns themselves, but the changes.  So if it starts out in one direction, we just say whether the next turn is the same as the previous one or different.  The "V" piece would then be different-same-different-different.  Now imagine same as 0 and different as 1 (e.g. 1011).  Each piece is described by four bits.  But some pieces have a different description if we start from the other end.  To correct for that, for each piece we'll pick the description that has the smallest number when treated as binary.

Here are the eight pieces:

LetterDescriptionFlipped
J00111100
U1001(same)
V10111101
E0110(same)
N01011010
I1111(same)
L01111110
S00100100

In this scheme, you can't have three zeros in a row, because that would make the piece intersect itself.  So 0000, 0000, and 1000 are out.  That means every workable bit sequence is represented.  These aren't arbitrary shapes at all, it's all possible unique shapes of length 5!  At length 4, there are 6 possible pieces.  At length 6, there would be 15.

All possible locations for the first piece.
Testing just the blue ones is enough.
So how many circuits are there? Let's start with an upper bound. For now let's say the first piece we put down can go in any point, in any direction, flipped or not. There are 224 possible first points (red and blue arrows in the diagram to the right).  However, some of those are equivalent to one another, because we could just rotate or "flip" the board itself.  So we'll cut that down to 28 (blue arrows only).

Suppose each piece can fit two ways at one of the blue arrows.  Actually, some pieces fit fewer ways than that, and sometimes they won't fit at all, but let's not work out those details yet.  After that first piece, we choose a next piece and fit it on in one of four ways.  This overestimated upper bound says there are fewer than 28×8!×2×47 paths (36,993,761,280). That's pretty high.  Luckily, many of the paths terminate quickly, either running off the board or crossing and earlier section of the path, so we're not going to need to search them all just to find the complete circuits.

I wrote a program to brute force all the paths.  It found 17,473 paths, starting from those blue-arrow positions, that used all 8 pieces without self-intersection or running off the board.  Of those, 1,520 ended up where they started, forming (possibly cool) circuits.

We're overcounting with that number though, because for any given unique solution, we're seeing it 16 different ways (counting reflection and cycling through the 8 pieces as starting pieces).  Now I very well may have made a mistake (or several) here, but I think the final answer, the number of unique solutions to this puzzle, the number of Cool Circuits, is 95 (no, see UPDATE below).


Solver Source Code

UPDATE 4/27: I found a mistake.  I didn't account for some solutions that fit so tightly that they leave four empty pegs all along one side of the board.  Those solutions are double counted in my initial number because they can be translated into another solution.  I was accounting for rotation and reflection, but not translation.  There are apparently 11 solutions like that, so my final answer (today) is 84.