Generate all Sublist Partitions
Retina, 27 19 bytes
Byte count assumes ISO 8859-1 encoding.
+1%`,
;$'¶$`];[
;
,
Try it online!
Explanation
Of course this computes all partitions using string processing. The basic idea is that we can generate all partitions by deciding for each ,
individually whether or not we want to split the list there. This kind of stuff can be done in Retina by matching each ,
in turn and using a replacement which gives both possible outputs.
The input acts as the base case: the partition where all elements are still in a single list.
+1%`,
;$'¶$`];[
Now we repeatedly (+
) match the first (1
) comma (,
), on each line (%
) (treating that line as a separate string, which is relevant for $'
and ``$1 ` in the substitution).
That comma gets replaced with:
; A semicolon. This is just a stand-in for the comma, so we know we've already
processed it and it won't be substituted again by the next iteration.
$' Everything after the match. This completes the first (unchanged) version of
the current line.
¶ A linefeed. Since the next iteration will scan for all lines again, this doubles
the number of strings we're working with.
$` Everything before the match. This completes the second (split) version of
the current line.
];[ A semicolon around which we split the list.
Remember that everything in front of the match and after the match remains in the string anyway, so the full result is actually $`;$'¶$`];[$'
which explains why we insert the suffix and prefix in that order.
This loop stops once all commas are gone.
;
,
Finally, replace the semicolons with commas again to match the input format.
Pure Bash, 28
eval echo [${1//:/{:,]:[\}}]
Here, lists are colon-separated, and contained in square brackets. For example in the question, the input list would be 1:2:3:4
and the output is:
[1:2:3:4] [1:2:3]:[4] [1:2]:[3:4] [1:2]:[3]:[4] [1]:[2:3:4] [1]:[2:3]:[4] [1]:[2]:[3:4] [1]:[2]:[3]:[4]
Try it online.
${1//:/REPLACEMENT}
replaces the colons in$1
with{:,]:[\}
- This generates a brace expansion like
[1{:,]:[}2{:,]:[}3{:,]:[}4]
- The eval (and careful
\
escapes) causes the brace expansion to happen last and give the desired result.
If it is necessary to exactly match the given [[ , , ...]]
format, then we can do this instead:
Pure Bash, 47
eval printf '%s\\n' ${1//, /{\\,\\ ,]\\,\\ [\}}
Try it online.
Pyth, 2 bytes
./
With input [1, 2, 3, 4]
(for instance).
Explanation: ./
is the partition operator. It returns all divisions of the input list into disjoint sub-lists. The input is implicitly fed to the program.
Test it online!