Convert 1D array index to 2D array index

后端 未结 4 694
青春惊慌失措
青春惊慌失措 2020-12-10 03: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          


        
相关标签:
4条回答
  • 2020-12-10 03:27

    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)
    }
    
    0 讨论(0)
  • 2020-12-10 03:31

    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);
        }
    
    0 讨论(0)
  • 2020-12-10 03:32
    p.x = index / 3;
    p.y = index % 3;
    
    0 讨论(0)
  • 2020-12-10 03:38

    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;
    
    0 讨论(0)
提交回复
热议问题