-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsecutive_partitions.sf
54 lines (44 loc) · 1.27 KB
/
consecutive_partitions.sf
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
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 29 April 2019
# https://github.com/trizen
# Given an array of elements, generate all the possible consecutive partitions (with no swaps and go gaps).
# For example, given the array [1,2,3,4,5], there are 16 different ways:
# [[1, 2, 3, 4, 5]]
# [[1], [2, 3, 4, 5]]
# [[1, 2], [3, 4, 5]]
# [[1, 2, 3], [4, 5]]
# [[1, 2, 3, 4], [5]]
# [[1], [2], [3, 4, 5]]
# [[1], [2, 3], [4, 5]]
# [[1], [2, 3, 4], [5]]
# [[1, 2], [3], [4, 5]]
# [[1, 2], [3, 4], [5]]
# [[1, 2, 3], [4], [5]]
# [[1], [2], [3], [4, 5]]
# [[1], [2], [3, 4], [5]]
# [[1], [2, 3], [4], [5]]
# [[1, 2], [3], [4], [5]]
# [[1], [2], [3], [4], [5]]
# In general, for a given array with `n` elements, there are `2^(n-1)` possibilities.
func split_at_indices(array, indices) {
var parts = []
var i = 0
for j in (indices) {
parts << array.slice(i, j - i + 1)
i = j+1
}
parts
}
func consecutive_partitions(array, callback) {
for k in (0..array.len) {
combinations(array.len, k, {|*indices|
var t = split_at_indices(array, indices)
if (t.sum_by{.len} == array.len) {
callback(t)
}
})
}
}
var arr = [1,2,3,4,5]
consecutive_partitions(arr, { .say })