D.Tomi
D.Tomi

Reputation: 71

Filling an array with true and false booleans randomly in c# (and other questions)

Currently studying on University, learning programming and I got a homework which i can't really solve.

My task is to create Conway's Game of Life where you make an array which you have to fill with "cells" These cells can be dead and alive, and you have tu randomly fill the array with random dead and alive cells. My first tought was to fill the cells with zeros and ones, zero represents the dead cells and ones represents the alive cells.

The game has a few rules, for example

This game goes on, has multiple rounds where all these cells change their state based on the rules. I have to keep track of a cells state changes and have to track the most numbers when it remained alive.

My questions are:

Sorry if i did ask a lot of questions. Thanks in advance! Tamas

Upvotes: 1

Views: 979

Answers (2)

MatteoCracco97
MatteoCracco97

Reputation: 416

The easiest way is to create the cell's class. Every cell has to contain a bool (false if is dead,true if is alive). (You could randomize the bool when you call the constructor)

The next step is to create an array of cells.

Now you could just use a thread on while true, and then inside of it you could use a foreach(Cell c in ArrayofCell)..... do something(for example respect the rules)

Upvotes: 0

Martynas
Martynas

Reputation: 188

Should you make a new class? You can if you want to. I know in some classes when they teach c# they want you to learn to create classes and object, but if that's not a requirement for your assignment you can manage without creating one.

Should you use true/false or 0/1? I don't really see a big difference between the two. True/false might use a bit less of the systems resources than 0/1, but I'm just guessing and it might depend on how you check their values.

How to fill an array with random Booleans? If you're using an array with 2 layers for your matrix I would do something like:

        int NumberOfColumns = 10;
        int NumberOfRows = 10;

        bool[,] Matrix = new bool[NumberOfRows, NumberOfColumns];

        Random rng  = new Random();

        for (int i = 0; i < NumberOfRows; i++)
        {
            for (int j = 0; j < NumberOfColumns; j++)
            {
                if (rng.Next(0, 2) == 1)
                {
                    Matrix[i,j] = true;
                }
                else
                {
                    Matrix[i,j] = false;
                }
            }
        }

Upvotes: 2

Related Questions