Converting index of one dimensional array into two dimensional array i. e. row and column

前端 未结 4 471
梦毁少年i
梦毁少年i 2020-12-29 00:29

I have one application of WinForms which inside list box I am inserting name and price..name and price are stored in two dimensional array respectively. Now whe

相关标签:
4条回答
  • 2020-12-29 01:04

    While I didn't fully understand the exact scenario, the common way to translate between 1D and 2D coordinates is:

    From 2D to 1D:

    index = x + (y * width)
    

    or

    index = y + (x * height)
    

    depending on whether you read from left to right or top to bottom.

    From 1D to 2D:

    x = index % width
    y = index / width 
    

    or

    x = index / height
    y = index % height
    
    0 讨论(0)
  • 2020-12-29 01:09

    Well, if I understand you correctly, in your case, obviously the index of the ListBox entry's array entry is the index in the ListBox. The name and price are then at index 0 and index 1 of that array element.

    Example:

    string[][] namesAndPrices = ...;
    
    // To fill the list with entries like "Name: 123.45"
    foreach (string[] nameAndPrice in namesAndPrices)
       listBox1.Items.Add(String.Format("{0}: {1}", nameAndPrice[0], nameAndPrice[1]));
    
    // To get the array and the name and price, it's enough to use the index
    string[] selectedArray = namesAndPrices[listBox1.SelectedIndex];
    string theName = selectedArray[0];
    string thePrice = selectedArray[1];
    

    If you have an array like that:

    string[] namesAndPrices = new string[] { "Hello", "123", "World", "234" };
    

    Things are different. In that case, the indices are

    int indexOfName = listBox1.SelectedIndex * 2;
    int indexOfPrice = listBox1.SelectedIndex * 2 + 1;
    
    0 讨论(0)
  • 2020-12-29 01:12

    For converting 1D indices to and from 3D indices:

    (int, int, int) OneToThree(i, dx, dy int) {
        z = i / (dx * dy)
        i = i % (dx * dy)
        y = i / dx
        x = i % dx
        return x, y, z
    }
    
    int ThreeToOne(x, y, z, dx, dy int) {
        return x + y*dx + z*dx*dy
    }
    
    0 讨论(0)
  • 2020-12-29 01:20

    Try this,

    int i = OneDimensionIndex%NbColumn
    int j = OneDimensionIndex/NbRow //Care here you have to take the integer part
    
    0 讨论(0)
提交回复
热议问题