Simagen
Simagen

Reputation: 419

2 dimensional array

For each element in the array I need a unique identifier such as Seat1, Seat2, Seat 3....... all the way to the end of the length of the array.

currently I have done the following:

int rows = 10, cols = 10;
bool[ , ] seatArray = new bool[rows , cols]; //10 rows, 10 collums

for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++ )
    {
        seatArray[i, j] = false;
    }

    foreach (bool element in seatArray)
    {
        Console.WriteLine("element {0}", element);
    }
}

this simply just says "Element False" x 100 in the console.

i need to replace "Element" with Seat1, Seat2, Seat3....to the end of the array length.

any help will be much appreciated!

thank you!

Upvotes: 1

Views: 3458

Answers (3)

Simagen
Simagen

Reputation: 419

tvanfosson, i am struggling to make your coding work, iv put it into a new class off my main method see below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Class1
    {
        public class Seat
            {
                public string ID { get; set; }
                public bool Occupied { get; set; }
            }

            int rows = 10, cols = 10;
            Seat[,] seats = new Seat[rows,cols];

            for (int i = 0; i < rows; ++i )
            {
                for (int j = 0; j < cols; ++j)
                {
                     seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
                }
            }

            foreach (var seat in seats)
            {
                Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
            }
    }
}

is this correct as i seem to be receiving a lot of syntax errors

thank you!

Upvotes: 0

loosecannon
loosecannon

Reputation: 7803

  int count = 1;

for (int i = 0; i < rows; i++)
  for (int j = 0; j < cols; j++ )
  {
    seatArray[i, j] = count;
    count++;
  }

  foreach (bool element in seatArray)
  {
    Console.WriteLine("element {0}", element);
  }

no idea what language this is so idk the syntax but just do some external counter to number them

that just says false every time you set every one to false, dont use a bool, or write a class to hold the true false and number info

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532445

Create a Seat class (or structure, if more appropriate) with ID and Occupied(?) properties. Make an array of this type.

public class Seat
{
    public string ID { get; set; }
    public bool Occupied { get; set; }
}

int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];

for (int i = 0; i < rows; ++i )
{
    for (int j = 0; j < cols; ++j)
    {
         seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
    }
}

foreach (var seat in seats)
{
    Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}

Upvotes: 4

Related Questions