Iterating all diagonal slices of a matrix

  • #1
1,039
2

Main Question or Discussion Point

I'm writing something in Java, (but the language doesn't really matter for this problem), and I can't figure out any way to do this efficiently.

I have some character array with a bunch of stuff in it, and I need to slice it into it's diagonals, for example:

[a,b,c; d,e,f; g,h,i]

becomes: [a], [d,b], [g,e,c], [f,h], (this is just one "direction" of slicing)

But the problem is, the character array is mxn with unknown dimensions!

No matter how I nestle loops, I just can't make this happen. Tomorrow morning I am going to try 3 cases, mxn where m=n, m>n, and m<n, but then it seems I must break each of those cases into 2-3 other parts to iterate through, and it blows out of proportion from there.

Any idea how I could accomplish this task?
 

Answers and Replies

  • #2
CompuChip
Science Advisor
Homework Helper
4,302
47
You start at ##(i, j) = (i_0, 0)## or ##(i, j) = (0, j_0)## and in every iteration send ##(i, j) \mapsto (i \pm 1, j \pm 1)## (with the two ##\pm## chosen depending on the direction you want to run) until one of the variables runs out of bounds (i.e. ##i < 0##, ##i \ge m##, ##j < 0## or ##j \ge n##).
 

Related Threads on Iterating all diagonal slices of a matrix

Replies
0
Views
2K
  • Last Post
Replies
17
Views
8K
Replies
2
Views
2K
  • Last Post
Replies
16
Views
2K
  • Last Post
Replies
1
Views
4K
  • Last Post
Replies
6
Views
17K
Replies
2
Views
5K
Replies
17
Views
4K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
2
Views
2K
Top