Need to calculate the number of ships. Ships are presented as a “battleship” game.
“1” represents a ship, “0” represents water. C#
namespace Ships
{
class Program
{
static int[,] ships = new int[10, 10] {
{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
{ 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, },
{ 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, },
{ 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, },
{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, }
};
static void Main(string[] args)
{
int count = 0;
// code write here
Console.WriteLine(count);
Console.ReadLine();
}
}
}
CodePudding user response:
Based on the rewritten question and clarification in your comment..
int count = ships.Cast<int>().Count(x => x == 1);
This will count the number of 1's in your 2D array (i.e. 20, in your example). Sum()
would be slightly simpler, but I think Count
is a little more self-documenting in this use case, and is simpler to change if you decide to use a value other than 1.
For a non-LINQ approach, you'd do something like:
int count = 0;
for (int i = 0; i < ships.GetLength(0); i )
{
for (int j = 0; j < ships.GetLength(1); j )
{
if (ships[i, j] == 1)
count ;
//Could also just do:
//count = ships[i, j];
//Since you're only working with 1 and 0
}
}
CodePudding user response:
Not possible: imagine you have this:
1 1 1
1 1 1
Are these two of length 3 or three of length 2?
You need to clarify your problem.
CodePudding user response:
given the new question this should be enough for you:
int count = ships.Cast<int>().Sum();
with a simple search through the internet you would have easily found this though