r/dailyprogrammer • u/jnazario 2 0 • Jul 08 '16
[2016-07-08] Challenge #274 [Hard] ∞ Loop solver
Description
∞ Loop is a mobile game that consists of n*m tiles, placed in a n*m grid. There are 16 different tiles:
┃, ━, ┏, ┓, ┛, ┗, ┣, ┳, ┫, ┻, ╋, ╹, ╺, ╻, ╸, and the empty tile.
(If some of the Unicode characters aren't shown, here is a screenshot of this paragraph).
In other words, every tile may or may not have a "pipe" going up, a "pipe" going right, a "pipe" going down, and a "pipe" going left. All combinations of those are valid, legal tiles.
At the beginning of the game, the grid is filled with those tiles. The player may then choose some tile and rotate it 90 degrees to the right. The player may do this an unlimited amount of times. For example, ┣ becomes ┳ and ┛ becomes ┗, but ╋ stays ╋.
The objective is to create a closed loop: every pipe must have another tile facing it in the adjacent tile — for example if some tile has a pipe going right, its adjacent tile to the right must have a pipe going left.
In case you need clarification, here's some random guy playing it.
Your task is to write a program that, given an initial grid of tiles, outputs a solution to that grid.
Formal Inputs & Outputs
An easy way to represent tiles without having to deal with Unicode (or ASCII art) is to use the bitmask technique to encode the tiles as numbers 0...15.
To encode a tile:
Start with 0.
If the tile has a pipe going up, add 1.
If the tile has a pipe going right, add 2.
If the tile has a pipe going down, add 4.
If the tile has a pipe going left, add 8.
For example, ┫ becomes 1+4+8=13.
If we look at the binary representation of that number, we see that:
The first digit from the right shows whether the tile has a pipe going up;
The second digit from the right shows whether the tile has a pipe going right;
The third digit from the right shows whether the tile has a pipe going down;
The fourth digit from the right shows whether the tile has a pipe going left.
13 in binary is 1101, from which it is evident that all pipes are present except the pipe going right.
Input description
The input consists of n rows, each row having m space-separated numbers in it. Those numbers are the tiles, encoded in the bitmask technique discussed above.
You may also include the number of rows and columns in the input, if that makes it easier to read the input.
Output description
Output a similar grid which is obtained by rotating some or all tiles in the input grid. A tile may be rotated multiple times. The output grid must be a closed loop.
Sample input 1
9 12 12 6
10 13 13 5
3 3 9 3
Sample output 1
6 12 6 12
5 7 13 5
3 9 3 9
The sample input corresponds to:
┛┓┓┏
━┫┫┃
┗┗┛┗
By rotating some tiles, we get:
┏┓┏┓
┃┣┫┃
┗┛┗┛,
which corresponds to the sample output and is a closed loop.
(Again, if Unicode characters don't load, here is the first sample input).
Sample input 2
0 8 8 0
Sample output 2
0 2 8 0
The input corresponds to ╸╸, surrounded by two empty tiles.
The corresponding output is ╺╸.
Notes
It is easiest to use the bitwise and/or/xor operators to rotate and check for pipes. Most programming languages have such operators. The bitwise shift operators may also be helpful to rotate the tiles. Here's a Wikipedia article on using them on bitmasks.
Finally
This challenge was suggested by /u/A858DE57B86C2F16F, many thanks! Have a good challenge idea? Consider submitting it to /r/dailyprogrammer_ideas
4
u/jnazario 2 0 Jul 08 '16 edited Jul 08 '16
a couple of thoughts to kick off discussion.
a strategy i was thinking about to reduce the search space for a solution. i have not tested this in code, only in gameplay.
as for time complexity:
feedback, corrections, insights, etc all very welcome.
9
u/gabyjunior 1 2 Jul 08 '16 edited Jul 14 '16
C, a backtracker that finds all possible solutions.
At each step of the recursion, it selects the tile with the least options possible to reduce the search space.
Tiles rotation are precomputed for speedup.
Code
Output for sample 1
Output for sample 2
Solve time is instant, maybe I will try to generate larger inputs if I have time.
9
u/bearific Jul 08 '16 edited Jul 08 '16
Python 3 random challenge generator, for if you want to test your solution on larger inputs. Call
create_challenge(width, height)to generate a random challenge.Some of sample outputs here.
P.S. you can remove
if p.val not in [0, 1, 2, 4, 8]to use all characters.4
u/thorwing Jul 08 '16
Java 8
First solution: A brute force one which is fairly straightforward, just to try out if it finds it in a feasible time. searching in a space of 4m*n, I find it pretty fast due to the inherent parallism of streams.
output
4
u/bearific Jul 08 '16 edited Jul 08 '16
Python 3
First removes all orientations that would point a pipe to an empty tile or outside the field, remove duplicate orientations and then lock all tiles that have only one possible orientation.
Second, for each non-locked tile that has locked neighbours, remove all orientations that do not work with the locked neighbour's orientation. If there is only one orientation left, lock the tile.
Repeat step 2 until solved.
Not sure if this would always work, and would loop infinitely for an unsolvable input, but works for the challenge inputs.
3
u/aklidic Jul 08 '16
Here's what I have so far in C. I have it correctly rotate all edges in, but the actual logic is escaping me. I came from AP Comp Sci so I'm new to all the bit-wise stuff, so I'm open to criticism on that.
Which correctly modifies input to the following:
3
u/Cosmologicon 2 3 Jul 08 '16 edited Jul 08 '16
Here's a simple genetic algorithm. It would be great to get a larger challenge input, since this finishes Sample Input 1 in less than a second, and I'm sure it could use some tweaking to the parameters:
EDIT: Here's an (invalid - see below) 8x8 I randomly generated. It has a solution, but it's not necessarily unique.
I've tweaked the parameters on my genetic algorithm so it solves this one in a minute or so. No idea how that compares to more exhaustive techniques - I expect this is slower. No luck on a 10x10 yet.
4
u/Godspiral 3 3 Jul 08 '16 edited Jul 08 '16
in J, starting with putting tiles in numerical order:
approach first limits the edges, then brute forces possible combinations. Would show multiple solutions if any.
2
u/mbdomecq Jul 09 '16
C++. Figures out tile orientations using the process of elimination. If this isn't enough to solve the problem (which happens when there's more than one valid solution) the program goes into a depth-first search. Code
2
u/IanCodes Jul 09 '16
C (Technically C99 though it could easily be made backwards compatible)
My solution is a backtracker in C, much like /u/gabyjunior's. However, rather than selecting the tile with the least options, it just goes through the tiles sequentially from left to right, top to bottom. It is optimized to ignore + and empty tiles, and to only rotate vertical or horizontal bars once.
Basic overview:
For each given tile in the grid, isConnected() checks if it's connected to the tiles that have already been visited, and checks if the tile doesn't have any pipes leading off of the edge of the grid. If this check succeeds, we move on to the next tile. If this check fails, then we rotate the tile and tries again. If we run out of rotations, we go back a tile.
2
u/slampropp 1 0 Jul 10 '16 edited Jul 11 '16
Haskell
Pretty standard backtracking algorithm.
The solver is quite unreadable :/ which probably means I haven't quite understood the essence of it yet. Particularly, the similarity between the solve_row and solve_cols can probably be named and abstracted, and re-used for other backtrackers?
Performance:
Acceptable performance for "human sized" puzzles, but terrible terrible scaling.
1
u/hugokun Jul 08 '16
Newbie here, what part of this is considered hard? I'm asking to know if I should give it a try, it seems pretty interesting.
1
u/[deleted] Jul 11 '16
Maybe a little late to the party, but that was a nice problem.
Greedy randomized algorithm, that solve 50x50 instantly(less then 1s) in ~C (I use a C++ compiler, so it may not compile as pure C)
It may not converge for every input. To get it out of a steady state I shake up all wrong tiles every 101 iterations.
Gist
1
u/MuffinsLovesYou 0 1 Jul 12 '16 edited Jul 12 '16
Solution is in C# so not a code-golf one. https://raw.githubusercontent.com/MuffinsLovesYou/Code-Samples/master/InfinityLoop/InfinityLoop/Program.cs
Next round of edits done. Consumes 30x30 in ~42ms and 50x50 in ~92ms. Gonna think about the option of multi-threading it so that I could potentially consume a much larger grid.
The bulk of the program is just structure and details, here's the crux of the algorithm:
Step 1: reduce impossible rotations for every tile.
A null neighbor is out-of-bounds, otherwise we check to see if the neighbor can't possibly face us, or can only face us and adjust our local rotation possibilities accordingly.
After that we're left with just tiles that have more than one possibility.
So if our neighbor isn't facing us, we rotate our neighbor until they are. If we have already rotated that neighbor in the past, we rotate ourselves (infinite loop condition breaker). Rotate() on a tile goes to the next possible orientation from the pruned list rather than just doing a bitwise shift.
1
u/jeaton Jul 15 '16 edited Jul 15 '16
C++
1
u/loueed Aug 14 '16
I bought the game and love it so I spent a couple of hours recreating it in codepen. I've used only CSS and jQuery but got the main concept sorted. Play Here.
To create a level, configure the pipes in a pattern and then copy the patterns code from the console.