20

I have 2 arrays. I want to convert the index of the first array to the second. Is there a better way to do it than what I have below?

Array array1[9];
Array array2[3][3];

// Index is the index of the 1D array
public Point convert1Dto2D(int index)
{
        Point p = new Point();

        switch (index) {
            case 0:
                p.x = 0;
                p.y = 0;
                break;
            case 1:
                p.x = 0;
                p.y = 1;
                break;
            case 2:
                p.x = 0;
                p.y = 2;
                break;
            case 3:
                p.x = 1;
                p.y = 0;
                break;
            case 4:
                p.x = 1;
                p.y = 1;
                break;
            case 5:
                p.x = 1;
                p.y = 2;
                break;
            case 6:
                p.x = 2;
                p.y = 0;
                break;
            case 7:
                p.x = 2;
                p.y = 1;
                break;
            case 8:
                p.x = 2;
                p.y = 2;
                break;
        }

return p;
}
Arizona1911
  • 2,181
  • 9
  • 29
  • 38

4 Answers4

52
p.x = index / 3;
p.y = index % 3;
Sapph
  • 6,118
  • 1
  • 29
  • 32
  • @PeterOlson Why does it matter? – vexe Aug 31 '14 at 09:45
  • 2
    @vexe It's been 3 years since I made that comment, so I don't remember exactly what I had in mind. I imagine it had more to do with being conventional than being correct. – Peter Olson Aug 31 '14 at 15:36
  • 1
    x, y, then z. its always has been and always will be – Dean Van Greunen Feb 26 '19 at 21:14
  • If you're using this solution in a different programming language, make sure to round the x index down to the nearest whole number. You don't have to in C# because it excludes decimals from the result of the division of two integers, while languages like javascript do not. – Justiniscoding Aug 20 '23 at 19:34
11

You can do this mathematically using modulus and integer division, given your second array is a 3x3 array the following will do.

p.y = index % 3;
p.x = index / 3;
Chris Taylor
  • 52,623
  • 10
  • 78
  • 89
2

Just in case someone wonders for Javascript.

var columnCount = 3
for(var i=0; i < 10; i++){
  var row = Math.floor(i/ columnCount )
  var col = i % columnCount 
  console.log(i, row, col)
}
Ska
  • 6,658
  • 14
  • 53
  • 74
2

I assume your running that code in a loop? If so

IEnumerable<Point> DoStuff(int length, int step) {
    for (int i = 0; i < length; i++)
        yield return new Point(i/step, i%step);
}

Call it

foreach (var element in DoStuff(9, 3))
    {
        Console.WriteLine(element.X);
        Console.WriteLine(element.Y);
    }
Razor
  • 17,271
  • 25
  • 91
  • 138