javascript - Using an index to find a position in a matrix -
my title might terrible, can explain want here. first of all, challenging myself specific. if guess i'm trying accomplish, please keep answers on topic asking here, , not overall problem solving.
i have string of 25 generated letters. index of letter via str.indexof(c)
, let's index 16. visualize str
linear representation of 5x5 table, index of 16 4th row, 2nd column of table.
i'm trying find way find row , column using javascript without looping through this:
var row = 1; var index = str.indexof(c) + 1; while(index > 5) { index = index - 5; row++; }
with above code, if index starts 16, end result row 4, index 2 - want. feels there should way algorithm instead of loop.
any thoughts?
why not use maths?
var index = 16; var columnsperrow = 5; row = parseint(index / columnsperrow) + 1; column = index % columnsperrow + 1;
Comments
Post a Comment