# Thread: Beginners Programming Challenge 16

1. ## Beginners Programming Challenge 16

The challenge now is related to the Conway's Game of Life. Yes - you must create a program which emulates it.
Rules: http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
You may consider dead anything outside the bounds of the grid.
Input: the program will be called with two arguments: a file containing the original state and (being it a square) the length of the side of the grid.
The file: it will be a string of 0's and 1's - 0 means a dead cell, 1 means a live cell. Example file:
Code:
`0000000000000000000000000000000000000011000001100000000011000110000000100101010100100001110110110111000001010101010100000001110001110000000000000000000000000111000111000000010101010101000001110110110111000010010101010010000000110001100000000011000001100000000000000000000000000000000000000`
Being this in a file named 'pulsar', this should merrily display the pulsar pattern being called by:
Code:
`./gol pulsar 17`
Displaying: get creative. If you have no GUI experience, a terminal displaying is completely acceptable.

2. 5 Cups of Ubuntu
Join Date
Nov 2009
Location
Dublin, Ireland
Beans
24
Distro
Kubuntu 9.10 Karmic Koala

## Re: Beginners Programming Challenge 16

Can we presume that the length of the file will be (or should be) the exact right length? Because if so we needn't really take the length of the side, surely. Or might the input file be longer than we need?

3. Ubuntu Green Coffee Beans
Join Date
Sep 2010
Beans
0

## Re: Beginners Programming Challenge 16

Is it okay to use a non standard library?
This is my first challenge so I don't know the rules.
Language is C++ and SFML for the graphics.

PHP Code:
``` #include <iostream>#include <vector>#include <fstream>#include <sstream>#include <SFML/Graphics.hpp>typedef std::vector< std::vector<char> > matrix_type;struct Point{    Point(int x = 0, int y = 0)         : x(x),y(y){}    int x;    int y;};int ToInt(const std::string& str) {    std::istringstream is(str);    int x = 0;    is >> x;    return x;}void PrintMatrix(const matrix_type& matrix){    for(int i = 0; i < matrix.size(); ++i)    {        for(int j = 0; j < matrix[i].size(); ++j)            std::cout << matrix[i][j];            std::cout << "\n";    }    std::cout << "\n";}void LoadMatrix(matrix_type& matrix, std::ifstream& isfile){    for(int i = 0; i < matrix.size(); ++i)        for(int j = 0; j < matrix.size(); ++j)            isfile >> matrix[i][j];}const int PossibleMovements = 8;const Point Movements[PossibleMovements] = {    Point(1, 0),  Point(-1, 0),     Point(0, 1),  Point(0, -1),     Point(1, 1),  Point(1, -1),     Point(-1, 1), Point(-1, -1)};enum State{Dead = '0', Alive = '1'};void ChangeState(matrix_type& matrix, int row, int col, std::vector<Point>& changes){    int count = 0;    for(int i = 0; i < PossibleMovements; ++i)    {        int x = Movements[i].x + col;        int y = Movements[i].y + row;        if(x < 0 || y < 0 || x >= matrix.size() || y >= matrix.size() )            continue;        if(matrix[y][x] == Alive) ++count;    }    if(matrix[row][col] == Alive )    {        if(count < 2 || count > 3)            changes.push_back(Point(col, row) );        }    else if(count == 3)        changes.push_back( Point(col, row) );}void Pulse(matrix_type& matrix){    std::vector<Point> changes;    for(int i = 0; i < matrix.size(); ++i)        for(int j = 0; j < matrix.size(); ++j)            ChangeState(matrix, i, j, changes);    for(int i = 0; i < changes.size(); ++i)    {            char& c = (matrix[changes[i].y][changes[i].x]);        c = (c == '0') ? ('1') : ('0');    }        }void CommandLine(matrix_type& matrix){    PrintMatrix(matrix);        while(std::cin.get())    {                Pulse(matrix);        PrintMatrix(matrix);        std::cout << "Enter - Next pulse\n";    }}void Graphics(matrix_type& matrix){    sf::RenderWindow app(sf::VideoMode(800, 600), "Life");    const int TileSize = 10;        sf::Clock timer;        while(app.IsOpened())    {        sf::Event event;        while(app.GetEvent(event))            if(event.Type == sf::Event::Closed)                app.Close();                    app.Clear();        if(timer.GetElapsedTime() > 0.5f)        {            Pulse(matrix);                    timer.Reset();            }        for(int i = 0; i < matrix.size(); ++i)        {            for(int j = 0; j < matrix.size(); ++j)                if(matrix[i][j] == Alive)                    app.Draw(sf::Shape::Rectangle(TileSize * j, TileSize * i, TileSize, TileSize, sf::Color::Red));        }                app.Display();    }}void Run(matrix_type& matrix){    std::cout << "Graphics? [Y/N]: ";    char answer;    std::cin >> answer;        if(std::tolower(answer) == 'y')        Graphics(matrix);    else        CommandLine(matrix);    }int main(int argc, char** argv){        if(argc < 3)    {        std::cout << "Usage: " << argv[0] << " <filename> <size>\n";        return 1;            }        std::ifstream isfile(argv[1]);        if(!isfile)    {        std::cout << "Error: bad filename\n";        return 1;    }            const int Size = ToInt(argv[2]);        matrix_type matrix(Size, std::vector<char>(Size));    LoadMatrix(matrix, isfile);            Run(matrix);}    /*CPP=g++FLAGS=-Wall -Wextra -pedantic -ansiLIBS=-lsfml2-graphics -lsfml2-window -lsfml2-systemMain:    main.o    \$(CPP) \$(FLAGS) -o Main main.o \$(LIBS)        Main.o: main.cpp    \$(CPP) -c main.cpp*/  ```

4. ## Re: Beginners Programming Challenge 16

Yes the file will be the right length. I realize that you can do without the size, bonus points I guess.
To the non-standard library, can I download it from the ubuntu repo?
Last edited by pedro3005; October 9th, 2010 at 02:48 AM.

5. ## Re: Beginners Programming Challenge 16

Here's a few more patterns for people to test with. I'll withhold my code until some more real entries are in.

Beacon (4x4)
Code:
`1100110000110011`
Glider (10x10)
Code:
`0010000000101000000001100000000000000000000000000000000000000000000000000000000000000000000000000000`
Gosper's Glider Gun (38x25) (Very cool)
Code:
`00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000010100000000000000000000000001100000011000000000000110000000000000100010000110000000000001100110000000010000010001100000000000000001100000000100010110000101000000000000000000000001000001000000010000000000000000000000001000100000000000000000000000000000000001100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000`
38x38 if your program requires the board to be square:
Code:
`0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000001010000000000000000000000000110000001100000000000011000000000000010001000011000000000000110011000000001000001000110000000000000000110000000010001011000010100000000000000000000000100000100000001000000000000000000000000100010000000000000000000000000000000000110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000`
Last edited by schauerlich; October 9th, 2010 at 07:28 PM.

6. ## Re: Beginners Programming Challenge 16

Is the program supposed to emulate the game of life as well, should the image change or is it just the initial snapshot of the image?

7. ## Re: Beginners Programming Challenge 16

Yes, it should emulate it. The image should change according to the rules of the game. Tip: make a waiting time between the changes so I can actually observe them.

8. ## Re: Beginners Programming Challenge 16

EDIT: nevermind
Last edited by schauerlich; October 9th, 2010 at 06:37 PM.

9. ## Re: Beginners Programming Challenge 16

code has been re-factored, combined the algorithm for checking changes in rows above and below.

Python 3.1:
Code:
```import os

import sys

import time

def create_matrix(data, row_length):
master_list = []
temp_list = []
count = 0
for number in data:
temp_list.append(number)
count += 1
if count % row_length == 0:
master_list.append(temp_list)
count = 0
temp_list = []
return master_list

# testing for row existence of a row below the current cell
try:
temp = matrix[row]
if row  >= 0:
if (el - 1)  >= 0:
neighbor_a = matrix[row][el - 1]
else:
neighbor_a = 0
neighbor_b = matrix[row][el]
try:
neighbor_c = matrix[row][el + 1]
except IndexError:
neighbor_c = 0
else:
neighbor_a, neighbor_b, neighbor_c = 0, 0, 0
except IndexError:
neighbor_a, neighbor_b, neighbor_c = 0, 0, 0
return neighbor_a, neighbor_b, neighbor_c

def same_row(matrix, row, el):
if (el - 1) >= 0:
neighbor1 = matrix[row][el - 1]
else:
neighbor1 = 0
try:
neighbor2 = matrix[row][el + 1]
except IndexError:
neighbor2 = 0
return neighbor1, neighbor2

def map_cells(matrix):
row = 0
el = 0
new_row = []
while row != len(matrix):
cell = matrix[row][el]
#numbers surroundin the cell are called neighbors
neighbor1, neighbor2 = same_row(matrix, row, el)
#calculates change for row below current one
neighbor3, neighbor4, neighbor5 = adjacent_row(matrix, (row + 1), el)
#calculates change for row above current one
neighbor6, neighbor7, neighbor8 = adjacent_row(matrix, (row - 1), el)
total = neighbor1 + neighbor2 + neighbor3 + neighbor4 + neighbor5 + neighbor6 + neighbor7 + neighbor8
#calculates if cell lives, dies, or is reborn
if total < 2 or total > 3:
cell = 0
if cell == 0:
if total == 3:
cell = 1
el += 1
if el > len(matrix[row]) - 1:
row += 1
el = 0
new_row.append(cell)
return new_row

def main():
with open(sys.argv[1]) as f:
#convert numbers in file to list
row = [int(i) for i in f.replace('\n', '')]
matrix = create_matrix(row, int(sys.argv[2]))
while True:
os.system('clear')
for line in matrix:
for el in line:
#print out blocks instead of 1 and 0 for easier visual representation
if el == 1:
print("\u25FC", end='')
else:
print("\u25FB", end='')
print()
time.sleep(0.5)
new_row = map_cells(matrix)
matrix = create_matrix(new_row, int(sys.argv[2]))

if __name__ == "__main__":
main()```
Last edited by mo.reina; October 12th, 2010 at 08:49 AM.

10. ## Re: Beginners Programming Challenge 16

Originally Posted by mo.reina
by the way, can anyone point me to a site that has the initial patterns?
I wrote a few here you can use to test.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•