Home > Enterprise >  Have a number correspond to a position in a multi dimensional array (map 1D numeric values to 2D)
Have a number correspond to a position in a multi dimensional array (map 1D numeric values to 2D)

Time:07-02

I would like the user to input a number 1-9 and have that number correspond to a position on a 3x3 2d array. And then change the value in that array to an "x".

int input = Convert.ToInt32(Console.ReadLine());

string[,] numbers = { 
                    { " ", " ", " " },
                    { " ", " ", " " }, 
                    { " ", " ", " " }
                    };

At first I decided to do this:

int x = input % 3 - 1;
int y = input / 3 - 1;

And then access the array at numbers[y, x] however this caused problems with the index being out of bounds.

CodePudding user response:

You had a somewhat good intuition for subtracting 1, but you did it in a wrong way.

The correct would be:

int x = (input-1) % 3;
int y = (input-1) / 3;

Subtracting 1 from the input (in the range 1..9) will translate it to the range 0..8.
Then using / and % with 3, will get you the x,y coordinates, both in 0..2 range.

  •  Tags:  
  • c#
  • Related