Create an account on Neowin to contribute and support the site.

# Matrix as a list

## Recommended Posts

Chester0    15

Hello everyone i have been trying to find a better approach to solve this instead of having allot of if checks...

so here is the problem:

say i have a matrix

`8  1  63  5  74  9  2[/CODE]`

and i represent it as a list:

[CODE]
8 3 4 1 5 9 6 7 2
[/CODE]

what i want is to return the position of the number in the list. As inputs i get the indexes of the matrix. ie for i=1, j=3 (row, column) the value is 6 and the position in the list is 7 (list is from 1 to 9)

I am looking for a relationship between the indexes of the matrix and the position in the list if any exists

cheers

##### Share on other sites
rfirth    727

If position in list is k:

row = k % 3

col = k / 3

Given row, col, find k:

k = row % 3 + col * 3

I'm assuming 0-indexed array and rows/cols. Otherwise, 1-indexed arrays and rows/cols as you specified:

If position in list is k:

row = (k - 1) % 3 + 1

col = (k - 1) / 3 + 1

Given row, col, find k:

k = (row - 1) % 3 + (col - 1) * 3 + 1

##### Share on other sites
giantpotato    296

...

Given row, col, find k:

k = (row - 1) % 3 + (col - 1) * 3 + 1

No cookie for you, It's more efficient to just have k= (col-1) * 3 + row

##### Share on other sites
Chester0    15

If position in list is k:

row = k % 3

col = k / 3

Given row, col, find k:

k = row % 3 + col * 3

I'm assuming 0-indexed array and rows/cols. Otherwise, 1-indexed arrays and rows/cols as you specified:

If position in list is k:

row = (k - 1) % 3 + 1

col = (k - 1) / 3 + 1

Given row, col, find k:

k = (row - 1) % 3 + (col - 1) * 3 + 1

Omg I've been trying something similar with adding 3 instead of mod/dividing :pinch:

Tried it out works perfect, no more banging my head on my desk :argh: How did you figure it out?

sorry cant bake no cookie for you :blushing: i do make a mean souvlaki if you are interested hehe

thanks, much appreciated :punk:

No cookie for you, It's more efficient to just have k= (col-1) * 3 + row

k in the unknown in my case, i have to work with col and row

thanks for the input

edit: brain fart, i need a break that works too

##### Share on other sites
rfirth    727

No cookie for you, It's more efficient to just have k= (col-1) * 3 + row

Oops, you're right. Looks like I got a little carried away there. Silly mistake. And I was really looking forward to that cookie, too!