How can I fill a Matrix row by row - c#

So I have this problem:
A person has N shops in a city. Write a console app which receives from input:
on the first line, N
next N lines, each of them containing the profit of every shops for each of the year trimesters, with 2 decimals precision. Numbers are separated by one space.
Output :
most profitable trimester;
most profitable shop;
Example:
2
1000.50 2000.00 1000.00 3000.00
500.00 600.00 700.00 800.00
Result:
Trimester 4 : 3800.00 Shop 1 : 7000.50
Now about my question... I've written some code, but I don't know how to fill the matrix row by row. Here is my code:
class Program
{
static void Main(string[] args)
{
const int numberOfTrimesters = 4;
int numberOfShops = Convert.ToInt32(Console.ReadLine());
double[,] shopsList = new double[numberOfShops, numberOfTrimesters];
for (int i = 0; i < numberOfShops; i++)
{
string input = Console.ReadLine();
string[] array = input.Split(' ');
double[] shop = new double[array.Length];
for (int j = 0; j < array.Length; j++)
shop[j] = Convert.ToDouble(array[j]);
for (int k = 0; k < numberOfShops; k++)
for (int m = 0; m < numberOfTrimesters; m++)
shopsList[k, m] = shop[array.Length];
}
The problem is on last line of the last for.

Related

Battleship game C#

I am stuck upon a problem about namimng the colums and the lines, differently than 0 to 10. something like this picture, the lines starting from the bottom 1 to 10 and colums from A to J.
I've created a program that tells me if the ship is destroyed or not, after using 14 moves( in this image using move 5 c, in my program 5 2, counts as a hit, if all the blue squares are hit the program returns destroyed).
My problem is that i don't know why i can't user input a move like "4 a" (Input string was not in a correct format.' - after debugging). I wrote the following code:
char[,] board = new char[10, 10];
int table = 10;
int hits = 2;
int totalHits = 14;
int neededHits = 8;
for (int i = 9; i >= 0; i--)
{
string line = Console.ReadLine();
string[] boardCharacters = line.Split(' ');
for (int j = 0; j < table; j++)
{
board[i, j] = Convert.ToChar(boardCharacters[j]);
}
}
int countHits = 0;
for (int z = 0; z < totalHits; z++)
{
var ac = Console.ReadLine().Split(' ');
var c1 = int.Parse(ac[0]) - 1;
var c2 = (ac[1].ToLower()[0] - 'a');
int[] attack = new int[2];
for (int i = 0; i < hits; i++)
{
attack[i] = int.Parse(ac[i]);
}
if (board[attack[0], attack[1]] == 'x')
{
countHits++;
}
}
Console.WriteLine(countHits == neededHits ? "destroyed" : "not destroyed");
Console.ReadLine();
Your problem is in this section:
var ac = Console.ReadLine().Split(' ');
var c1 = int.Parse(ac[0]) - 1;
var c2 = (ac[1].ToLower()[0] - 'a');
int[] attack = new int[2];
// You've already parsed the two parts of the input into 'c1' and 'c2'.
// This loop is redundant, and is the cause of the problem.
for (int i = 0; i < hits; i++)
{
// When 'i' = 1, this is looking at the second part of the input ("a")
// and trying to parse it as a number. This is what causes the exception.
attack[i] = int.Parse(ac[i]);
}
I would suggest removing that loop, and populate the 'attack' array when you create it:
int[] attack = new int[] { c1, c2 };

Comparison of grades of students and Coins distributions

I'm stuck at this. I`m beginner into software development. You get a list of N students and then a list of ratings for each student. A student which has bigger rating than his neighbour from list gets more coins than both of them. For example:
Data input:
3
John
Dan
Sam
9
10
8
Data output:
John 1
Dan 3
Sam 1
My output is just the names of the students.
I wrote this code:
using System;
class Program
{
private static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
var numberCoins = new int[n];
string[] studentNames = new string[n];
numberCoins[0] = 1;
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine();
}
int[] grades = new int[n];
for (int i = 0; i < n; i++)
{
grades[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 1; i < n; i++)
{
if (grades[i] > grades[i - 1])
{
numberCoins[i] = numberCoins[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--)
{
if (grades[i] > grades[i + 1])
{
numberCoins[i] = numberCoins[i + 1] + 1;
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(studentNames[i], " ", numberCoins[i]);
}
Console.ReadLine();
}
}
You didn't mention if there is any pattern to give coins to the students. And if we have specific number of coins or not.
If we consider at first no one has any coins the result must be something like the following:
Please specify the number of the students:
3
Please write students' name (after each name hit the ENTER):
John
Dan
Sam
Please write students' ratings (after each rating hit the ENTER):
9
10
8
The result:
John: 0
Dan: 2
Sam: 0
I wrote a piece of code which might help you approach the functionality you want.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please specify the number of the students:");
int n = int.Parse(Console.ReadLine());
string[] studentNames = new string[n];
int[] studentRatings = new int[n];
int[] studentCoins = new int[n];
Console.WriteLine();
Console.WriteLine("Please write students' name (after each name hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentNames[i] = Console.ReadLine() ?? string.Empty;
}
Console.WriteLine();
Console.WriteLine("Please write students' ratings (after each rating hit the ENTER):");
for (int i = 0; i < n; i++)
{
studentRatings[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("The result:");
for (int i = 0; i < n; i++)
{
int coins = 1;
studentCoins[i] = 0;
if (i != 0)
if (studentRatings[i] > studentRatings[i - 1])
coins++;
if (i != n - 1)
if (studentRatings[i] > studentRatings[i + 1])
coins++;
studentCoins[i] = coins;
}
for (int i = 0; i < n; i++)
{
Console.WriteLine($"{studentNames[i]}: {studentCoins[i]}");
}
}
}

input 2d array sideways

how can I input an integer array sideways not downward? suppose it has array [2,2] then in c # :
input :
1
2
3
4
I want to store like this:
1 2
3 4
what should i do? I am confused, as for the code I use:
int length = Convert.ToInt16(Console.ReadLine());
int[,] box = new int[length, 2];
for(int i = 0; i<length; i++){
for(int j = 0; j<2; j++){
photo[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
static void Main(String[] args){
int length = Convert.ToInt32(Console.ReadLine());
int[,] box = new int[length, 2];
for (int i = 0; i < length; i++){
box[i, 0] = Int32.Parse(Console.ReadLine());
box[i, 1] = Int32.Parse(Console.ReadLine());
}
}
As you have mentioned that you have two columns it might give you a better understanding.For each row since we have two columns due to that I we are fetching values two times.

Accepting a 'n x n' Matrix in C#

I've been bugged with this idea for a while.
Accepting an array with spaces is not straight forward in c#. How do we accept a 2d array, whose size is given by the user? I tried this, but something isn't right. Help is much appreciated. Thank You.
Input:
4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Where the first line specifies the value of 'n' in 'n x n'
Well, the code i tried was this. This might look stupid for a few of you :
string input;
string[] inputArray;
int[] inputInt;
int MxM = Convert.ToInt32(Console.ReadLine()); //MxM = First Line=n
int[,] array = new int[MxM, MxM];
for (int i = 0; i < MxM; i++)
{
for (int j = 0; j < MxM; j++)
{
input = Console.ReadLine();
inputArray = input.Split(' ');
inputInt = new int[MxM];
for (int k = 0; k < MxM; k++)
{
inputInt[k] = int.Parse(inputArray[k]);
array[i, j] = inputInt[k];
}
}
}
Hopefully, the answer for this will also be the answer to output a matrix. Thank You
Either:
for (int i = 0; i < MxM; i++)
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(Console.ReadLine());
or:
for (int i = 0; i < MxM; i++)
{
inputArray = Console.ReadLine().Split(' ');
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(inputArray[j]);
}
which, of course, could fail if you don't enter in the right format.
If I am understanding what you want correctly:
You would like to take an input N, in your example 4, with that - create a 4 x 4 array. Then for each index in the first dimension, ask the user for input equating to N number of integers separated by spaces. Read that input and place it into the array at the proper 2d-index. So with 4 as the first input, the user will be prompted something like:
Please input 4 integers(separated by spaces):
The user would type in, for example:
Please input 4 integers(separated by spaces): 1 2 3 4
And hit enter. Again the user is prompted:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces):
And so on until:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces): 2 3 4 5
Please input 4 integers(separated by spaces): 3 4 5 6
Please input 4 integers(separated by spaces): 4 5 6 7
You could probably use something like the following in this case:
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Please enter the size of the matrix:");
if (!int.TryParse(Console.ReadLine(), out size))
{
Console.WriteLine("The value provided for the size was not a proper integer value.");
Console.WriteLine("Press ESC to quit...");
while (Console.ReadKey().Key != ConsoleKey.Escape) { }
return;
}
int[,] matrix = new int[size, size];
for (int i = 0; i < size; ++i)
{
bool complete = false;
while (!complete)
{
Console.WriteLine(string.Format("[{0}] - Please input {1} integers(separated by spaces):", i, size));
string[] input = Console.ReadLine().Split(' ');
if (input.Count() != size)
{
Console.WriteLine("The input was invalid, try again...");
continue;
}
for (int j = 0; j < size; ++j)
{
if (!int.TryParse(input[j], out matrix[i, j]))
{
complete = false;
Console.WriteLine("The input was invalid, try again...");
break;
}
complete = true;
}
}
}
Console.WriteLine("Output: \n");
WriteMatrix(matrix, size);
Console.ReadKey();
}
private static void WriteMatrix(int[,] matrix, int size)
{
string output = string.Empty;
for(int i = 0; i < size; ++i)
{
string line = string.Empty;
for (int j = 0; j < size; ++j)
line += string.Format("{0} ", matrix[i, j]);
output += string.Format("{0}\n", line.Trim());
}
Console.WriteLine(output);
}
}
The code above should be mostly safe against the user typing invalid values, but you could probably spend some time to clean it up or enhance it some more. The basic idea is there.
You can try to use code like this:
Console.ReadLine().Split().Select(str => Convert.ToInt32(str)).ToArray()
to get an int array out of the line.
I think you understood the idea.
public static int[,] MatrixConstructor()
{
int N = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++)
{
String[] line = Console.ReadLine().Split(' ');
for (int j = 0; j < N; j++)
{
matrix[i,j] = Convert.ToInt32(line[j]);
}
}
return matrix;
}
This conforms to your input.

C# program that returns morse code for numbers not working

I'm trying to make a program that: When given a 4 digit number (for example, 1001) it sums the digits of that number, for 1001 this is 1 + 0 + 0 + 1 = 2, than it finds all sequences of 6 numbers from 1 to 6 (including permutations, i.e. 1*1*1*1*1*2 is different than 2*1*1*1*1*1) whose product is that number.
The result should be printed on the console in the following format: each sequence of 6 numbers, with their Morse representation, separated with a single pipe: 1 is .---- , 2 is ..---: .----|.----|.----|.----|..---|, on a new row the next permutation: .----|.----|.----|..---|.----| and so on.
The problem is, my solution doesn't show the correct answers, not even the correct number of them.
Here's my code (and please, if possible, tell me where my mistake is, and not some one line hack solutions to the problem with LINQ and regex and God knows what):
string n = Console.ReadLine();
string[] digitsChar = new string[n.Length];
for (int i = 0; i < 4; i++)
{
digitsChar[i] = n[i].ToString();
}
int[] digits = new int[digitsChar.Length];
for (int i = 0; i < 4; i++)
{
digits[i] = Convert.ToInt32(digitsChar[i]);
}
int morseProduct = digits.Sum();
Console.WriteLine(morseProduct);
List<int> morseCodeNumbers = new List<int>();
for (int i = 1; i < 6; i++)
{
for (int j = 1; i < 6; i++)
{
for (int k = 1; i < 6; i++)
{
for (int l = 1; i < 6; i++)
{
for (int m = 1; i < 6; i++)
{
for (int o = 1; o < 6; o++)
{
int product = i * j * k * l * m * o;
if (product == morseProduct)
{
morseCodeNumbers.Add(i);
morseCodeNumbers.Add(j);
morseCodeNumbers.Add(k);
morseCodeNumbers.Add(l);
morseCodeNumbers.Add(m);
morseCodeNumbers.Add(o);
}
}
}
}
}
}
}
int numberOfNumbers = morseCodeNumbers.Count;
string[] morseCodes = new string[] { "-----", ".----", "..---", "...--", "....-", "....." };
for (int i = 0; i < numberOfNumbers; i++)
{
int counter = 0;
if (i % 5 == 0)
{
Console.WriteLine();
counter = 0;
}
if (counter < 5)
{
int index = morseCodeNumbers[i];
Console.Write(morseCodes[index] + "|");
counter++;
}
A lot of your for-loop conditions refer to i instead of j,k,l and m. The same for the increment part. For example:
for (int j = 1; i < 6; i++)
should be
for (int j = 1; j < 6; j++)
Furthermore if the range is from 1 to 6 you need to change < to <=, see:
for (int i = 1; i <= 6; i++)
You don't need to convert the string to a string array to get the int array of digits btw, so while this is correct:
for (int i = 0; i < 4; i++)
{
digitsChar[i] = n[i].ToString();
}
int[] digits = new int[digitsChar.Length];
for (int i = 0; i < 4; i++)
{
digits[i] = Convert.ToInt32(digitsChar[i]);
}
you could it do like that (sry for LINQ):
var digits = n.Select(c=>(int)char.GetNumericValue(c) ).ToArray();

Categories

Resources