1

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!

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Glitchezz
  • 353
  • 2
  • 7
  • 21

3 Answers3

2

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;
            }
AD.Net
  • 13,352
  • 2
  • 28
  • 47
0

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]].

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
0

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
Ryan Frame
  • 285
  • 1
  • 16