12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- #!/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 })
|