Loop diagonally through two dimensional array

Viewed 83483

I wrote the following code to walk half the diagonals of an array:

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

public void LoopDiag()
   for (int i = b.length - 1; i > 0; i--) {
       String temp = "";
       for (int j = 0, x = i; x <= b.length - 1; j++, x++) {
          temp = temp+b[x][j];
       }
       System.out.println(temp)
   }


   for (int i = 0; i <= b.length - 1; i++) {
        String temp = "";
        for (int j = 0, y = i; y <= b.length - 1; j++, y++) {
        temp = temp+b[j][y];
        }
        System.out.println(temp);
   }
}

Right now it prints the diagonals i.e current output:

g dh aei bf c

How do I make it print the other half diagonals i.e required output:

a db gec hf i 
12 Answers

Just help yourself, have a look at the indices you need to loop through:

#1 (0,0)               -> a
#2 (1,0)  (0,1)        -> bd
#3 (2,0)  (1,1)  (0,2) -> gec
#4 (2,1)  (1,2)        -> hf
#5 (2,2)               -> i

Look at the change of the indices in each iteration and create your algorithm. Not so difficult, so do your homework yourself ;)

Type 1: We can solve this using python very easily

Code:

r,c=map(int,input().split())
mat=[[str(ch) for ch in input().split()]for _ in range(r)]
for i in range(r*c-2):
    lis=[]
    for j in range(r):
        for k in range(c):
            if k+j==i:
                lis.append(mat[j][k])
    print(*lis[::-1])

Output:

5 5
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y

a
f b
k g c
p l h d
u q m i e
v r n j
w s o
x t
y
Related