How to Save a Multidimensional Array Index? - c#

Basically my first task was to save the position of the '0' in an integer. Real simple with a standard array. This code loops through an array (Size: 8) until it locates the 0, then save that as the position. See code below:
p.s: n is a reference to an array saved somewhere else.
int position = 0;
this.nodesExpanded++;
// Loop through the array to get the position of where '0' is
for (int i = 0; i < n.getPuzzle().length; i++){
if (n.getPuzzle()[i] == 0){
position = i;
break;
}
}
My ultimate task was to make this possible for a multidimensional array (Size: [3, 3]). So here's what I've created thus far:
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
if (n.getPuzzle()[x,y] == 0)
{
**position = ;**
break;
}
}//end y loop
}//end x loop
So how do I go about saving an array reference to a location to a value?
'position' will need to be something other than int I'm guessing..
If you need more clarification be sure to comment, sorry in advance & thank you!

You can use a Tuple to store that position. Or you can create your own data structure.
Example: at the end you can see how to access tuple items.
var positions = new List<Tuple<int, int>>();
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
if (n.getPuzzle()[x,y] == 0)
{
positions.Add(new Tuple<int, int>(x,y));
break;
}
}//end y loop
}//end x loop
if(positions.Any())
{
var xpos = positions[0].Item1;
var ypos = positions[0].Item2;
}

I find a natural way to store a multidimensional array index is to use a single dimensional array whose size is the number of dimensions.
So if you have a object[,,] A and index int[] i you would index into A with the expression A[i[0],i[1],i[2]].

It works the same way as your one-dimensional array, but you have two position values to keep. I've used ints for the example, but you may want to use a custom structure or Tuple (as AD.Net) said.
int xpos = -1;
int ypos = -1;
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
if (n.getPuzzle()[x,y] == 0)
{
xpos = x;
ypos = y;
break;
}
}//end y loop
}//end x loop
if (!(xpos > -1 && ypos > -1)) ; // 0 was not found

Related

Delete Specific Column Row Multidimensional Array C#

Hi can someone help me deleting array in multidimensional this code keeps on Array out of Bound
```
int[,] Arr = {
{ 10,20,30,40},
{ 10,20,30,40},
{ 10,20,30,40},
{ 10,20,30,40}
};
int index = 1;
for(int x = 0; x <= 3; x++) {
for (int i = index; i < Arr.Length - 1; i++)
{
Arr[i, x] = Arr[i + 1, x];
}
}
```
The Length property returns the length of the first dimension. When you want to access the other dimensions, you have to use the GetLength() method. See this SO.

Problem with program that separates 2D array into even/odd 2D arrays (extra zeroes in even/odd arrays)

I am practicing with 2D arrays and am making a program that separates a 2D array with random integer values into two separate arrays based on if the values are even or odd.
However, the program seems to be adding additional zeroes to each row in the even and odd arrays. What am I doing wrong?
I think the problem is in the sort() function where I determine the size of the even and odd arrays but I am not sure.
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[10, 10];
// Fills 2D array with random values and prints them out
Random r = new Random();
for (int y = 0; y < arr.GetLength(0); y++)
{
for (int x = 0; x < arr.GetLength(1); x++)
{
arr[y, x] = r.Next(1, 99);
Console.Write(arr[y,x] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
// Function that separates original array into 2 separate ones (even and odd)
sort(arr);
Console.ReadLine();
}
public static void sort(int[,] array)
{
int j1 = 0;
int i1 = 0;
int j2 = 0;
int i2 = 0;
// Increases the size of the even/odd arrays whenever the value of the original array is even/odd respectively
// I think this is where the problem is
for (int y = 0; y < array.GetLength(0); y++)
{
for (int x = 0; x < array.GetLength(1); x++)
{
if (array[y,x] % 2 == 0)
{
i1 += 1;
}
else
{
i2 += 1;
}
}
j1 += 1;
j2 += 1;
}
int[,] evenArr = new int[j1, i1];
int[,] oddArr = new int[j2, i2];
// Sets the values for the even/odd arrays
for (int y = 0; y < array.GetLength(0); y++)
{
for (int x = 0; x < array.GetLength(1); x++)
{
if (array[y, x] % 2 == 0)
{
evenArr[y, x] = array[y, x];
}
else
{
oddArr[y, x] = array[y, x];
}
}
}
// Prints the values for the even array
for (int y = 0; y < evenArr.GetLength(0); y++)
{
for (int x = 0; x < evenArr.GetLength(1); x++)
{
Console.Write(evenArr[y, x] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
// Prints the values for the odd array
for (int y = 0; y < oddArr.GetLength(0); y++)
{
for (int x = 0; x < oddArr.GetLength(1); x++)
{
Console.Write(oddArr[y, x] + " ");
}
Console.WriteLine();
}
}
}
When you initialize your arrays (evenArr = new int[j1, i1], oddArr = new int[j2, i2];) the default values are zero. Since there's an extra zero it means you should check the length and probably reduce it by one.

How to assign a value to an index of a three dimensional array?

I have defined two three dimensional arrays as:
int[, ,] Link_k = new int[length1, length1, length1];
int[][][] Link_k2 = new int[length1][][];
where length1 is variable and could be any integer number.
My question is that how could I assign a value for a special index or for all first indices. I tried
Link_k.SetValue(-1,(0,,));
Link_k2.SetValue(-1,[0][][]);
But that does not compile.
As #Patrick Hofman said, Link_k is pretty easy:
Link_k[x, y, 0] = -1;
Or, using SetValue:
Link_k.SetValue( -1, x, y, 0 );
However, you don't actually create a three dimensional array for Link_k2 - you create a one dimensional array of arrays of arrays. E.g. Link_k2[0] is int[][], and, when it is initialised, Link_k2[0][0] is int[].
So, for Link_k2 you'd need to:
for (int x = 0; x < Link_k2.Length; x++)
{
//create a new array of arrays at Link_k2[x]
Link_k2[x] = new int[length1][];
for (int y = 0; y < Link_k2[x].Length; y++)
{
//create a new arrays at Link_k2[x][y]
Link_k2[x][y] = new int[length1];
for (int z = 0; z < Link_k2[x][y].Length; z++)
{
Link_k2[x][y][z] = -1;
}
}
}
If you want to set the first index of every Z-axis array, you have to iterate over it, using for for example.
For Link_k:
for (int x = 0; x < Array.GetUpperBound(Link_k, 0); x++)
{
for (int y = 0; i < Array.GetUpperBound(Link_k, 1); y++)
{
Link_k[x, y, 0] = -1;
}
}
And for Link_k2:
int[][][] Link_k2 = new int[length1][][];
for (int x = 0; x < Link_k2.Length; x++)
{
Link_k2[x] = new int[length1][];
for (int y = 0; i < Link_k2[x].Length; y++)
{
Link_k2[x][y] = new int[length1];
Link_k2[x][y][0] = -1;
}
}
(Note you don't seem to assign the second and third array. Assign that in a for loop, so you assign every array in every array, etc. so I have put that in too)

C# Resorting an array in a unique way

I am wanting to create multiple arrays of ints(in C#). However they all must have a unique number in the index, which no other array has that number in that index. So let me try show you what I mean:
int[] ints_array = new int[30];
for (int i = 0; i < ints_array.Count(); i++)
ints_array[i] = i;
//create a int array with 30 elems with each value increment by 1
List<int[]> arrayList = new List<int[]>();
for(int i = 0; i < ints_array.Count(); i++)
arrayList.Add(ints_array[i]. //somehow sort the array here randomly so it will be unique
So I am trying to get the arrayList have 30 int[] arrays and each is sorted so no array has the same int in the same index as another.
Example:
arrayList[0] = {5,2,3,4,1,6,7,8,20,21... etc }
arrayList[1] = {1,0,5,2,9,10,29,15,29... etc }
arrayList[2] = {0,28,4,7,29,23,22,17... etc }
So would this possible to sort the array in this unique kind of way? If you need anymore information just ask and ill fill you in :)
Wouldn't it be easier to create the arrays iteratively using an offset pattern?
What I mean is that if you created the first array using 1-30 where 1 is at index 0, the next array could repeat this using 2-30 where 2 is at index 0 and then wrap back to 1 and start counting forward again as soon as you go past 30. It would be an easy and repeatable way to make sure no array shared the same value/index pair.
You can do it like that:
List<int[]> arrayList = new List<int[]>();
Random rnd = new Random();
for (int i = 0; i < ints_array.Length; i++)
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
var isDuplicate = arrayList.Any(x => x.SequenceEqual(ints_array));
if (isDuplicate)
{
while (arrayList.Any(x => x.SequenceEqual(ints_array)))
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
}
}
arrayList.Add(ints_array);
}
I think, this wouldn't be so efficient for bigger numbers than 30.But in this case it shouldn't be a problem, in my machine it takes 7 milliseconds.
Jesse's idea would be best unless you needed a pure random pattern. In that case I would recommend generating a random number, checking all your previous arrays, and then placing it in an array if it did not match any other arrays current index. Otherwise, generate a new random number until you find a fresh one. Put that into a loop until all your arrays are filled.
Use a matrix (2D-array). It is easier to handle than a list of arrays. Create a random number generator. Make sure to initialize it only once, otherwise random number generator may create bad random numbers, if created in too short time intervals, since the slow PC-clock might not have ticked in between. (The actual time is used as seed value).
private static Random random = new Random();
Create two helper arrays with shuffeled indexes for rows and columns:
const int N = 30;
int[] col = CreateUniqueShuffledValues(N);
int[] row = CreateUniqueShuffledValues(N);
Then create and initialize the matrix by using the shuffeled row and column indexes:
// Create matrix
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[row[i], col[j]] = (i + j) % N;
}
}
The code uses these two helper methods:
private static int[] CreateUniqueShuffledValues(int n)
{
// Create and initialize array with indexes.
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
// Shuffel array using one variant of Fisher–Yates shuffle
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm
for (int i = 0; i < n; i++) {
int j = random.Next(i, n);
Swap(array, i, j);
}
return array;
}
private static void Swap(int[] array, int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
int size = 10;
// generate table (no duplicates in rows, no duplicates in columns)
// 0 1 2
// 1 2 0
// 2 0 1
int[,] table = new int[size, size];
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
table[y, x] = (y + x) % size;
// shuffle rows
Random rnd = new Random();
for (int i = 0; i < size; i++)
{
int y1 = rnd.Next(0, size);
int y2 = rnd.Next(0, size);
for (int x = 0; x < size; x++)
{
int tmp = table[y1, x];
table[y1, x] = table[y2, x];
table[y2, x] = tmp;
}
}
// shuffle columns
for (int i = 0; i < size; i++)
{
int x1 = rnd.Next(0, size);
int x2 = rnd.Next(0, size);
for (int y = 0; y < size; y++)
{
int tmp = table[y, x1];
table[y, x1] = table[y, x2];
table[y, x2] = tmp;
}
}
// sample output
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
Console.Write("{0} ", table[y, x]);
Console.WriteLine();
}

move the values from a normal array to a 2D array - What's wrong with this code?

Basically I'm working on an assignment and I need to move the values from a normal array to a 2D array. I have to take input to set the length of the aray. The 2d array will be a square array, so say 3 is input my array needs to be 3x3. I've made the 1D array size n*n, with n being what the user inputs. I'm getting an index out of rage exception but I've gone through the code and written out what I think the values of everything should be at each stage and can't find out what's causing it.
public static void createTwoD(int[,] twoDArray, int[] startArray, int arrayLength)
{
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
}
The line getting the exception is the last line in that method. I'm passing in a 2D array of size [n,n], a 1D array of size [n*n] and the just n. If you want to see any more of the code let me know.
The problem is in you lines:
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
arrayLength variable makes jump out of bounds on startArray. Note that both x and i are in range from 0 to arrayLength
If you know already dimensions of your 2d array, you can easily achieve this by (here I assume it 3x3):
var x = 0;
for (int i = 0; i < arrayLength; i++) {
if(i!= 0 && i % 3 == 0) ++x; // go to another row
twoDArray[i, x] = startArray[i];
}
I would start by adding the following to the start of your method. These document your assumptions about the dimensions of the arrays passed as arguments.
Debug.Assert(twoDArray.Rank == 2);
Debug.Assert(startArray.Rank == 1);
Debug.Assert(twoDArray.GetLength(0) == arrayLength);
Debug.Assert(twoDArray.GetLength(1) == arrayLength);
Debug.Assert(startArray.GetLength(0) == arrayLength * arrayLength);
maybe twoDArray issnt initilized correctly:
public static void createTwoD(int[,] twoDArray, int[] startArray, int arrayLength)
{
//twoDArray musst be initialized correctly, otherwise use:
twoDArray = new int[arrayLength][arrayLength];
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
}

Categories