consecutive_partitions.sf 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 29 April 2019
  4. # https://github.com/trizen
  5. # Given an array of elements, generate all the possible consecutive partitions (with no swaps and go gaps).
  6. # For example, given the array [1,2,3,4,5], there are 16 different ways:
  7. # [[1, 2, 3, 4, 5]]
  8. # [[1], [2, 3, 4, 5]]
  9. # [[1, 2], [3, 4, 5]]
  10. # [[1, 2, 3], [4, 5]]
  11. # [[1, 2, 3, 4], [5]]
  12. # [[1], [2], [3, 4, 5]]
  13. # [[1], [2, 3], [4, 5]]
  14. # [[1], [2, 3, 4], [5]]
  15. # [[1, 2], [3], [4, 5]]
  16. # [[1, 2], [3, 4], [5]]
  17. # [[1, 2, 3], [4], [5]]
  18. # [[1], [2], [3], [4, 5]]
  19. # [[1], [2], [3, 4], [5]]
  20. # [[1], [2, 3], [4], [5]]
  21. # [[1, 2], [3], [4], [5]]
  22. # [[1], [2], [3], [4], [5]]
  23. # In general, for a given array with `n` elements, there are `2^(n-1)` possibilities.
  24. func split_at_indices(array, indices) {
  25. var parts = []
  26. var i = 0
  27. for j in (indices) {
  28. parts << array.slice(i, j - i + 1)
  29. i = j+1
  30. }
  31. parts
  32. }
  33. func consecutive_partitions(array, callback) {
  34. for k in (0..array.len) {
  35. combinations(array.len, k, {|*indices|
  36. var t = split_at_indices(array, indices)
  37. if (t.sum_by{.len} == array.len) {
  38. callback(t)
  39. }
  40. })
  41. }
  42. }
  43. var arr = [1,2,3,4,5]
  44. consecutive_partitions(arr, { .say })