Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
using System;
class TwoD
{
static void Main()
{
int[][,] a = new int[3][,];
a[0] = new int[2, 2];
// a[1] = new int[3, 3];
int i,j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[0][i,j] = i;//confused
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine(a[0][i, j] + " ");
Console.WriteLine();
}
}
This is the program and the output is
0
0
1
1
But i am little bit confused about initialisation of jagges array where i have commented. Please tell me the initialisation of jagged two dimentional array and correct me if i am wrong.
Not sure about where you are confused but I guess only confusion is about mixture of jagged array and multidimensional array. i.e. a[][] is jagged array, the second dimension can have any (or no) length. You have to initialize each dimension in a separate look While multidimensional array have same length for each dimension and that's why you can pre-initialize the multidimensional array. Like a[2,5].
Below example will explain more about initialization of each kind of array and how you can write more dynamic code of your example.
//jagged array sample of initialization
int[][] jagged = new int[3][];
for (int i = 0; i < jagged.Length; i++)
jagged[i] = new int[i + 4]; //each element of jagged array can have different length
//multidimensional array sample of initialization
int[,] multiD = new int[3, 4]; //that's it.
//multiD.GetLength(0) is 3 and multiD.GetLength(1) is 4
//Your example.
int[][,] a = new int[3][,];
a[0] = new int[2, 2];
a[1] = new int[3, 4];
int interationOrder = 0;
for (int jag = 0; jag < a.Length; jag++)
{
//considering rank of multidimentional array is always 2 (Rank of [,] = 2, Rank of [,,] = 3)
if (a[jag] == null)
continue;
for (int i = 0; i < a[jag].GetLength(0); i++)
{
for (int j = 0; j < a[jag].GetLength(1); j++)
{
a[jag][i, j] = interationOrder++;//no confusion :) this is corret.
}
}
}
Related
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];
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i am trying to create minesweeper in c# to do this i create an multidimensional array and then randomly pick positions using
Random rand = new Random;
the problem comes when trying to run the code, when i run it it takes an extremely long time to finish, i suspect it is because of the while loop and the if statements, if the rand.Next keeps getting the same values it could cause the loop to run for a long time. is there something im doing that is afftecting the pseudo randomness of my numbers. code below.
after returning to this questing a while later in an attempt to make it less horrendous it is clear that the reason for the program taking so long to run lies within the
while (counter < numberOfMines)
{
if (Minefield[randomNumber1, randomNumber2] == 9)
{
counter--;
}
else
{
Minefield[randomNumber1, randomNumber2] = 9;
counter++;
}
randomNumber1 = (rand.Next(4)) + 1;
randomNumber2 = (rand.Next(4)) + 1;
}
section of the code. The reason that it was taking so long is that i was treating the while loop like a for loop and taking away from the counter when it was failing to place a mine. this is incorrect and i should have just not added to it.
using System;
class MainClass
{
static void Main(string[] args)
{
int boardSize = 5;
int numberOfMines = 25;
GenerateMinefield(boardSize,numberOfMines);
Console.ReadKey();
}
static int[,] GenerateMinefield(int boardSize, int numberOfMines)
{
int[,] Minefield = new int[boardSize + 2, boardSize + 2];
for (int i = 0; i <= boardSize; i++)
{
for (int j = 0; j <= boardSize; j++)
{
Minefield[j, i] = 0;
}
}
Random rand = new Random();
int randomNumber1 = (rand.Next(4)) + 1;
int randomNumber2 = (rand.Next(4)) + 1;
int counter = 0;
while (counter < numberOfMines)
{
if (Minefield[randomNumber1, randomNumber2] == 9)
{
counter--;
}
else
{
Minefield[randomNumber1, randomNumber2] = 9;
counter++;
}
randomNumber1 = (rand.Next(4)) + 1;
randomNumber2 = (rand.Next(4)) + 1;
}
for (int i = 0; i <= boardSize; i++)
{
for (int j = 0; j <= boardSize; j++)
{
Console.Write(Minefield[j, i]);
}
Console.WriteLine(Minefield[boardSize, i]);
}
return Minefield;
}
}
Looks like your problem is in the counter--. You're not removing a mine, you're simply failing to place a mine, so counter should be unchanged.
If I understand correctly the while loop should look something like this:
while (counter < numberOfMines)
{
if (Minefield[randomNumber1, randomNumber2] != 9)
{
Minefield[randomNumber1, randomNumber2] = 9;
counter++;
}
randomNumber1 = (rand.Next(4)) + 1;
randomNumber2 = (rand.Next(4)) + 1;
}
It looks like you're trying to do the following:
Create a minefield board of size (N+2, N+2)
Fill the interior of the board (excluding the cells on the border) randomly with a specified number of mines.
It's possible to do this in linear time (i.e. O(N)) as follows:
Create a 1D array of bools with the same number of elements as the interior of the minefield, excluding the border cells.
Fill the start of array with a number of true values equal to the number of mines that you want.
Shuffle the array - now the "mines" are in random locations.
Go through the array and for every true value set the corresponding value in the minefield to 9.
It's slightly inefficient to create a temporary array almost the same size as the minefield, but this has the advantage that it will always run in linear time.
Putting this together:
static int[,] GenerateMinefield(int boardSize, int numberOfMines, Random rng)
{
if (numberOfMines > boardSize)
throw new InvalidOperationException($"{nameof(numberOfMines)} exceeds {nameof(boardSize)}");
int[,] minefield = new int[boardSize + 2, boardSize + 2]; // Already filled with zeros.
bool[] mines = new bool[(boardSize-2)*2];
for (int i = 0; i < numberOfMines; ++i) // Set the first 'numberOfMines' to 9.
mines[i] = true;
Shuffle(mines, rng); // Now the mines are in random locations.
for (int i = 1, n = 0; i < boardSize; i++)
{
for (int j = 1; j < boardSize; j++, n++)
{
if (mines[n])
minefield[j, i] = 9;
}
}
return minefield;
}
static void Shuffle<T>(IList<T> array, Random rng)
{
for (int n = array.Count; n > 1;)
{
int k = rng.Next(n);
--n;
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
(That's using a standard shuffle algorithm.)
There's a better but more subtle way of doing this that doesn't require a separate array of bools. You can use the following code:
static int[,] GenerateMinefield(int boardSize, int numberOfMines, Random rng)
{
if (numberOfMines > boardSize)
throw new InvalidOperationException($"{nameof(numberOfMines)} exceeds {nameof(boardSize)}");
int[,] minefield = new int[boardSize + 2, boardSize + 2]; // Already filled with zeros.
int available = boardSize*2;
for (int i = 1, n = 0; i < boardSize; i++)
{
for (int j = 1; j < boardSize; j++, n++)
{
if (rng.NextDouble() < numberOfMines / (double)available)
{
minefield[j, i] = 9;
--numberOfMines;
}
}
}
return minefield;
}
The drawback of this approach is that it is not obvious how it works! It's also not completely evenly distributed, but I suspect that wouldn't matter for this program. See here for further discussion.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've created an array called place and filled all 100 indexes with random numbers from 1 to 100 and run a bubblesort on the array. When I want to print out in console, it gives nothing. It's all blank. Mind, I'm pretty new to C# and programming in general, so if you can tell me why this thing doesn't print my sorted array, I'd be grateful.
static void Main(string[] args)
{
Random random = new Random();
int[] place = new int[100];
int spot = random.Next(1, 101);
for (int i = 0; i < place.Length; i++)
{
spot = random.Next(1, 101);
place[i] = spot;
}
for (int i = 0; i <= place.Length; i++)
{
for (int j = 0; j < place.Length - 1; i++)
{
if (place[j] > place[j + 1])
{
int temp = place[j + 1];
place[j + 1] = place[j];
place[j] = temp;
}
}
Console.WriteLine(place[i]);
}
Console.ReadKey();
}
You have two typos:
for (int i = 0; i < place.Length; i++) // should be <, not <= (throws exception)
{
for (int j = 0; j < place.Length - 1; j++) // should be j++ instead of i++
{
if (place[j] > place[j + 1])
{
int temp = place[j + 1];
place[j + 1] = place[j];
place[j] = temp;
}
}
Console.WriteLine(place[i]); // is it necessary?
}
Console.WriteLine();
for (int i = 0; i < place.Length; i++)
{
Console.WriteLine(place[i]);
}
I also added code that prints the whole array, to see if this sorting works (and it does).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I'm trying to split int array into two arrays that the difference of arrays sums would be minimum. Does anyone have any ideas how can I do that? Or any tips?
F.e.
int[] S = { 1, 1, 3, 6 };
We can split S array into
int[] a = {1,1,3};
and
int[] b = {6};
Array a sum is 5 and array b sum is 6 so the minimum difference is 1. By the way, I'm trying to get split arrays of S like a and b, not the sums difference.
Input:
int[] S = { 1, 1, 3, 6 };
Output: int[] a = {1,1,3}; and int[] b = {6};. That's what I'm trying to do.
So far I've tried Link
PROBLEM SOLVED! Thank you everyone for help!
The link you gave is for a more complex problem than the one you are showing us. In your example, elements can't be "reordered", so you can only subdivide the array in two parts. You simply have to choose where to "cut".
var array = new int[] { 1, 1, 3, 6 };
int leftSum = 0;
int rightSum = 0;
for (int i = 0; i < array.Length; i++)
{
rightSum += array[i];
}
int leftArraySize = 0;
int minDiff = rightSum;
for (int i = 0; i < array.Length; i++)
{
rightSum -= array[i];
leftSum += array[i];
int diff = Math.Abs(rightSum - leftSum);
if (diff < minDiff)
{
minDiff = diff;
leftArraySize = i + 1;
}
}
var leftArray = new int[leftArraySize];
var rightArray = new int[array.Length - leftArraySize];
Array.Copy(array, 0, leftArray, 0, leftArray.Length);
Array.Copy(array, leftArray.Length, rightArray, 0, rightArray.Length);
Simple code, without Linq: you have two "sum pools", leftSum and rightSum. You sum all the elements of the array in the rightSum pool. Then element by element you "move" one element from the rightSum sum to the leftSum sum. You then check if/when the difference between two "sum pools" is the minimum one. Then you simply copy the elements in two new arrays.
int[] values = new int[] { 1, 2, 3, 4, 5, 6 };
int minIndex = -1;
int minDiff = int.MaxValue;
for (int i = 0; i < values.Length; i++)
{
int p1 = 0;
for (int j = 0; j <= i; j++)
p1 += values[j];
int p2 = 0;
for (int k = i + 1; k < values.Length; k++)
p2 += values[k];
int diff = Math.Abs(p1 - p2);
if (diff < minDiff)
{
minIndex = i;
minDiff = diff;
}
}
Console.WriteLine("Min index = " + minIndex);
Console.WriteLine("Min difference = " + minDiff);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
public void ascendingOrder()
{
// helper class
double temp = 0;
for (int j = 0; j < numbers.Length; j++)
{
for (int i = 0; i < numbers.Length - 1; i++)
{
if (numbers[i] > numbers[i + 1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
i need the code to sort the columns first and then sort the rows like the following example!
input :
n=3
2 2 1
3 53 4
32 5 3
output:
1 2 2
3 3 54
4 32 53
Some helpful links:
http://www.codeproject.com/Tips/166236/Sorting-a-Two-Dimensional-Array-in-Csharp
How to Sort 2D Array in C#
How do I sort a two-dimensional array in C#?
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)
));
Better way to sort array in descending order
I believe this person is currently writing an exam, so linq methods will not make him pass this test.
Try with this code.
double[,] numbers = new double[,]{ { 1, 3, 2 }, { 4, 6, 5 }, { 7, 9, 8 } };
// helper class
double temp = 0;
for (int k = 0; k < 3; k++)
{
for (int j = 0; j < 2; j++)
{
for (int i = 1; i < 3; i++)
{
if (numbers[k,i] < numbers[k,j])
{
temp = numbers[k,i];
numbers[k,i] = numbers[k,j];
numbers[k,j] =temp;
}
}
}
}