-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzig-zag_permutations.sf
More file actions
71 lines (54 loc) · 1.36 KB
/
zig-zag_permutations.sf
File metadata and controls
71 lines (54 loc) · 1.36 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/ruby
# Generate Zig-Zag permutations for a set {1..n}.
# See also:
# https://rosettacode.org/wiki/Zigzag_numbers
# https://en.wikipedia.org/wiki/Alternating_permutation
func zigzag_permutations(n) {
var arr = []
func (dir, have, rest) {
if (!rest) {
arr << have
return nil
}
var last = (have.last \\ (1 + rest.last))
for n in (rest.grep {|k| (k <=> last) == dir }) {
var new = rest.clone
var t = have.clone
if (new.delete_first_by {|k| k == n }) {
t << n
}
__FUNC__(-dir, t, new)
}
}(-1, [], @(1..n))
return arr
}
func zigzag_permutations2(n) {
var arr = []
var have = []
var used = n.of(false)
func (dir) {
if (have.len == n) {
arr << have.clone
return nil
}
var last = (have.last \\ (n + 1))
for k in (1..n) {
next if used[k - 1]
next if ((k <=> last) != dir)
used[k - 1] = true
have << k
__FUNC__(-dir)
have.pop
used[k - 1] = false
}
}(-1)
return arr
}
assert_eq(
zigzag_permutations(5),
zigzag_permutations2(5)
)
for n in (1..5) {
var arr = zigzag_permutations(n)
say "a(#{n}) = #{'%2d' % arr.len}: #{arr}"
}