I'm doing my homework. I am assigned to create a Tic Tac Toe application, I've finished it but there's a small error, and I think I'm overlooking something, but I can't figure it out and need some new eyes to check it out because I think I'm looking at it for too long and missing a big concept.
Random r = new Random();//Creates the number generator.
int [][] numbers = new int [3][3]; //creates a 3x3 integer grid.
for (int i = 0; i< numbers.Length; i++){
for (int j=0;j<numbers[i].Length;j++){
numbers[i][j] = r.Next(2);//Traverses the array and inputs a number between 0 and 1 here.
}
}
Console.WriteLine("%d|%d|%d\n",numbers[0][0],numbers[0][1],numbers[0][2]);
Console.WriteLine("------");
Console.WriteLine("%d|%d|%d\n",numbers[1][0],numbers[1][1],numbers[1][2]);
Console.WriteLine("------");
Console.WriteLine("%d|%d|%d\n",numbers[2][0],numbers[2][1],numbers[2][2]);
The error is in the second line. Maybe I did the int [][] numbers = new int [][]; format wrong? Please help me identify what's wrong it. Thank you.
Try this when declaring your array:
int [,] numbers = new int[3,3];
You need to change your accesses to the array also fx:
numbers[i,j] = r.Next(2);
To iterate the array you can use numbers.GetLength(index) method instead of numbers.Length and numbers[i].Length.
In your case it would be something like this:
for (int i = 0; i < numbers.GetLength(0); i++)
{
for (int j = 0; j < numbers.GetLength(1); j++)
{
...
EDIT: If you really want to stay with your array of arrays (also called jagged arrays) you can initialize it like this:
int[][] numbers = new int[3][]
{
new int[3],
new int[3],
new int[3]
};
Related
I would like to get the output of this to be [1,2,3,4,...,200]. Any suggestions for how to go about this?
var Laser_data = 0;
var i = 0;
var j = 1;
int[] LaserData_200 = new int[200];
for (i = 0; i < LaserData_200.Length; i++)
{
Laser_data += j;
LaserData_200[i] = Laser_data;
Console.WriteLine(" " + LaserData_200[i]);
}
Current output:
1
2
3
4
ect.
Your array initialization and element assignment can be simplified massively. Your array is just the numbers 1 through 200 (inclusive). Enumerable.Range can generate that for you, then save it as an array.
int[] myArray = Enumerable.Range(1, 200).ToArray();
To print it all, string.Join it using a comma as a seperator.
Console.WriteLine($"[{string.Join(',', myArray)}]");
// [1,2,3,4,5,6,7,8,9,10,11,12,13, .... 200]
I see the title has nothing to do with the posted code.
So I am answering the question in the title.
Say you have two arrays a and b and you want to create a third array that combines the two arrays, then you write code like
int[] c = Enumerable.Concat(a, b).ToArray();
or you have and array a and you want to keep adding values to it in loop. When arrays are fixed size (a.IsFixedSize = true always) so you can do this efficiently.
The best solution is to use List<T> instead of an array
List<int> a = new List<int>()
for(int i=0; i<200; i++)
{
a.Add( i+1 );
}
and if you want an array in the end, you just do
int[] c= a.ToArray();
This question already has answers here:
2d Array in C# with random numbers
(2 answers)
Closed 4 years ago.
How do you print and save random values in array using Random.
So I need to have 10x10 table of rows containing random values from 0-9 but I seem to can't find a way how to get them printed!
int[,] mas = new int[9,9];
Random rand = new Random();
for (int i = 0; i <mas.Length; i++)
{
mas[i] = rand.Next(0,9);
Console.WriteLine(mas[i]);
for (int k = 0; k < mas.Length; k++)
{
mas[k] = rand.Next(0,9);
Console.WriteLine(mas[k]);
}
}
You have a small issue in your code: The array you create has two dimensions (int[9,9]). Therefore, whenever you want to read or write a cell, you need to provide two coordinates. You only set mas[i] or mas[k].
You should use max[i,k] instead in the inner loop. That way, every combination of coordinates will be tried out.
Unrelated: You mention you want a 10x10 grid of cells, but declare int[9,9]. While array indexing starts at 0, the size starts at 1. For example, if you create an array a = int[2], then it only contains entries at int[0] and int[1].
Similarly, the maximum parameter of the Random.Next(...) function is exclusive, so to get the value 9, you need to pass the maximum value 10.
If you want 2D array (i.e. you have two coordinates: lines - i and columns - j), nested loops is usual choice:
Random rand = new Random();
int[,] mas = new int[9, 9];
for (int i = 0; i < mas.GetLength(0); ++i)
for (int j = 0; j < mas.GetLength(1); ++j)
mas[i, j] = rand.Next(0, 10); // 10 will not be included, range [0..9]
Let's print the array:
for (int i = 0; i < mas.GetLength(0); ++i) {
for (int j = 0; j < mas.GetLength(1); ++j) {
Console.Write(mas[i, j]);
Console.Write(' '); // <- delimiter between columns
}
Console.WriteLine(); // <- delimiter between lines
}
Also, note that mas.length returns the overall length of the array, which will give you an IndexOutOfRangeException using your Code. Use mas.GetLength instead of mas.length
myArray.GetLength(0) -> Gets first dimension size
myArray.GetLength(1) -> Gets second dimension size
So your Code would look like this:
int[,] mas = new int[9, 9];
Random rand = new Random();
for (int i = 0; i < mas.GetLength(0); i++)
{
for (int k = 0; k < mas.GetLength(1); k++)
{
mas[i, k] = rand.Next(0, 9);
Console.Write(mas[i, k] + " ");
}
Console.WriteLine();
}
Probably like this
int[,] mas = new int[10, 10];
Random rand = new Random();
for (int i = 0; i < mas.GetLength(0); i++)
{
for (int k = 0; k < mas.GetLength(1); k++)
{
mas[i,k] = rand.Next(0, 9);
Console.Write(mas[i,k]);
}
Console.WriteLine("\n");
}
There are many things wrong with your code,
You dont know how indexing works - you want array of 10 times 10 but you create one with 9 times 9.
You need to specify both dimenstion when adding number to array.
Also,
Consolo.Writeline(string);
Will always write new line, something you dont want since you want to print 10 numbers, then new line with another then etc.
Im new to programming and struggling with this task:
In array X [20] random numbers from 1 to 30 are entered, in array Y enter only odd numbers from array X.
Print down Y.
int[] x = new int[20];
Random rnd = new Random();
int counter = 0;
int[] y;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 30);
if (x[i] % 2 !=0 )
{
y = new int[counter];
counter++;
y[counter] = x[i];
}
}
foreach (int number in y)
{
Console.WriteLine(number);
}
Im having problems to fill Y array with odd numbers without defining length of Y, I tried with adding counter but getting some errors all the time,
If someone can help me with some suggestions that would be helpful, thank you!
This looks like homework, so I guess using a more appropriate collection such as a List<int> is out of the question, just as using Linq.
At y = new int[counter]; you're reinitializing the array. This happens each iteration, so your final array only holds the latest added value, and all values before that will be set to their default: 0.
You could've seen this by debugging your code by setting breakpoints, stepping through the code and inspecting your variables. You could then also have provided a more proper problem description than "getting some errors".
If you know the input is never larger than 20, you can initialize the output array to the same size and keep a counter of how many values you copied (the latter of which you already do).
Then when printing, only print the elements up till that count with a for loop instead of foreach.
So something like this:
int[] x = new int[20];
int[] y = new int[x.Length];
Random rnd = new Random();
int counter = 0;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 30);
if (x[i] % 2 != 0)
{
y[counter] = x[i];
counter++;
}
}
for (int i = 0; i < counter; i++)
{
Console.WriteLine(y[i]);
}
Your problem is that you create a new y array for each odd number you find. You need to create the array only once and then fill it.
Since you don't know how many odd numbers there will be, I suggest to use a List<int> instead:
int[] x = new int[20];
Random rnd = new Random();
List<int> y = new List<int>(); // create the list before the loop
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 30);
if (x[i] % 2 !=0 )
y.Add(x[i]); // add odd number to list
}
foreach (int number in y)
{
Console.WriteLine(number);
}
See, In your case you are not aware about the number of odd numbers in that random array. so Array will not be a right choice here if you are following the current implementation. If you want the output as array, then Why not a simple LINQ with Where like this example:
First you collect all random numbers to your array as you are doing currently:
int[] randomIntegers = new int[20];
Random rnd = new Random();
for (int i = 0; i < randomIntegers.Length; i++)
{
randomIntegers[i] = rnd.Next(1, 30);
}
Now you have the all random numbers in x now perform the following operation:
int[] oddValues = randomIntegers.Where(a=> a % 2 !=0).ToArray();
Im getting this exeption thrown when the method is invoked. the list contains exactly 52 objects(number of cards).
Any suggestions what may cause it? maybe the Add and RemoveAt Methods? Or maybe the Random?
The compiler also tell the the problem is in deck.Add(temp[j]); line.
public void Shuffle()
{
List<Card> temp = new List<Card>();
Random rand = new Random();
for (int i = 0; i < 52; i++)
{
for (int j = rand.Next(i, 52); j < 52; j++)
{
temp.Add(deck[j]);
deck.RemoveAt(j);
deck.Add(temp[j]);
}
}
}
Ok, let's imagine we are on the first run through the loops. First iteration of both the outer and inner loop. i is 0, and Rand(i, 52) produces 13.
So we have:
i - 0
j - 13
temp - empty list
deck - assume this is a list with 52 elements
Now let's run the three lines of code inside the loop:
temp.Add(deck[j]);
Get the 13th item of deck and add it to temp. Ok, done. temp now has 1 item.
deck.RemoveAt(j);
Remove the 13th item in deck. Ok, fine.
deck.Add(temp[j]);
Get the 13th item in temp and add it to, wait, what?1? temp only has 1 item! Exception! Exception!.
There isn't a need for the temp list in the first place. There is a very good shuffling algorithm that involves going through the original list of items once (not N times). And you just need one temp variable to hold a value while you swap it with another. Like this:
public void Shuffle()
{
Card temp;
Random rand = new Random();
for (int i = deck.Length; i >= 1; i--)
{
int j = rand.Next(0, i + 1);
temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
Done.
If you want to shuffle list of items then you can use the following method:
public static void Shuffle<T>(IList<T> arr, Random rnd)
{
for (var i = 0; i < arr.Count; i++)
{
var j = rnd.Next(i, arr.Count);
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
This method will help you shuffle your deck without ArgumentsOutOfRangeExeption
temp[j] does not neccessarily exist. You will need to initialize temp so it has at least j+1 entries or you need to change the line of temp[j] to something more fitting.
When you call rand.Next(i, 52), the result could be 52, which would be out of range for your deck and temporary deck.
Also, you need to initialize your temp list, as #nvoigt points out. List has a constructor that takes an integer for the initial size. You could pass in 52. See: http://msdn.microsoft.com/en-us/library/dw8e0z9z(v=vs.110).aspx.
You could have also easily debugged this yourself by looking at the value of j in your debugger.
I have an somewhat basic question regarding multidimensional arrays in C#.
Currently I have the following array:
float[] matrix = new float[16];
I need to create instead a 2D array with each line containing the previously mentioned 16 float numbers. Also, the number of lines in the 2D array is not known at the start of the program (i.e. it will be based on a variable).
How can I create such an array using an efficient data structure?
You could do something like this:
const Int32 arraySize = 16;
var list = new List<float[]>();
Which gives you an empty list containing zero elements (arrays) to start. As you need to add new arrays you would write this:
var array = new float[arraySize];
// do stuff to the array
And then add it to the list:
list.Add(array);
To store 16 float numbers, you could use a 4x4 matrix (which is a 4x4 2-dimensional array). For more details, check out this documentation.
// init the array
float[,] matrix = new float[4,4];
// loop through the array
for(int col = 0; col < matrix.GetLength(0); col++)
for(int row = 0; row < matrix.GetLength(1); row++)
Console.WriteLine(matrix[col, row]);
You can use multidimentional array syntax
float[,] arr2D = new float[12,12];
Alternatively, you could use a loop
float[][] floats = new float[12][];
for(int i=0; i< 12; i++)
{
floats[i] = new float[12];
}