Zig-zag matrix
1
func zig_zag(w, h) {
2
3
var r = []
4
var n = 0
5
6
h.of { |e|
7
w.of { |f|
8
[e, f]
9
}
10
}.reduce('+').sort { |a, b|
11
(a[0]+a[1] <=> b[0]+b[1]) ||
12
(a[0]+a[1] -> is_even ? a[0]<=>b[0]
13
: a[1]<=>b[1])
14
}.each { |a|
15
r[a[1]][a[0]] = n++
16
}
17
18
return r
19
}
20
21
zig_zag(5, 5).each { say .join('', {|i| "%4i" % i}) }
Copied!

Output:

1
0 1 5 6 14
2
2 4 7 13 15
3
3 8 12 16 21
4
9 11 17 20 22
5
10 18 19 23 24
Copied!
Last modified 1yr ago
Copy link
Contents
Output: