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.
Related
I am trying to make a 2d array that has shuffled elements in each row. For example, in a 3x5 array, each row will have 1, 2, and 3, but the order of the elements will be different:
what I want:
1 3 2
2 1 3
2 3 1
3 1 2
1 2 3
code I've tried:
//initialize a matrix
int[,] matrix = new int[3, 5];
Random rnd = new Random();
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i,j] = rnd.Next(1,3);
Console.WriteLine(matrix[i,j]);
}
Console.ReadLine();
}
It seems fairly easy, but as a newbie, I've been struggling for days over this problem.
Any help or lead will be appreciated!
You can make an List containing 1, 2, and 3, and then shuffle it for each row. Then just copy the shuffled values over:
public static void Main(string[] args)
{
int[,] matrix = new int[5, 3];
Random rnd = new Random();
var values = Enumerable.Range(1, 3).ToList();
for (int row = 0; row < matrix.GetLength(0); row++)
{
values = values.OrderBy(x => rnd.NextDouble()).ToList();
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[row, col] = values[col];
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
Sample Output:
2 3 1
3 1 2
3 2 1
1 3 2
2 1 3
Press Enter to Quit.
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 };
I wrote this code for a 1D array:
int[] arr= new int[9];
arr=Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse)
It takes my whole input at once and converts it as an array besides removing spaces. Where input is 1 2 3 4 5 6 7 8 9.
This same concept was tried for 2D arrays but still can't match. Here is my code,
int[,] arr = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
arr[i, j] =Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
}
}
My input is:
1 2 3
4 5 6
7 8 9
What is the solution? How can I input the entire 2D array at once in C#?
You should call Console.ReadLine for every line and then put in the values:
int[,] arr = new int[3, 3];
for (int i = 0; i < 3; i++)
{
int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
for (int j = 0; j < 3; j++)
{
arr[i, j] = temp[j];
}
}
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.
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.