Welcome Guest! To access all forums & features, please register an account or sign-in. → Why register?

# Matrix as a list

4 replies to this topic

### #1 Chester0

Chester0

Resident Fanatic

• Joined: 06-January 05

Posted 08 September 2012 - 06:18

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
```

and i represent it as a list:

```8 3 4 1 5 9 6 7 2
```

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

### #2 rfirth

rfirth

Software Engineer

• Joined: 11-September 09
• Location: Baton Rouge, Louisiana
• OS: Windows 8
• Phone: Nokia Lumia 800

Posted 08 September 2012 - 06:33

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

### #3 giantpotato

giantpotato

Neowinian Wise One

• Joined: 27-January 04

Posted 08 September 2012 - 06:58

...
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

### #4 OP Chester0

Chester0

Resident Fanatic

• Joined: 06-January 05

Posted 08 September 2012 - 07:01

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
Tried it out works perfect, no more banging my head on my desk How did you figure it out?
sorry cant bake no cookie for you i do make a mean souvlaki if you are interested hehe
thanks, much appreciated

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

### #5 rfirth

rfirth

Software Engineer

• Joined: 11-September 09
• Location: Baton Rouge, Louisiana
• OS: Windows 8
• Phone: Nokia Lumia 800

Posted 08 September 2012 - 07:44

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!