• 0

Matrix as a list


Question

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 6
3 5 7
4 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

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

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

Where's my cookie? :)

Link to comment
Share on other sites

  • 0

...

Given row, col, find k:

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

Where's my cookie? :)

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

Link to comment
Share on other sites

  • 0

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

Where's my cookie? :)

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

Link to comment
Share on other sites

  • 0

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!

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.