2 dimensional array - c#

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!

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" );
}

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

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!

Related

A method to search Id inside a matrix -Trouble with output

I am new at programming and I am trying to create a method that allows me search Id inside a [10,4] matrix, however I don't get how to do it without using nested fors and also if and else statement. The problem is related to output, I know the structure isn't correct, but since I don't what else can be done I am trying make it as it is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace menu
{
class Program
{
enum header { id, name, surname, addres };
public static int id = 1;
static void Main(string[] args)
{
string[,] matrix = new string[10, 4];
insertStudent(matrix);
idSearch(matrix);
Console.ReadKey();
}
static int generateId()
{
return id++;
}
static void insertStudent(string[,] matrix)
{
int n = generateId();
matrix[n - 1, 0] = Convert.ToString(n);
for (int i = 1; i < matrix.GetLength(1); i++)
{
do
{
Console.WriteLine($"Insert {Enum.GetName(typeof(header), i)}");
matrix[n - 1, i] = Console.ReadLine();
}
while (String.IsNullOrEmpty(matrix[n - 1, i]));
}
}
static void idSearch(string[,] matrix)
{
int idChosen=0;
Console.WriteLine($"Insert ID you want to visualize:");
int.TryParse(Console.ReadLine(), out idChosen);
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (matrix[i, 0] == Convert.ToString(idChosen))
{
Console.WriteLine(matrix[i, j]);
}
else
{
Console.WriteLine("The chosen ID does not exist");
}
}
}
}
}
}
Right now you printing "The chosen ID does not exist" every time you check an index in your matrix. You want to move that statement to outside of your loop after you've already checked every index. Right now that check is really saying that your ID is not in that specific cell. I've altered your code slightly to reflect this. I also fixed your check to be on matrix[i,j] instead of matrix[i,0]
Also using a nested for loop is OK to use. I don't believe C# has any built in helper methods for searching multidimensional arrays.
bool found = false;
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (matrix[i, j] == Convert.ToString(idChosen))
{
//note that this will print your id
Console.WriteLine(matrix[i, j]);
//this would print where it found it
Console.WriteLine("Found at [" + i + "," + j + "]");
found = true;
}
}
}
if (!found)
{
Console.WriteLine("The chosen ID does not exist");
}

Show sublist value from index C#

My problem is I have M subproblem. Each subproblem include x (double array) and reduced cost which has different value for each iteration m. I want to show x which has the minimum reduced cost among all subproblems. here is my class:
public class Subproblem
{
public double[,] x { get; set; }
public double ReducedCost { get; set; }
}
So far, I already can get the minimum Reduced Cost and index of it. Now I want to show x value (double array) which on that index. I've code like this:
var sub = new List<Subproblem>();
for (int m = 0; m < M; ++m)
{
Subproblem s = new Subproblem();
s.x = new double[DC1, DC1];
s.ReducedCost = model.ObjVal;
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
s.x[i, j] = x[i, j].X;
}
}
sub.Add(s);
}
double minRC = sub.Min(a => a.ReducedCost);
int minRCIndex = sub.FindIndex((i) => i.ReducedCost == minRC);
Console.WriteLine(sub.x(minRCIndex));
the last line (Console.WriteLine(sub.x(minRCIndex));) still got red underline, I don't know how to write it
If you are only trying to get the minimum Reduced Costed subproblem you should be doing:
Subproblem minimumReducedCostedSubproblem = sub[minRCIndex];
And you can print the matrix down like this:
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.Write(minimumReducedCostedSubproblem.x[i, j] + "\t");
}
Console.Write("\n");
}
But you seem a little confused. You are pushing a Subproblem into your sub list with the same object for M times. Because model.ObjVal doesn't change along the first for loop. There is something wierd going on there too.
It should be
var objWithMinReduceCost = sub[minRCIndex];
//Now you have the object of Subproblem derived from your logic.
//You can access x property of it have further logic to process it.
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.WriteLine(objWithMinReduceCost.x[i, j]);
}
}
If you are interested in obtaining the double array, you could just do this:
double[,] result = sub.First(i => i.ReducedCost == minRC).x;
Although as Tolga mentioned, all your elements will have the same ReducedCost with your current code.

Comparing two variable in a structure C#

What I want to do is compare two of the same variable in a structure.
For example I have a structure like so:
struct player
{
public string name;
public int number;
}
static player[] players = new player[3];
and what I want to do is compare the numbers, so that if two players have the same number, something will happen.
This is what I tried, however it would always say two numbers were the same because it would compare two of the same
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
Hopefully you understand what I mean.
Any help would be really appreciated!
Thanks
Problem is in your loop variables i and j starting both at index zero. Then you are comparing element zero to element zero and therefore the condition is true.
Update this line:
for (int j = 0; j < length; j++)
to this:
for (int j = i + 1; j < length; j++)
Edit
To be more precise. The condition evaluates to true not only for the first element, but for each element when i and j are the same. This solution bars both control variables from having the same value in any iteration.
Simple, just add a check to make sure you aren't comparing the same index, because this is the same object:
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (i == j) continue;
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
Use a Class, and do it using Linq:
public class Player
{
public string Name { get; set; }
public int Number { get; set; }
}
Then in the other class have this method to cross-check
private void Match()
{
var players = new Player[3].ToList();
foreach (var found in players.ToList().Select(player => players.FirstOrDefault(p => p.Number == player.Number)))
{
if (found != null)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
}

how to initialize ArrayObject value to ZERO in C#

I have
Cell[,] cells = new Cells[6,6];
I want to initialize it all values to zero
I did something like this
for(int i=1; i<=6;i++) {
for(int j=1; j<=6; j++) {
cells[i,j] = 0;
}
}
The problem is it cant convert int 0 to Cell type. How do I initializze them to zero for first time?? For eg: I have [6,6] array and I want to assign every Cell[2,3].Value = 0
Thanks
The problem is it cant convert int 0 to Cell type. How do I initializze them to zero for first time??
Going by your Class make x and y public first (assuming you are accessing them in methods not in your Cell class:
class Cell
{
public int x;
public int y;
Warrior warrior;
};
Then you should get access to your class members:
Cell[,] cells = new Cells[6,6];
for(int i=0; i<6;i++)
{
for(int j=0; j<6; j++)
{
cells[i,j].x = cells[i,j].y = 0;
}
}
The above is for resetting the values to 0. If you want this on initialization then create a constructor:
Cell(Warrior getWarrior)
{
x = 0;
y = 0;
warrior = getWarrior;
}
Cells[,] cells = new Cells[6, 6];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
cells[i, j]= new Cells(sendWarrior);
Console.WriteLine("\t{0} {1}", cells[i, j].x, cells[i, j].y);
}
}
You can put it like that:
class Cell {
public int x {get; set;}
public int y {get; set;}
Warrior warrior {get; set;}
};
Cell[,] cells = new Cells[6, 6];
// Arrays are zero-based in C#, so they start with 0
for(int i = 0; i < Cells.GetLength(0); i++) // <- Better get length than put "6"
for(int j = 0; j < Cells.GetLength(1); j++)
cells[i, j] = new Cell() { // <- Do not forget to create Cell
x = 0, // <- Overshoot, x will be 0 by default, to show the trick only
y = 0 // <- Overshoot, y will be 0 by default, to show the trick only
};

removing elements from this C# program [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any chance to get unique records using Linq (C#)?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WaysOf100
{
class WaysOf100Test
{
static void Main(string[] args)
{
WaysOf100 test= new WaysOf100();
test.Go();
test.EliminateDuplicates();
}
}
class WaysOf100
{
List<string> results = new List<string>();
public void Go()
{
int num = 5, temp=0;//to store the intermediate difference
for (int i = 1; i <num; i++)
{
temp = num - i;
for (int j = 1; j <= temp; j++)
{
if (temp % j == 0)
{
//Console.Write(i + " ");
string text = "";
text = i.ToString();
for (int k = 1; k <= (temp / j); k++)
{
//Console.Write(j + " ");
text += j.ToString();
}
char[] rev = text.ToCharArray();
Array.Reverse(rev);
if(!(results.Contains(rev.ToString())))
results.Add(text);
}
}
}
}
public void EliminateDuplicates()
{
//To eliminate the duplicates
/*for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char [] rev = results[j].ToCharArray();
Array.Reverse(rev);
if (results[i]==rev.ToString())
results.Remove(rev.ToString());
}
}
}*/
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is :{0}",results.Count);
}
}
}
The result so far is
11111
122
14
2111
23
311
32
41
This is what I want in short : the reverse of 41 is 14 and 14 already exists in the list so i don't want to add 41. Similarly, the reverse of 32 is 23 which also exists and hence 32 should not be added. But this piece of could which I've written to achieve the functionality is not giving the desired results
if(!(results.Contains(rev.ToString())))
results.Add(text);
The problem you are having is that rev.ToString()' returns "System.Char[]" and not the string value you wanted/expected. For your logic, try the following:
public void EliminateDuplicates()
{
//Eliminate the duplicates
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char[] rev = results[j].ToCharArray();
char[] forward = results[i].ToCharArray();
Array.Reverse(rev);
bool bEqual = true;
for( int n = 0 ; n < results[j].Length && true == bEqual ; n++ )
{
if( rev[n] != forward[n] )
{
bEqual = false;
}
}
if( true == bEqual)
results.Remove(results[j] );
}
}
}
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is : {0} ", results.Count);
}
Solved by myself finally..
if (!(results.Contains(new string(rev))))
results.Add(text);
changed the rev.ToString() as new string(rev) and works fine now. What I want is achieved. Thanks a lot for the help guys
Is reverse the only case you want to check for? One approach would be to canonicalize your results to e.g. sorted order before comparing. So transform both 132 and 213 to 123 before comparing.

Categories

Resources