How to get location coordinates in a grid?

How can I get location coordinates on a grid with a single window number?

1 2 3 4 5 6 ------------------------------ 1| 1 2 3 4 5 6 2| 7 8 9 10 11 12 3| 13 14 15 16 17 18 4| 19 20 21 22 23 24 5| 25 26 27 28 29 30 6| 31 32 33 34 35 36 

ie: if I have the number 15, the coordinates are x = 3; y = 3

I tried to develop a function, but it does not work, does anyone have an idea?

Thank you for your help

+4
source share
2 answers

UPDATE (The formula was incorrect):

 y = (myNumber - 1) / 6 + 1; x = (myNumber - 1) % 6 + 1; 

UPDATE (Explanation):

Each line contains 6 elements. We define x as the remainder when divided by 6:

x ~ myNumber% 6

and add +1 as the definition range is [1; 6].

x ~ myNumber% 6 + 1

But the last element in the line is divisible by 6 without a remainder. To consider this, we subtract 1 from myNumber before applying the modulo operator:

x = (myNumber - 1)% 6 + 1

eg. myNumber = 1 => x = 1; myNumber = 6 => x = 6; myNumber = 7 => x = 1; myNumber = 12 => x = 6;

The number of lines is called y and is proportional to the integer division by 6:

y ~ myNumber / 6

But again, we must consider that we do not start at 0, but at 1:

y ~ myNumber / 6 + 1

And again, a β€œleft shift” appears, since the last element of each row can be divided by 6 without a remainder. So, we subtract 1 from myNumber before division to reflect this:

y = (myNumber - 1) / 6 + 1

+2
source

You can use a gear array:

 private static readonly int[][] matrix = new int[6][]; // ... matrix[0] = new int[] { 1, 2, 3, 4, 5, 6 }; matrix[1] = new int[] { 7, 8, 9, 10, 11, 12 }; matrix[2] = new int[] { 13, 14, 15, 16, 17, 18 }; matrix[3] = new int[] { 19, 20, 21, 22, 23, 24 }; matrix[4] = new int[] { 25, 26, 27, 28, 29, 30 }; matrix[5] = new int[] { 31, 32, 33, 34, 35, 36 }; 

and Linq to find the values ​​of x and y:

 int num = 15; var matches = matrix .Select((yArr, index) => new { yArr, yPos = index + 1 }) .Where(y => y.yArr.Contains(num)) .Select(y => new { X = (y.yArr.Select((x, i) => new { x, i }) .First(x => xx == num).i) + 1, Y = y.yPos, }); if(matches.Any()) { var firstMatch = matches.First(); int x = firstMatch.X; int y = firstMatch.Y; } 

Demo

+2
source

All Articles