Search code examples
c#celldrawrectangle

10*10 table, cell's neighbor count


So I've got this code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click_1(object sender, EventArgs e)
    {
        Table t = new Table();
    }
}
class Cell
{
    Point position;
    const int SIZE = 20;
    Cell[] neighbors;
    public Cell(Point position, Random r)
    {
        this.position = position;
        Visualisation(r);
    }
    void Visualisation(Random r)
    {
        Graphics paper= Form1.ActiveForm.CreateGraphics();
        paper.DrawRectangle(new Pen(Color.Red), position.X, position.Y, SIZE, SIZE);
    }
}
class Table
{
    Cell[] table = new Cell[100];
    public Table()
    {
        Random r = new Random();
        for (int i = 0; i < 100; i++)
        {
            table[i] = new Cell(new Point(i % 10 * 20 + 40, i / 10 * 20 + 40), r);
        }
    }

And i would write the number to the all cells, how many neighbors got each cells. How should I do that? Cella[] szomszedok; is the part where i should count how many neighbors got each cells. The goal what i need in the cells:

3 5 5 5 5 5 5 5 5 3
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
5 8 8 8 8 8 8 8 8 5
3 5 5 5 5 5 5 5 5 3

Solution

  • There are many possible approaches for this.

    A naive approach would be to create an GetIndex(int x, int y) method to get the index to use for table[]. Let it return -1 for a position that is not on the grid. Then create a GetCell(int x, int y) method that calls GetIndex() and returns the given cell, or null for a position that is not on the grid.

    Now you can count the neighbors for a given cell at [x, y] by introducing a method that finds the neighbors:

    public List<Cell> GetNeighbors(int x, int y)
    {
        var neighbors = new List<Cell>();
        neighbors.Add(GetCell(x - 1, y - 1));
        neighbors.Add(GetCell(x + 0, y - 1));
        neighbors.Add(GetCell(x + 1, y - 1));
        // ...
        neighbors.Add(GetCell(x + 1, y + 1));
    
        return neighbors;
    }
    

    Then to count a cell's neighbors, just count table.GetNeighbors(x, y).Count(n => n != null).