Reputation: 1321
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 index?
The row is easy: (int)(index / width)
.
My brain is suffering massive bleed trying to compute the column.
Shame on me.
Upvotes: 41
Views: 40279
Reputation: 881633
For a zero-based index, the two operations are, where width
is the width of the structure:
row = index / width
column = index % width
Those are for C using integers, where the division rounds down and the %
modulo operator gives the remainder. If you're not using C, you may have to translate to the equivalent operations.
If you don't have a modulo operator, you can use:
row = index / width
column = index - (row * width)
Upvotes: 83
Reputation: 900
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 ;
Upvotes: 0
Reputation: 2463
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)
}
Upvotes: 2
Reputation: 1591
Paxdiablo's answer is the right one. If someone needs the reverse process to get index from row and column:
index = (row * width) + column
Upvotes: 27