Diagonally Print a Square Array

Description

Given an sqaure array (n*n) of integers, print elements diagonally .

Example

1
2
3
4
5
6
7
8
9
10
11
12
let nums = [
[1,2,3],
[4,5,6],
[7,8,9]
]

should print the following:
1
2 4
3 5 7
6 8
9

Solution: O(n^2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function printDiagnally(input){
let n = input.length // 3
let lines = 2*(n-1) + 1 // 5

// determine how many diagonal lines
for( let sum = 0; sum < lines; sum++ ){

// determine the starting x-coord, and starting y-coord
let x0 = sum < n ? sum : n-1
let y0 = sum - x0
let num = Math.abs(x0 - y0) +1 // how many elements in this line
let str = ""

// concat all elements in this line
for( let x = x0; x > x0-num; x-- ){
let y = sum - x
str = input[x][y] + " "+str
}
console.log(str)
}
}

// ---------- Testing: ------------
console.log("Test1: ")
let input = [[1]]
printDiagnally(input)


console.log("Test2: ")
input = [
[1, 2],
[3, 4]
]
printDiagnally(input)


console.log("Test3: ")
input = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
printDiagnally(input)

console.log("Test4: ")
input = [
[1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
printDiagnally(input)