How to get row and column from index?

前端 未结 4 627
南方客
南方客 2020-12-25 11:59

I\'m drawing a HUGE blank here.

Everything I\'ve found is about getting an index from a given row and column, but how do I get a row and a column from an in

相关标签:
4条回答
  • 2020-12-25 12:12

    Swift 4

    typealias ColumnRowType = (column:Int, row:Int)
    
    func indexToColumnRow(index:Int, columns:Int) -> ColumnRowType
    {
        let columnIndex = (index % columns)
        let rowIndex = /*floor*/(index / columns)    // we just cast to an `Int`
    
        return ColumnRowType(columnIndex, rowIndex)
    }
    
    0 讨论(0)
  • 2020-12-25 12:17

    In java, with a column offset of 1, this is a way to do it

    int offset=1;
    column = Math.floorDiv(location-offset , 3)+offset;
    row = ( (location-offset) %3 )+offset ;
    
    0 讨论(0)
  • 2020-12-25 12:23

    For a zero-based index, the two operations are:

    row    = (int)(index / width)
    column = index % width
    

    I'm using % here since I'm a C guy and, though you haven't specified your language, it certainly looks like one of the C-based ones.

    If your question does not pertain to C or its brethren, it will be whatever the modulo operator is for your particular environment, the remainder left over when you divide index by width.

    If you don't have a modulo operator, you can use:

    row    = (int)(index / width)
    column = index - (row * width)
    
    0 讨论(0)
  • 2020-12-25 12:27

    Paxdiablo's answer is the right one. If someone needs the reverse process to get index from row and column:

    index = (row * width) + column
    
    0 讨论(0)
提交回复
热议问题