How to escape stable pattern in conway's game of life? - algorithm

I built conway's game of life and its working fine but my game after many generations is either ending with no lives or reaching a stable pattern which it can't escape.
For example I have followed these rules
Any live cell with fewer than two live neighbours dies, as if by underpopulation.
(live_cell = True and neighourhood < 2)
Any live cell with two or three live neighbours lives on to the next generation.
(live_cell = True and neighourhood == 2 or neighourhood == 3)
Any live cell with more than three live neighbours dies, as if by overpopulation.
(live_cell = True and neighourhood > 3)
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
(live_cell = False and neighourhood == 3)
This is my game of life matrix where 1 is life and 0 not
000000
001000
010100
001000
000000
000000
and this is its corresponding neighbourhood maps created by my programe
011100
122210
124210
122210
011100
000000
After reaching this pattern even after thousands of generation its still stuck in this pattern itself. I dont know how to escape this pattern ?

If the space is finite, then the number of possible configurations is finite and then the GoL will end either in a stable pattern or in a loop. If the space is very small (as it looks like) then you will observe only stupid behavior. You need at least to use a much bigger space (500x500), fill it with 1's at many places and look; that is the basic play with GoL. The next step is to build interesting configurations, and there exists a lot that have been discovered over time, for examples see GoL Pattern Library. Basic well-known patterns are gliders, glider-guns, oscillators... You will discover that GoL is in fact a very interesting way of programming: the initial configuration is a program code executed by the machine that you can see evolving on your screen. But that programming is not so easy, especially if you want to obtain a specific behavior!

Related

How to write Analysis function for Min-Max Algorithm?

I'm trying to code AI for a game somewhat similar to Tic-Tac-Toe. You can see its rules here.
The min-max algorithm and analysis function I'm using can be found here
The way I've tried so far:
I've built some patterns which will be good for the current player. (in Python)
e.g. my_pattern = " ".join(str(x) for x in [piece, None, piece, piece, None])
I'm matching such patterns with all the 6 possible orientations on the hexagonal gameboard for every piece (not for blank spaces). To be precise, matching my_pattern with 6 different arrays (each array represents one of 6 different orientations).
Now, What should this analysis function actually calculate?
The score of entire state of board?
The score of the last move made on board?
If someone can accurately describe the purpose of Analysis function, that would be great.
The analysis function represents the current state of board. It may/ may not include the last move, any of the previous moves or the order of moves to reach a board position. It should also consider whose turn it is to play.
What I mean is the same board can be good/bad for white/black depending on whose turn it is. (Called the situation of zugzwang in chess).
Also, the same board can be reached in a variety of move sequences, hence, it depends on the type of game whether you want to include that in the analysis or not. (High level chess engines surely include order of moves, though not for calculating current board, but for further analysis on a possibility of reaching that position). In this game however, I don't think there is any need of including last or any of the previous moves (order) for your analysis function.
EDIT:
An example of analysis function:
value = 10000*W(4) - 10000*W(3) + 200*W(2.1) + 200*W(1.2) + 100*W(2) + 100*W(1.1) + 2*W(1e) + 10*W(1m) + 30*W(1c) - (10000*B(4) - 10000*B(3) + 200*B(2.1) + 200*B(1.2) + 100*B(2) + 100*B(1.1) + 2*B(1e) + 10*B(1m) + 30*B(1c))
where:
W = white
B = black pieces
4 = made line of 4 pieces
3 = made line of 3 pieces
2 = made line of 2 pieces having possibility of getting extended to 4 from atleast one side
. = blank (ie, 1.2 = W.WW on the board)
1.1 = Piece|Blank|Piece and possibility of extending to 4 from atleast one side
e|m|c = edge|middle|center of board, and possibility of extending to 4 from either sides
The positive result of this analysis function would mean white is better, 0 indicates balanced board and negative value means black has advantageous position. You can change the weights owing to the result of tests you will execute. However, finding all possible combinations is exhaustive task, but the game is such :)

Tic-Tac-Toe Strategy - 60's MiniVac 601 Logic

Tic-Tac-Toe seems to be a fairly solved problem space, most 100% solutions seem to search through a finite tree of possibilities to find a path to winning.
However, I came across something from a computer-simulation toy from the 60's, The MiniVac 601. http://en.wikipedia.org/wiki/Minivac_601
This 'comptuer' consisted of 6 relays that could be hooked up to solve various solutions. It had a game section, which had this description on a program for Tic-Tac-Toe, that claims to be unbeatable as long as the Minivac went first.
Since most solutions to this seem to require lots of memory or computational power, its surprising to see a solution using a computer of 6 relays. Obviously I haven't seen this algorithm before, not sure I can figure it out. Attempts to solve this on a pad and paper seem to indicate a fairly easy win against the computer.
http://www.ccapitalia.net/descarga/docs/1961-minivac601-book5&6.pdf
"with this program, MINI VAC can not lose. The human opponent may
tie the game, but he can never win. This is because of the decision
rules which are the basis of the program. The M IN IV A C is so
programmed that the machine will move 5 squares to the right of its
own last move if and only if the human opponent has blocked that last
move by moving 4 squares to the right of the machine's last move. If
the human player did not move 4 squares to the right of the machine's
last move, M IN IV A C will move into that square and indicate a win.
If the hu­ man player consistently follows the "move 4 to the right"
rule, every game will end in a tie. This program requires that M IN IV
A C make the first move; the machine's first move will always be to
the center of the game matrix. A program which would allow the human
opponent to move first would require more storage and processing
capacity than is available on M IN IV A C
601. Such a program would, of course, be much more complex than the program which permits the machine to move first"
EDIT: OK so the Question a little more explicitly: Is this a real solution to solving Tic-Tac-Toe? Does anyone recognize this algorithm, it seems very very simple to not be easily searchable.
I think it is all in the layout of the "board". If you look at the 601 units tic-tac-toe area, 9 is in the middle and 1 is top left numbered sequentially clockwise around 9.
The "computer" goes first in the 9 position. The user then goes next.
If the user hasn't gone in position 1 (top left) then that is the next position for the computer. The user then goes next. Then the computer tries to go in position 1+4 (5 - bottom right). If the position is not available it will go in 1+5 (6 - bottom middle). x + 4 is always opposite the previous move, and since the computer has the center position it will be a winning move.

brute forcing a brain puzzle

I was given a brain puzzle from lonpos.cc as a present. I was curius of how many different solutions there were, and I quite enjoy writing algorithms and code, so I started writing an application to brute force it.
The puzzle looks like this : http://www.lonpos.cc/images/LONPOSdb.jpg / http://cdn100.iofferphoto.com/img/item/191/498/944/u2t6.jpg
It's a board of 20x14 "points". And all puzzle pieces can be flipped and turned. I wrote an application where each piece (and the puzzle) is presented like this:
01010
00100
01110
01110
11111
01010
Now my application so far is reasonably simple.
It takes the list of pieces and a blank board, pops of piece #0
flips it in every direction, and for that piece tries to place it for every x and y coordinate. If it successfully places a piece it passes a copy of the new "board" with some pieces taken to a recursive function, and tries all combinations for their pieces.
Explained in pseudocode:
bruteForce(Board base, List pieces) {
for (Piece in pieces.pop, piece.pop.flip, piece.pop.flip2...) {
int x,y = 0;
if canplace(piece, x, y) {
Board newBoard = base.clone();
newBoard.placePiece(piece, x, y);
bruteForce(newBoard, pieces);
}
## increment x until x > width, then y
}
}
Now I'm trying to find out ways to make this quicker. Things I've thought of so far:
Making it solve in parallel - Implemented, now using 4 threads.
Sorting the pieces, and only trying to place the pieces that will fit in the x,y space we're trying to fit. (Aka if we're on the bottom row, and we only have 4 "points" from our position to the bottom, dont try the ones that are 8 high).
Not duplicating the board, instead using placePiece and removePiece or something like it.
Checking for "invalid" boards, aka if a piece is impossible to reach (boxed in completely).
Anyone have any creative ideas on how I can do this quicker? Or any way to mathematically calculate how many different combinations there are?
I don't see any obvious way to do things fast, but here are some tips that might help.
First off, if you ignore the bumps, you have a 6x4 grid to fill with 1x2 blocks. Each of the blocks has 6 positions where it can have a bump or a hole. Therefore, you're trying to find an arrangement of the blocks such that at each edge, a bump is matched with a hole. Also, you can represent the pieces much more efficiently using this information.
Next, I'd recommend trying all ways to place a block in a specific spot rather than all places to play a specific block anywhere. This will reduce the number of false trails you go down.
This looks like the Exact Cover Problem. You basically want to cover all fields on the board with your given pieces. I can recommend Dancing Links, published by Donald Knuth. In the paper you find a clear example for the pentomino problem which should give you a good idea of how it works.
You basically set up a system that keeps track of all possible ways to place a specific block on the board. By placing a block, you would cover a set of positions on the field. These positions can't be used to place any other blocks. All possibilities would then be erased from the problem setting before you place another block. The dancing links allows for fast backtracking and erasing of possibilities.

How can I use TDD to solve a puzzle with an unknown answer?

Recently I wrote a Ruby program to determine solutions to a "Scramble Squares" tile puzzle:
I used TDD to implement most of it, leading to tests that looked like this:
it "has top, bottom, left, right" do
c = Cards.new
card = c.cards[0]
card.top.should == :CT
card.bottom.should == :WB
card.left.should == :MT
card.right.should == :BT
end
This worked well for the lower-level "helper" methods: identifying the "sides" of a tile, determining if a tile can be validly placed in the grid, etc.
But I ran into a problem when coding the actual algorithm to solve the puzzle. Since I didn't know valid possible solutions to the problem, I didn't know how to write a test first.
I ended up writing a pretty ugly, untested, algorithm to solve it:
def play_game
working_states = []
after_1 = step_1
i = 0
after_1.each do |state_1|
step_2(state_1).each do |state_2|
step_3(state_2).each do |state_3|
step_4(state_3).each do |state_4|
step_5(state_4).each do |state_5|
step_6(state_5).each do |state_6|
step_7(state_6).each do |state_7|
step_8(state_7).each do |state_8|
step_9(state_8).each do |state_9|
working_states << state_9[0]
end
end
end
end
end
end
end
end
end
So my question is: how do you use TDD to write a method when you don't already know the valid outputs?
If you're interested, the code's on GitHub:
Tests: https://github.com/mattdsteele/scramblesquares-solver/blob/master/golf-creator-spec.rb
Production code: https://github.com/mattdsteele/scramblesquares-solver/blob/master/game.rb
This isn't a direct answer, but this reminds me of the comparison between the Sudoku solvers written by Peter Norvig and Ron Jeffries. Ron Jeffries' approach used classic TDD, but he never really got a good solution. Norvig, on the other hand, was able to solve it very elegantly without TDD.
The fundamental question is: can an algorithm emerge using TDD?
From the puzzle website:
The object of the Scramble Squares®
puzzle game is to arrange the nine
colorfully illustrated square pieces
into a 12" x 12" square so that the
realistic graphics on the pieces'
edges match perfectly to form a
completed design in every direction.
So one of the first things I would look for is a test of whether two tiles, in a particular arrangement, match one another. This is with regard to your question of validity. Without that method working correctly, you can't evaluate whether the puzzle has been solved. That seems like a nice starting point, a nice bite-sized piece toward the full solution. It's not an algorithm yet, of course.
Once match() is working, where do we go from here? Well, an obvious solution is brute force: from the set of all possible arrangements of the tiles within the grid, reject those where any two adjacent tiles don't match. That's an algorithm, of sorts, and it's pretty certain to work (although in many puzzles the heat death of the universe occurs before a solution).
How about collecting the set of all pairs of tiles that match along a given edge (LTRB)? Could you get from there to a solution, quicker? Certainly you can test it (and test-drive it) easily enough.
The tests are unlikely to give you an algorithm, but they can help you to think about algorithms, and of course they can make validating your approach easier.
dunno if this "answers" the question either
analysis of the "puzzle"
9 tiles
each has 4 sides
each tile has half a pattern / picture
BRUTE FORCE APPROACH
to solve this problem
you need to generate 9! combinations ( 9 tiles X 8 tiles X 7 tiles... )
limited by the number of matching sides to the current tile(s) already in place
CONSIDERED APPROACH
Q How many sides are different?
IE how many matches are there?
therefore 9 X 4 = 36 sides / 2 ( since each side "must" match at least 1 other side )
otherwise its an uncompleteable puzzle
NOTE: at least 12 must match "correctly" for a 3 X 3 puzzle
label each matching side of a tile using a unique letter
then build a table holding each tile
you will need 4 entries into the table for each tile
4 sides ( corners ) hence 4 combinations
if you sort the table by side and INDEX into the table
side,tile_number
ABcd tile_1
BCda tile_1
CDab tile_1
DAbc tile_1
using the table should speed things up
since you should only need to match 1 or 2 sides at most
this limits the amount of NON PRODUCTIVE tile placing it has to do
depending on the design of the pattern / picture
there are 3 combinations ( orientations ) since each tile can be placed using 3 orientations
- the same ( multiple copies of the same tile )
- reflection
- rotation
God help us if they decide to make life very difficult
by putting similar patterns / pictures on the other side that also need to match
OR even making the tiles into cubes and matching 6 sides!!!
Using TDD,
you would write tests and then code to solve each small part of the problem,
as outlined above and write more tests and code to solve the whole problem
NO its not easy, you need to sit and write tests and code to practice
NOTE: this is a variation of the map colouring problem
http://en.wikipedia.org/wiki/Four_color_theorem

intelligent path truncation/ellipsis for display

I am looking for an existign path truncation algorithm (similar to what the Win32 static control does with SS_PATHELLIPSIS) for a set of paths that should focus on the distinct elements.
For example, if my paths are like this:
Unit with X/Test 3V/
Unit with X/Test 4V/
Unit with X/Test 5V/
Unit without X/Test 3V/
Unit without X/Test 6V/
Unit without X/2nd Test 6V/
When not enough display space is available, they should be truncated to something like this:
...with X/...3V/
...with X/...4V/
...with X/...5V/
...without X/...3V/
...without X/...6V/
...without X/2nd ...6V/
(Assuming that an ellipsis generally is shorter than three letters).
This is just an example of a rather simple, ideal case (e.g. they'd all end up at different lengths now, and I wouldn't know how to create a good suggestion when a path "Thingie/Long Test/" is added to the pool).
There is no given structure of the path elements, they are assigned by the user, but often items will have similar segments. It should work for proportional fonts, so the algorithm should take a measure function (and not call it to heavily) or generate a suggestion list.
Data-wise, a typical use case would contain 2..4 path segments anf 20 elements per segment.
I am looking for previous attempts into that direction, and if that's solvable wiht sensible amount of code or dependencies.
I'm assuming you're asking mainly about how to deal with the set of folder names extracted from the same level of hierarchy, since splitting by rows and path separators and aggregating by hierarchy depth is simple.
Your problem reminds me a lot of the longest common substring problem, with the differences that:
You're interested in many substrings, not just one.
You care about order.
These may appear substantial, but if you examine the dynamic-programming solution in the article you can see that it revolves around creating a table of "character collisions" and then looking for the longest diagonal in this table. I think that you could instead enumerate all diagonals in the table by the order in which they appear, and then for each path replace, by order, all appearances of these strings with ellipses.
Enforcing a minimal substring length of 2 will return a result similar to what you've outlined in your question.
It does seem like it requires some tinkering with the algorithm (for example, ensuring a certain substring is first in all strings), and then you need to invoke it over your entire set... I hope this at least gives you a possible direction.
Well, the "natural number" ordering part is actually easy, simply replace all numbers with formatted number where there is enough leading zeroes, eg. Test 9V -> Test 000009V and Test 12B -> Test 000012B. These are now sortable by standard methods.
For the actual ellipsisizing. Unless this is actually a huge system, I'd just add manual ellipsisizing "list" (of regexes, for flexibility and pain) that'd turn certain words into ellipses. This does requires continuous work, but coming up with the algorithm eats your time too; there are myriads of corner cases.
I'd probably try a "Floodfill" approach. Arrange first level of directories as you would a bitmap, every letter is a pixel. iterate over all characters that are in names of directories. with all of them, "paint" this same character, then "paint" the next character from first string such that it follows this previous character (and so on etc.) Then select the longest painted string that you find.
Example (if prefixed with *, it's painted)
Foo
BarFoo
*Foo
Bar*Foo
*F*oo
Bar*F*oo
...
note that:
*ofoo
b*oo
*o*foo
b*oo
.. painting of first 'o' stops since there are no continuing characters.
of*oo
b*oo
...
And then you get to to second "o" and it will find a substring of at least 2.
So you will have to iterate over most possible character instances (one optimization is to stop in each string at position Length-n, where n is the longest already found common substring. But then there is yet another problem (here with "Beta Beta")
| <- visibility cutout
Alfa Beta Gamma Delta 1
Alfa Beta Gamma Delta 2
Alfa Beta Beta 1
Alfa Beta Beta 2
Beta Beta 1
Beta Beta 2
Beta Beta 3
Beta Beta 4
What do you want to do? Cut Alfa Beta Gamma Delta or Alfa Beta or Beta Beta or Beta?
This is a bit rambling, but might be entertaining :).

Resources