r/compsci • • Dec 09 '22

How would you write an algorithm to solve this?

1.1k Upvotes

84 comments sorted by

263

u/teawreckshero Dec 09 '22

As someone else said: backtracking.

More specifically: each configuration of the pieces (state of the board) is a node in a tree. Each node connects to child nodes which correspond to all the possible moves you could make in that board state. It's possible to reach the same state from multiple previous states, so it technically wouldn't be tree, but since you're always losing a piece it's guaranteed to be acyclic, so it would be a DAG (useful to note so your code can avoid re-exploring the same state redundantly from 2 different states). Start from the root node and explore the graph using DFS until you find a state with 1 piece left. DFS will "backtrack" each time it exhausts a branch without finding a solution. Once a solution is found, output the path back to the root to get a series of steps to solve it. Note there are multiple solutions, so you could keep searching exhaustively if you want to output them all.

53

u/gwszack Dec 09 '22

Any estimation on the size of the search space? Would a brute force search like this perform in reasonable time without any optimization?

44

u/[deleted] Dec 09 '22

There are 2^33 possible states (each hole either contains a pebble or does not), so about 8.6 billion states. I'd expect a brute force search to take a few minutes to run.

27

u/primitiveType Dec 09 '22

There's actually fewer than that right? For instance, you can never have just the rightmost peg be empty.

Hard to judge how much lower it is than that but I wouldn't be surprised if the difference is significant. In fact answering that question might be more interesting than the op

22

u/ctartamella Dec 10 '22

Also should be some rotational symmetries.

2

u/howaboot Dec 10 '22

Why is it more interesting? It's trivial to brute force the answer the exact same way and you don't even have to track the transitions.

2

u/primitiveType Dec 10 '22

Well you also have to eliminate states that are symmetrically the same. Maybe that's pretty trivial, but less so than the original question I think

13

u/HeyJamboJambo Dec 09 '22

Can't be worse than 2×N! where N is the number of pebbles. Each pebble will be removed once, you don't know the order or removal (hence the factorial), and there are only a maximum of two ways to remove a pebble from any configuration (since you need to make the opposite side empty).

42

u/nemotux Dec 09 '22

Uh... 32 pebbles... 32! = 2.6 x 1035. "Can't be worse." I think you need it to be much better to solve this realistically.

17

u/Cridor Dec 09 '22

As someone else pointed out, you'll never be able to make N choices for a given board, since you always start with only 4 available moves, and the first move reduces to N-1, etc.

The board size would need to be fairly large before you'll bump up against that factorial

21

u/nemotux Dec 09 '22

Sure. I was just pointing out how that bound is not terribly helpful.

5

u/Cridor Dec 09 '22

That's fair. I've been treating the comment section in discussions on this sub like an exploratory round table to find solutions to problems like these.

It would be interesting to see how the number of available moves increases whole there are still pins to move, and then where the state changes and removing pins limits moves

5

u/nemotux Dec 09 '22

Also interesting is, as someone up the chain mentioned, the fact that it's not a tree but rather a DAG, as you can get to the same board position in multiple ways. So using a transposition table will likely save loads of search time.

2

u/Cridor Dec 09 '22

If we store color information in the table as well, we can mark nodes as processed, processing and unprocessed.

Then we could parallelize the search by marking unprocessed nodes as processing when touched by the search, and as processed when backtracking.

The threads can drill down until they hit terminal nodes and help process nodes that are not processed without duplicating work

1

u/[deleted] Dec 09 '22

Yeah the other commenter might as well have said “well it can’t be any worse than dying a slow agonizing death”

Technically true but in-order for the activity to be fun it needs to be much much much better than the reported worse case.

3

u/HeyJamboJambo Dec 09 '22

Yeah, I was thinking about the general case with any boards. That's why I used N instead of 32.

4

u/gwszack Dec 09 '22

This isn’t a very useful upper bound. There’s a better trivial upper bound of 233 which is around ten billion. Still not enough to perform in seconds but once you account for how much of a loose upper bound it is, my intuition tells me that the backtrack algorithm would perform in a reasonable time.

What’s also of note is that we have symmetry here so there’s only a need to search 1/4 of the space.

1

u/HeyJamboJambo Dec 09 '22

I'm thinking more of the general problem with N pebbles and large enough board. That's why I used N and not 32. If the problem is already a very specific configuration, then it's not as interesting as theoretically it can be hardcoded if we know the solution already.

3

u/swierdo Dec 09 '22

There's no factorial there. There's 2N possible states, some of which unreachable. And there are at most O(N) possible states to move to from any given state. So you have to store up to 2N states and their connections for N*2N.

2

u/HugoNikanor Dec 09 '22

Is it my turn to point out that O(2N!) = O(N!)?

10

u/ragusa12 Dec 09 '22

An upper bound is not the same as an asymptotic upper bound. The upper bound 2×N! is tighter than O(N!).

9

u/[deleted] Dec 09 '22

Conveniently, no one said O(N!), so I'm going to say no, get back in line.

1

u/[deleted] Dec 09 '22

[removed] — view removed comment

4

u/Cridor Dec 09 '22

We also know that each move adds 1 hole, and removes one peg.

So each step adds at most 3 possible moves to the total, and takes away a peg.

13

u/eras Dec 09 '22

You can also prune the tree due to symmetricity.

It might actually be pretty interesting to implement this with optimizations.

1

u/Mountain_Thanks4263 Dec 09 '22

You can use the symmetry of the board to get rid of quasi-identical scenarios

-1

u/SteeleDynamics Dec 09 '22

CPS has entered the chat

48

u/19c766e1-22b1-40ce Dec 09 '22

I guess backtracking would be one option?

27

u/Antimon3000 Dec 09 '22 edited Dec 09 '22

Yup, and maybe one can recognize certain patterns to cut off unsolvable branches early.

-4

u/ActAmazing Dec 09 '22

yes it seems a very suitable one, as there are limited number of options at start and end of game. and it should get solve very efficiently even well within 1 sec.

66

u/frblnl Dec 09 '22

You just hardcore the pattern from the video and you're done /s

But no indeed, I'd also say backtracking. And you can discard a number of duplicate options as the thing is semetric

8

u/574859434F4E56455254 Dec 09 '22

Why /s? It may not be in the spirit of the question, or the most academically interesting way to do it, but would be the quickest.

51

u/pacman-based Dec 09 '22

This is actually a popular programming lab that almost all Carnegie Mellon undergrads do. This guide has a set of steps to implement/optimize a backtracking search for this problem in C.

2

u/l33tIsSuperpower Dec 09 '22

NOOOOO not peg waaahhh

20

u/maweki Dec 09 '22

You could SAT encode the board with a quadratic number of boolean variables and then encode all the move rules from one board to the next and then fix all the initial variables as true and the final variables as false and let the sat solver do its magic and give you a satisfying order of operations.

8

u/Technohazard Dec 09 '22

You're on to something here. Each node on the board is a bit. The rules define which bits are allowed to flip in which conditions, e.g. the legal moves. With that 232 set of board hashes and a ruleset of single bit transforms. Everytime you run the game and win, add +1 to transforms taken during that win from the associated board hash. In future plays, take the transform with the highest score. Eventually it'll figure out which moves are best from most possible states. For fun, you could start with a random move strategy (pick any random transform with no regard to weighting or goal) just to populate your game data. Or play various strategies against each other. It also makes solving for previous board states easy, as you just have to store a list of board hashes already played, and disallow any transforms that would lead to that hash from the current board.

5

u/maweki Dec 09 '22

Say you index each board state and connect every pair of states that is reachable by one move, then you have a semi-order over all the indexes with all least elements being the boards without moves left and all greatest elements being possible initial board states.

I guess that solves the game.

6

u/Nicolixxx Dec 09 '22 edited Dec 09 '22

Did this one for a school projet few years ago : backtracking is the way

15

u/EatingBeansAgain Dec 09 '22

My Pop made this game out of wood. I would sit on their front porch and play it for hours. I know that isn’t what this post is about but thank you for the memories. Sometimes I wonder how much of an influence this game had on my future interests and career.

9

u/zockchster Dec 09 '22

Maybe tree search, where each possible move is a node. Might take ages to finish capculating all the options though

6

u/clarkcox3 Dec 09 '22

Worst case, there are 2³² board states. Wouldn’t take too long to build such a tree; especially if you pruned obviously losing branches as early as possible.

3

u/lordcirth Dec 09 '22

It's also 4-way symmetrical, so a lot of simple states could lumped in with their mirror.

7

u/Morinator Dec 09 '22

I highly suspect this to be a NP-hard Problem. So your best shot is to do backtracking and optimize it as good as you can with heuristics, shrinking the searchspace by using symmetry, clever pruning...

2

u/DebraRBlack Dec 09 '22

Damn, I've been trying to figure this out whenever I see my grandmother. A wooden version of it is currently on her coffee table. I must save this.

2

u/YouKnowMe_9 Dec 09 '22

What puzzle is this? Seeing for the first time

7

u/jonhanson Dec 09 '22 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

2

u/superluminary Dec 09 '22

Depth first tree search, with pruning. Write a function that can tell you if the board is unsolvable, then prune the subtree when you reach a state where this function == true.

1

u/themissinglint Dec 11 '22

I like this optimization. It helps even if you have a weak idea of what is unsolvable. Maybe something like "is the empty space just created part of a 3-hole-wide gap with pieces on both sides of it?"

2

u/Fantastic_Search8930 Dec 10 '22

Brute Force 💀💀💀

1

u/rbobby Dec 09 '22

How weird. I was just thinking about this game the other day. Trying to remember which grandparent had it.

Spooky.

1

u/potter1024 Dec 09 '22

A backtracking algorithm would solve it, not sure about the complexity

1

u/dgermain Dec 09 '22

Would that starting from the end point and playing it in reverse not simplify the search?

1

u/Miserable_District Dec 09 '22

Umm Pythagoras theorem!

1

u/pablocael Dec 10 '22

Maybe Simulated Annealing can also be useful if you can evaluate the board position with number value.

1

u/[deleted] Dec 10 '22

Recursion for every move.

1

u/sugarsnuff Aug 22 '23

DFS all the moves?

1

u/derlarsianer Nov 29 '23

I write a blog post some time ago about that.

1

u/ThePhantomPhoton Dec 09 '22

Because this problem appears to be reducible to a kind of Euler tour with some helpful symmetry we could make use of, I think the individual who suggested treating this as a graph and relying on the results of a DFS has the correct approach.

1

u/clarkcox3 Dec 09 '22

The moves are pretty limited; just build a tree of all possible board states, and pick the shortest path to a node that ends with a single piece remaining.

0

u/Technohazard Dec 09 '22

So simple a slime mold could solve it!

0

u/themissinglint Dec 11 '22

all paths that end with a single piece will be the same length (the number of pieces).

1

u/Neoxus30- Dec 09 '22

Copy the video)

1

u/JMBourguet Dec 10 '22

Dynamic programming (or backtracking with memoization which can be considered as a special case of dynamic programming, but considering it like a dynamic programming opens more design choices; backtracking without memoization is a bad idea IIRC). Consider the spacial symmetry, but also the temporal one (play the game in reverse to see what I mean) if you just want to solve for a given ending position.

1

u/derlarsianer Dec 14 '22 edited Dec 16 '22

Interesting exercise. I just wrote a quick implementation without any performance optimization in Kotlin using DFS approach.

The algorithm looks as follows:

fun dfs(
    game: Solitaire = this,
): Pair<Move?, Boolean> {
    if (game.hasWon()) return Pair(null, true)

    val moves = game.getPossibleMoves()
    if (moves.isEmpty()) return Pair(null, false)

    // Play each move and call recursively
    // Pick first solution that was found.
    for (move in moves) {
        val newGame = game.move(move)
        val hasWon = dfs(newGame).second
        if (hasWon)
            return Pair(move, true) // Return move that lead to win
    }

    // Case when no solution was found
    return Pair(moves.random(), false)
}

The algorithm returns a Pair<Move,Boolean> including the best move and whether the game was won or not. After 31 moves the game will be finished. It finds a solution for all moves in < 100ms. I can publish it on GitHub if someone is interested.

EDIT: I just wrote a blog post about that.

-2

u/labronesy Dec 10 '22

plumbuses. Everyone has a plumbus in their home. First, they take the dinglebop, and they smooth it out with a bunch of schleem. The schleem is then repurposed for later batches. They take the dinglebop and they push it through the grumbo, where the fleeb is rubbed against it. It’s important that the fleeb is rubbed, because the fleeb has all of the fleeb juice. Then a schlami shows up, and he rubs it and spits on it. They cut the fleeb. There’s several hizzards in the way. The blamfs rub against the chumbles. And the ploobis and grumbo are shaved away. That leaves you with a regular old plumbus.

0

u/[deleted] Dec 10 '22

2 tru

0

u/RayATrogdon Dec 09 '22

These Anthem Blue Cross commercials...

0

u/IAMGODONLY Dec 10 '22

Ah the good ol marble game.

0

u/Dangerous_Grocery_48 Dec 10 '22

Instead of solving it straight, I'd go backwards. Start with one marble and add marbles as you "unjump" Record all these moves and play them back. Actually I have done this before when challenged by my mom. But I did it with a physical game and recorded the moves in my head instead of a computer. But there's no reason why we can't apply the same logic via an algorithm. Please try and let me know

-6

u/TompsonG Dec 09 '22

There is a limited amount of moves, that can be done each time, u take one dot out.

U could consider this and write ur algorithm based on the outcome of the possibilities of your last move.

Maybe machine learning would be an option here.

0

u/[deleted] Dec 09 '22

[deleted]

4

u/lordcirth Dec 09 '22

I think you would at least need to do symmetry pruning to keep the exponents within reason.

3

u/[deleted] Dec 10 '22

We're going depth first greedy algorithm and we're gonna like it

0

u/[deleted] Dec 10 '22

[deleted]

0

u/themissinglint Dec 11 '22

not fair to say A* without giving the heuristic

0

u/themissinglint Dec 11 '22

(if you choose "number of pieces remaining" it's just a depth first search since every move always removes one piece)

0

u/[deleted] Dec 09 '22

[deleted]

1

u/IamConor21 Dec 09 '22

There is one less blue circle from one state to the next, so this is equivalent to bfs.

0

u/[deleted] Dec 09 '22

[deleted]

1

u/clarkcox3 Dec 09 '22

Well that was a lot of mental masturbation, and a very strange way of describing CS and SWE.

0

u/[deleted] Dec 09 '22

[deleted]

1

u/lordcirth Dec 09 '22

Throwing deep learning at a single well-defined problem? Why?

2

u/RomanRiesen Dec 09 '22

If we start to vary board-shapes it's no longer a single problem though.

1

u/lordcirth Dec 09 '22

That's true, but it's still a well-defined set with the same basic rules. If you can state the question, you probably don't need a neural net to find the answer.

1

u/Technohazard Dec 09 '22

Why not?

Now imagine playing this on an infinite board... :)

-4

u/mrezar Dec 09 '22

id go with reinforcement learning as well, i dont think it needs to be "deep" tho