Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I would like the user to input a number 1-9 and have that number correspond to a position on a 3×3 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading