Ordered partitions: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Ordered partitions en FreeBASIC)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(14 intermediate revisions by 10 users not shown)
Line 48:
<math>\mathit{arg}_1,\mathit{arg}_2,...,\mathit{arg}_n</math> are the arguments — natural numbers — that the sought function receives.
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F partitions(lengths)
[[[Int]]] r
[(Int, Int)] slices
V delta = -1
V idx = 0
L(length) lengths
assert(length >= 0, ‘lengths must not be negative.’)
delta += length
slices.append((idx, delta))
idx += length
 
V n = sum(lengths)
V perm = Array(1 .. n)
 
L
[[Int]] part
L(start, end) slices
V s = perm[start .. end]
I !s.is_sorted()
L.break
part.append(s)
L.was_no_break
r.append(part)
 
I !perm.next_permutation()
L.break
 
R r
 
F toString(part)
V result = ‘(’
L(s) part
I result.len > 1
result ‘’= ‘, ’
result ‘’= ‘{’s.join(‘, ’)‘}’
R result‘)’
 
F displayPermutations(lengths)
print(‘Ordered permutations for (’lengths.join(‘, ’)‘):’)
L(part) partitions(lengths)
print(toString(part))
 
:start:
I :argv.len > 1
displayPermutations(:argv[1..].map(Int))
E
displayPermutations([2, 0, 2])</syntaxhighlight>
 
{{out}}
<pre>
Ordered permutations for (2, 0, 2):
({1, 2}, {}, {3, 4})
({1, 3}, {}, {2, 4})
({1, 4}, {}, {2, 3})
({2, 3}, {}, {1, 4})
({2, 4}, {}, {1, 3})
({3, 4}, {}, {1, 2})
 
Ordered permutations for (1, 1, 1):
({1}, {2}, {3})
({1}, {3}, {2})
({2}, {1}, {3})
({2}, {3}, {1})
({3}, {1}, {2})
({3}, {2}, {1})
</pre>
 
=={{header|Ada}}==
partitions.ads:
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Indefinite_Ordered_Sets;
with Ada.Containers.Ordered_Sets;
package Partitions is
Line 63 ⟶ 133:
(Partition);
function Create_Partitions (Args : Arguments) return Partition_Sets.Set;
end Partitions;</langsyntaxhighlight>
 
partitions.adb:
<langsyntaxhighlight Adalang="ada">package body Partitions is
-- compare number sets (not provided)
function "<" (Left, Right : Number_Sets.Set) return Boolean is
Line 213 ⟶ 283:
return Result;
end Create_Partitions;
end Partitions;</langsyntaxhighlight>
 
example main.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Partitions;
procedure Main is
Line 276 ⟶ 346:
Ada.Text_IO.New_Line;
end;
end Main;</langsyntaxhighlight>
 
Output:
Line 289 ⟶ 359:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM list1%(2) : list1%() = 2, 0, 2
PRINT "partitions(2,0,2):"
PRINT FNpartitions(list1%())
Line 340 ⟶ 410:
j% -= 1
ENDWHILE
= TRUE</langsyntaxhighlight>
'''Output:'''
<pre>
Line 376 ⟶ 446:
=={{header|C}}==
Watch out for blank for loops. Iterative permutation generation is described at [[http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations]]; code messness is purely mine.
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
int next_perm(int size, int * nums)
Line 426 ⟶ 496:
 
return 1;
}</langsyntaxhighlight>
Output:
<pre>Part 2 0 2:
Line 444 ⟶ 514:
{ 0 } { 1 2 } { 3 5 6 } { 4 7 8 9 }
....</pre>
With bitfield:<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned int uint;
Line 494 ⟶ 564:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
Line 564 ⟶ 634:
static string Delimit<T>(this IEnumerable<T> source, string separator) => string.Join(separator, source);
static string Encase(this string s, char start, char end) => start + s + end;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 584 ⟶ 654:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <algorithm>
Line 637 ⟶ 707:
std::cin.get();
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 649 ⟶ 719:
=={{header|Common Lisp}}==
Lexicographical generation of partitions. Pros: can handle duplicate elements; probably faster than some methods generating all permutations then throwing bad ones out. Cons: clunky (which is probably my fault).
<langsyntaxhighlight lang="lisp">(defun fill-part (x i j l)
(let ((e (elt x i)))
(loop for c in l do
Line 694 ⟶ 764:
(loop while a do
(format t "~a~%" a)
(setf a (next-part a #'string<))))</langsyntaxhighlight>output
<pre>#((1 2) NIL (3 4))
#((1 3) NIL (2 4))
Line 710 ⟶ 780:
{{trans|Python}}
Using module of the third D entry of the Combination Task.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.array, std.conv,
combinations3;
 
Line 734 ⟶ 804:
auto b = args.length > 1 ? args.dropOne.to!(int[]) : [2, 0, 2];
writefln("%(%s\n%)", b.orderPart);
}</langsyntaxhighlight>
{{out}}
<pre>[[1, 2], [], [3, 4]]
Line 745 ⟶ 815:
===Alternative Version===
{{trans|C}}
<langsyntaxhighlight lang="d">import core.stdc.stdio;
 
void genBits(size_t N)(ref uint[N] bits, in ref uint[N] parts,
Line 788 ⟶ 858:
uint[parts.length] bits;
genBits(bits, parts, m - 1, m - 1, 0, parts[0], 0);
}</langsyntaxhighlight>
{{out}}
<pre>[1 2 ][][3 4 ]
Line 798 ⟶ 868:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'list) ;; (combinations L k)
 
Line 824 ⟶ 894:
writeln
(_partitions (range 1 (1+ (apply + args))) args )))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 861 ⟶ 931:
{{trans|Ruby}}
Brute force approach:
<langsyntaxhighlight lang="elixir">defmodule Ordered do
def partition([]), do: [[]]
def partition(mask) do
Line 890 ⟶ 960:
IO.inspect part
end)
end)</langsyntaxhighlight>
 
{{out}}
Line 920 ⟶ 990:
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight FreeBASIClang="freebasic">Function Perm(x() As Integer) As Boolean
Dim As Integer i, j
For i = Ubound(x,1)-1 To 0 Step -1
Line 974 ⟶ 1,044:
Print Particiones(list3())
 
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 1,003 ⟶ 1,073:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">FixedPartitions := function(arg)
local aux;
aux := function(i, u)
Line 1,030 ⟶ 1,100:
FixedPartitions(1, 1, 1);
# [ [ [ 1 ], [ 2 ], [ 3 ] ], [ [ 1 ], [ 3 ], [ 2 ] ], [ [ 2 ], [ 1 ], [ 3 ] ],
# [ [ 2 ], [ 3 ], [ 1 ] ], [ [ 3 ], [ 1 ], [ 2 ] ], [ [ 3 ], [ 2 ], [ 1 ] ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,092 ⟶ 1,162:
}
ordered_part(n)
}</langsyntaxhighlight>
Example command line use:
<pre>
Line 1,128 ⟶ 1,198:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def partitions = { int... sizes ->
int n = (sizes as List).sum()
def perms = n == 0 ? [[]] : (1..n).permutations()
Line 1,140 ⟶ 1,210:
return recomp[0] <=> recomp[1]
}
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">partitions(2, 0, 2).each {
println it
}</langsyntaxhighlight>
 
Output:
Line 1,156 ⟶ 1,226:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List ((\\))
 
comb :: Int -> [a] -> [[a]]
Line 1,168 ⟶ 1,238:
p xs (k:ks) = [ cs:rs | cs <- comb k xs, rs <- p (xs \\ cs) ks ]
 
main = print $ partitions [2,0,2]</langsyntaxhighlight>
 
An alternative where <code>\\</code> is not needed anymore because <code>comb</code> now not only
keeps the chosen elements but also the not chosen elements together in a tuple.
 
<langsyntaxhighlight lang="haskell">comb :: Int -> [a] -> [([a],[a])]
comb 0 xs = [([],xs)]
comb _ [] = []
Line 1,184 ⟶ 1,254:
p xs (k:ks) = [ cs:rs | (cs,zs) <- comb k xs, rs <- p zs ks ]
 
main = print $ partitions [2,0,2]</langsyntaxhighlight>
 
Output:
Line 1,193 ⟶ 1,263:
 
Faster by keeping track of the length of lists:
<syntaxhighlight lang="haskell">import Data.Bifunctor (first, second)
<lang haskell>-- choose m out of n items, return tuple of chosen and the rest
choose aa _ 0 = [([], aa)]
choose aa@(a:as) n m
| n == m = [(aa, [])]
| otherwise = map (\(x,y) -> (a:x, y)) (choose as (n-1) (m-1)) ++
map (\(x,y) -> (x, a:y)) (choose as (n-1) m)
 
-- choose m out of n items, return tuple of chosen and the rest
partitions x = combos [1..n] n x where
n = sum x
combos _ _ [] = [[]]
combos s n (x:xs) = [ l : r | (l,rest) <- choose s n x,
r <- combos rest (n - x) xs]
 
choose :: [Int] -> Int -> Int -> [([Int], [Int])]
choose [] _ _ = [([], [])]
choose aa _ 0 = [([], aa)]
choose aa@(a : as) n m
| n == m = [(aa, [])]
| otherwise =
(first (a :) <$> choose as (n - 1) (m - 1))
<> (second (a :) <$> choose as (n - 1) m)
 
partitions :: [Int] -> [[[Int]]]
partitions x = combos [1 .. n] n x
where
n = sum x
combos _ _ [] = [[]]
combos s n (x : xs) =
[ l : r
| (l, rest) <- choose s n x,
r <- combos rest (n - x) xs
]
 
main :: IO ()
main = mapM_ print $ partitions [5,5,5]</lang>
main = mapM_ print $ partitions [5, 5, 5]</syntaxhighlight>
 
=={{header|J}}==
Line 1,213 ⟶ 1,294:
Brute force approach:
 
<langsyntaxhighlight lang="j">require'stats'
partitions=: ([,] {L:0 (i.@#@, -. [)&;)/"1@>@,@{@({@comb&.> +/\.)</langsyntaxhighlight>
 
First we compute each of the corresponding combinations for each argument, then we form their cartesian product and then we restructure each of those products by: eliminating from values populating the the larger set combinations the combinations already picked from the smaller set and using the combinations from the larger set to index into the options which remain.
Line 1,220 ⟶ 1,301:
Examples:
 
<langsyntaxhighlight lang="j"> partitions 2 0 2
┌───┬┬───┐
│0 1││2 3│
Line 1,258 ⟶ 1,339:
360360
*/ (! +/\.)3 5 7
360360</langsyntaxhighlight>
 
Here's some intermediate results for that first example:
 
<langsyntaxhighlight Jlang="j"> +/\. 2 0 2
4 2 2
({@comb&.> +/\.) 2 0 2
Line 1,283 ⟶ 1,364:
├───┼┼───┤
│2 3││0 1│
└───┴┴───┘</langsyntaxhighlight>
 
In other words, initially we just work with relevant combinations (working from right to left). To understand the step which produces the final result, consider this next sequence of results (J's <code>/</code> operator works from right to left, as that's the pattern established by assignment operations, and because that has some interesting and useful mathematical properties):
 
<langsyntaxhighlight Jlang="j"> ([,] {L:0 (i.@#@, -. [)&;)/0 1;0 1
┌───┬───┐
│0 1│2 3│
Line 1,298 ⟶ 1,379:
┌───┬───┬───┬───┐
│0 1│2 3│4 5│6 7│
└───┴───┴───┴───┘</langsyntaxhighlight>
 
Breaking down that last example:
 
<langsyntaxhighlight Jlang="j"> (<0 1) ([,] {L:0 (i.@#@, -. [)&;)0 1;2 3;4 5
┌───┬───┬───┬───┐
│0 1│2 3│4 5│6 7│
└───┴───┴───┴───┘</langsyntaxhighlight>
 
Here, on the right hand side we form 0 1 0 1 2 3 4 5, count how many things are in it (8), form 0 1 2 3 4 5 6 7 from that and then remove 0 1 (the values in the left argument) leaving us with 2 3 4 5 6 7. Meanwhile, on the left side, keep our left argument intact and use the indices in the remaining boxes to select from the right argument. In theoretical terms this is not particularly efficient, but we are working with very short lists here (because otherwise we run out of memory for the result as a whole), so the actual cost is trivial. Also note that sequential loops tend to be faster than nested loops (though we do get the effect of a nested loop, here - and that was the theoretical inefficiency).
 
=={{header|Java}}==
 
<syntaxhighlight lang="java">
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public final class OrderedPartitions {
 
public static void main(String[] aArgs) {
List<Integer> sizes = ( aArgs == null || aArgs.length == 0 ) ?
List.of( 2, 0, 2 ) : Arrays.stream(aArgs).map( s -> Integer.valueOf(s) ).toList();
System.out.println("Partitions for " + sizes + ":");
final int total = sizes.stream().reduce(0, Integer::sum);
List<Integer> permutation = IntStream.rangeClosed(1, total).boxed().collect(Collectors.toList());
while ( hasNextPermutation(permutation) ) {
List<List<Integer>> partition = new ArrayList<List<Integer>>();
int sum = 0;
boolean isValid = true;
for ( int size : sizes ) {
List<Integer> subList = permutation.subList(sum, sum + size);
if ( ! isIncreasing(subList) ) {
isValid = false;
break;
}
partition.add(subList);
sum += size;
}
if ( isValid ) {
System.out.println(" ".repeat(4) + partition);
}
}
}
private static boolean hasNextPermutation(List<Integer> aPerm) {
final int lastIndex = aPerm.size() - 1;
int i = lastIndex;
while ( i > 0 && aPerm.get(i - 1) >= aPerm.get(i) ) {
i--;
}
if ( i <= 0 ) {
return false;
}
int j = lastIndex;
while ( aPerm.get(j) <= aPerm.get(i - 1) ) {
j--;
}
swap(aPerm, i - 1, j);
j = lastIndex;
while ( i < j ) {
swap(aPerm, i++, j--);
}
return true;
}
private static boolean isIncreasing(List<Integer> aList) {
return aList.stream().sorted().toList().equals(aList);
}
private static void swap(List<Integer> aList, int aOne, int aTwo) {
final int temp = aList.get(aOne);
aList.set(aOne, aList.get(aTwo));
aList.set(aTwo, temp);
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
Partitions for [2, 0, 2]:
[[1, 3], [], [2, 4]]
[[1, 4], [], [2, 3]]
[[2, 3], [], [1, 4]]
[[2, 4], [], [1, 3]]
[[3, 4], [], [1, 2]]
</pre>
 
=={{header|JavaScript}}==
Line 1,315 ⟶ 1,483:
{{trans|Haskell}}
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,375 ⟶ 1,543:
return partitions(2, 0, 2);
 
})();</langsyntaxhighlight>
 
{{Out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">[[[1, 2], [], [3, 4]],
[[1, 3], [], [2, 4]],
[[1, 4], [], [2, 3]],
[[2, 3], [], [1, 4]],
[[2, 4], [], [1, 3]],
[[3, 4], [], [1, 2]]]</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
''The approach adopted here is similar to the [[#Python]] solution''.
<langsyntaxhighlight lang="jq"># Generate a stream of the distinct combinations of r items taken from the input array.
def combination(r):
if r > length or r < 0 then empty
Line 1,408 ⟶ 1,576:
| [$c] + ($mask[1:] | p(s - $c))
end;
. as $mask | p( [range(1; 1 + ($mask|add))] );</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">([],[0,0,0],[1,1,1],[2,0,2])
| . as $test_case
| "partitions \($test_case):" , ($test_case | partition), ""</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -n -c -r -f Ordered_partitions.jq
 
partitions []:
Line 1,436 ⟶ 1,604:
[[2,3],[],[1,4]]
[[2,4],[],[1,3]]
[[3,4],[],[1,2]]</langsyntaxhighlight>
 
=={{header|Julia}}==
The method used, as seen in the function masked(), is to take a brute force permutation of size n = sum of partition,
partition it using the provided mask, and then sort the inner lists in order to properly filter duplicates.
<syntaxhighlight lang="julia">
<lang Julian>
using Combinatorics
 
Line 1,467 ⟶ 1,635:
println(orderedpartitions([1, 1, 1]))
 
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 1,485 ⟶ 1,653:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun nextPerm(perm: IntArray): Boolean {
Line 1,553 ⟶ 1,721:
while (nextPerm(perm))
println("]")
}</langsyntaxhighlight>
 
{{out}}
Line 1,586 ⟶ 1,754:
=={{header|Lua}}==
A pretty verbose solution. Maybe somebody can replace with something terser/better.
<langsyntaxhighlight lang="lua">--- Create a list {1,...,n}.
local function range(n)
local res = {}
Line 1,674 ⟶ 1,842:
end
io.write "]"
io.write "\n"</langsyntaxhighlight>
 
Output:
Line 1,682 ⟶ 1,850:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
This code works as follows:
 
'''Permutations''' finds all permutations of the numbers ranging from 1 to n.
 
'''w''' finds the required partition for an individual permutation.
 
'''m''' finds partitions for all permutations.
 
'''Sort''' and '''Union''' eliminate duplicates.
 
<syntaxhighlight lang="mathematica">w[partitions_]:=Module[{s={},t=Total@partitions,list=partitions,k}, n=Length[list];
<lang Mathematica>
w[partitions_]:=Module[{s={},t=Total@partitions,list=partitions,k}, n=Length[list];
While[n>0,s=Join[s,{Take[t,(k=First[list])]}];t=Drop[t,k];list=Rest[list];n--]; s]
m[p_]:=(Sort/@#)&/@(w[#,p]&/@Permutations[Range@Total[p]])//Union</syntaxhighlight>
'''Usage'''
Grid displays the output in a table.
<syntaxhighlight lang="mathematica">Grid@m[{2, 0, 2}]
Grid@m[{1, 1, 1}]</syntaxhighlight>
[[File:Example.png]]
 
=={{header|Nim}}==
m[p_]:=(Sort/@#)&/@(w[#,p]&/@Permutations[Range@Total[p]])//Union
We use the function <code>nextPermutation</code> form standard module “algorithm” to build the permutations. The partition is built by using a list of slices. We keep only the partitions which contain sequences sorted by ascending order. Those partitions are yielded by an iterator.
</lang>
 
The iterator may be called with a list of integer arguments or a single list of integers as argument.
As requested, the arguments specifying the length of each sequence may also be provided on the command line.
 
<syntaxhighlight lang="nim">import algorithm, math, sequtils, strutils
'''Usage'''
 
type Partition = seq[seq[int]]
Grid displays the output in a table.
 
<lang Mathematica>
Grid@m[{2, 0, 2}]
 
func isIncreasing(s: seq[int]): bool =
Grid@m[{1, 1, 1}]
## Return true if the sequence is sorted in increasing order.
</lang>
var prev = 0
for val in s:
if prev >= val: return false
prev = val
result = true
 
 
[[File:Example.png]]
iterator partitions(lengths: varargs[int]): Partition =
## Yield the partitions for lengths "lengths".
 
# Build the list of slices to use for partitionning.
var slices: seq[Slice[int]]
var delta = -1
var idx = 0
for length in lengths:
assert length >= 0, "lengths must not be negative."
inc delta, length
slices.add idx..delta
inc idx, length
 
# Build the partitions.
let n = sum(lengths)
var perm = toSeq(1..n)
while true:
 
block buildPartition:
var part: Partition
for slice in slices:
let s = perm[slice]
if not s.isIncreasing():
break buildPartition
part.add s
yield part
 
if not perm.nextPermutation():
break
 
 
func toString(part: Partition): string =
## Return the string representation of a partition.
result = "("
for s in part:
result.addSep(", ", 1)
result.add '{' & s.join(", ") & '}'
result.add ')'
 
 
when isMainModule:
 
import os
 
proc displayPermutations(lengths: varargs[int]) =
## Display the permutations.
echo "Ordered permutations for (", lengths.join(", "), "):"
for part in partitions(lengths):
echo part.toString
 
if paramCount() > 0:
var args: seq[int]
for param in commandLineParams():
try:
let val = param.parseInt()
if val < 0: raise newException(ValueError, "")
args.add val
except ValueError:
quit "Wrong parameter: " & param
displayPermutations(args)
 
else:
displayPermutations(2, 0, 2)</syntaxhighlight>
 
{{out}}
<pre>$ ./ordered_partitions
Ordered permutations for (2, 0, 2):
({1, 2}, {}, {3, 4})
({1, 3}, {}, {2, 4})
({1, 4}, {}, {2, 3})
({2, 3}, {}, {1, 4})
({2, 4}, {}, {1, 3})
({3, 4}, {}, {1, 2})</pre>
<pre>$ ./ordered_partitions 1 1 1
Ordered permutations for (1, 1, 1):
({1}, {2}, {3})
({1}, {3}, {2})
({2}, {1}, {3})
({2}, {3}, {1})
({3}, {1}, {2})
({3}, {2}, {1})</pre>
 
=={{header|Perl}}==
===Threaded Generator Method===
Code 1: threaded generator method. This code demonstrates how to make something like Python's
This code demonstrates how to make something like Python's
generators or Go's channels by using Thread::Queue. Granted, this is horribly inefficient, with constantly creating and killing threads and whatnot (every time a partition is created, a thread is made to produce the next partition, so thousands if not millions of threads live and die, depending on the problem size). But algorithms are often more naturally expressed in a coroutine manner -- for this example, "making a new partition" and "picking elements for a partition" can be done in separate recursions cleanly if so desired. It's about 20 times slower than the next code example, so there.
 
<syntaxhighlight lang ="perl">use Thread 'async'strict;
use warnings;
use Thread 'async';
use Thread::Queue;
 
Line 1,744 ⟶ 2,001:
};
 
$q = new Thread::Queue->new;
(async{ &$gen; # start the main work load
$q->enqueue(undef) # signal that there's no more data
Line 1,760 ⟶ 2,017:
print "@$a | @$b | @$rb\n";
}
}</syntaxhighlight>
}
</lang>
 
Code 2: ===Recursive solution.===
{{trans|Raku}}
<syntaxhighlight lang ="perl">use List::Util 1.33 qw(sum pairmap)strict;
use warnings;
use List::Util 1.33 qw(sum pairmap);
 
sub partition {
Line 1,783 ⟶ 2,041:
 
print "(" . join(', ', map { "{".join(', ', @$_)."}" } @$_) . ")\n"
for partition( @ARGV ? @ARGV : (2, 0, 2) );</langsyntaxhighlight>
 
Example command-line use:
Line 1,807 ⟶ 2,065:
 
=={{header|Phix}}==
Uses the permutes() routine [new in 1.0.2], which handles duplicate elements properly, so in the {1,2,3,4} test
Note that the builtin permute() function returns results in an idiosyncratic manner, so we use sort a lot and check for duplicates,
this only generates 12,600 combinations, whereas the previous version generated and obviously filtered and sorted
which might make this a tad inefficient.
all of the possible 3,628,800 full permutations, therefore it is now at least a couple of hundred times faster.
<lang Phix>function partitions(sequence s)
<!--<syntaxhighlight lang="phix">(phixonline)-->
integer N = sum(s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence set = tagset(N), perm,
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span>
results = {}, result, resi
<span style="color: #008080;">function</span> <span style="color: #000000;">partitions</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to factorial(N) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
perm = permute(i,set)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">pset</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000080;font-style:italic;">-- eg s==={2,0,2} -&gt; {1,1,3,3}</span>
integer n = 1
<span style="color: #000000;">rn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "" -&gt; <nowiki>{{</nowiki>0,0},{},{0,0<nowiki>}}</nowiki></span>
result = {}
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
for j=1 to length(s) do
<span style="color: #000000;">pset</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
resi = {}
<span style="color: #000000;">rn</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
for k=1 to s[j] do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
resi = append(resi,perm[n])
<span style="color: #008080;">if</span> <span style="color: #000000;">pset</span><span style="color: #0000FF;">={}</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">rn</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- edge case</span>
n += 1
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">permutes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pset</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000080;font-style:italic;">-- eg {1,1,3,3} means put 1,2 in [1], 3,4 in [3]
result = append(result,sort(resi))
-- .. {3,3,1,1} means put 1,2 in [3], 3,4 in [1]</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if not find(result,results) then
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ri</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000080;font-style:italic;">-- a "flat" permute</span>
results = append(results,result)
<span style="color: #000000;">rdii</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- where per set</span>
end if
<span style="color: #004080;">integer</span> <span style="color: #000000;">rii</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ri</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
return sort(results)
<span style="color: #004080;">integer</span> <span style="color: #000000;">rdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ri</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span> <span style="color: #000080;font-style:italic;">-- which set</span>
end function
<span style="color: #000000;">rnx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rdii</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rdx</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- wherein""</span>
 
<span style="color: #000000;">rii</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
ppOpt({pp_Nest,1})
<span style="color: #000000;">rn</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rdx</span><span style="color: #0000FF;">][</span><span style="color: #000000;">rnx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rii</span> <span style="color: #000080;font-style:italic;">-- plant 1..N</span>
pp(partitions({2,0,2}))
<span style="color: #000000;">rdii</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rnx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
pp(partitions({1,1,1}))
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
pp(partitions({1,2,0,1}))
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rii</span><span style="color: #0000FF;">=</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
pp(partitions({}))
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rn</span><span style="color: #0000FF;">)</span>
pp(partitions({0,0,0}))</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">partitions</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ia</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">?{</span><span style="color: #008000;">"is"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">}:{</span><span style="color: #008000;">"are"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"s"</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"There %s %,d ordered partion%s for %v:\n{%s}\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">ia</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">),</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%v"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"\n "</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{},{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}},</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
There are 6 ordered partions for {2,0,2}:
{{{1,2}, {}, {3,4}},
{{{1,32}, {}, {23,4}},
{{1,43}, {}, {2,34}},
{{21,34}, {}, {12,43}},
{{2,43}, {}, {1,34}},
{{32,4}, {}, {1,2}3}}
{{{13,4}, {2}, {31,2}}},
There are 6 ordered partions for {1,1,1}:
{{1}, {3}, {2}},
{{2{1}, {12}, {3}},
{{21}, {3}, {12}},
{{32}, {1}, {23}},
{{3}, {21}, {1}2}}
{{{12}, {2,3}, {1}, {4}},
{{13}, {2,4}, {1}, {3}},
There are 12 ordered partions for {1,2,0,1}:
{{1}, {3,4}, {}, {2}},
{{2{1}, {12,3}, {}, {4}},
{{21}, {12,4}, {}, {3}},
{{21}, {3,4}, {}, {12}},
{{32}, {1,23}, {}, {4}},
{{32}, {1,4}, {}, {23}},
{{3}, {1,2,4}, {}, {14}},
{{4}, {1,2}, {}, {3}},
{{43}, {1,34}, {}, {2}},
{{4}, {21,3}, {}, {1}2}}
{{2},{3,4},{},{1}}
{{3},{2,4},{},{1}}
{{4},{2,3},{},{1}}}
There are 12,600 ordered partions for {1,2,3,4}:
{{{1},{2,3},{4,5,6},{7,8,9,10}}
{{1},{2,3},{4,5,7},{6,8,9,10}}
{{1},{2,3},{4,5,8},{6,7,9,10}}
{{1},{2,3},{4,5,9},{6,7,8,10}}
{{1},{2,3},{4,5,10},{6,7,8,9}}
...
{{9},{7,10},{5,6,8},{1,2,3,4}}
{{10},{7,9},{5,6,8},{1,2,3,4}}
{{8},{9,10},{5,6,7},{1,2,3,4}}
{{9},{8,10},{5,6,7},{1,2,3,4}}
{{10},{8,9},{5,6,7},{1,2,3,4}}}
There is 1 ordered partion for {}:
{{}}
There is 1 ordered partion for {0,0,0}:
{{{}, {}, {}}}
{{{},{},{}}}
</pre>
 
=={{header|PicoLisp}}==
Uses the 'comb' function from [[Combinations#PicoLisp]]
<langsyntaxhighlight PicoLisplang="picolisp">(de partitions (Args)
(let Lst (range 1 (apply + Args))
(recur (Args Lst)
Line 1,880 ⟶ 2,167:
'((R) (cons L R))
(recurse (cdr Args) (diff Lst L)) ) )
(comb (car Args) Lst) ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (more (partitions (2 0 2)))
Line 1,901 ⟶ 2,188:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import combinations
 
def partitions(*args):
Line 1,915 ⟶ 2,202:
return p(s, *args)
 
print partitions(2, 0, 2)</langsyntaxhighlight>
 
An equivalent but terser solution.
<langsyntaxhighlight lang="python">from itertools import combinations as comb
 
def partitions(*args):
Line 1,927 ⟶ 2,214:
return p(range(1, sum(args) + 1), *args)
 
print partitions(2, 0, 2)</langsyntaxhighlight>
 
Output:
Line 1,938 ⟶ 2,225:
Or, more directly, without importing the ''combinations'' library:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Ordered Partitions'''
 
 
Line 2,044 ⟶ 2,331:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Tests of the partitions function:
Line 2,070 ⟶ 2,357:
{{trans|Haskell}}
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (comb k xs)
Line 2,094 ⟶ 2,381:
(run 2 0 2)
(run 1 1 1)
</syntaxhighlight>
</lang>
 
Output:
Line 2,118 ⟶ 2,405:
(formerly Perl 6)
{{works with|Rakudo|2018.04.1}}
<syntaxhighlight lang="raku" perl6line>sub partition(@mask is copy) {
my @op;
my $last = [+] @mask or return [] xx 1;
Line 2,132 ⟶ 2,419:
}
 
.say for reverse partition [2,0,2];</langsyntaxhighlight>
{{out}}
<pre>[[1, 2], (Any), [3, 4]]
Line 2,142 ⟶ 2,429:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">//*REXX program displays the ordered partitions as: orderedPartitions(i, j, k, ···). */
call orderedPartitions 2,0,2 /*Note: 2,,2 will also work. */
call orderedPartitions 1,1,1
Line 2,185 ⟶ 2,472:
say center($, length(hdr) ) /*display numbers in ordered partition.*/
end /*g*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,224 ⟶ 2,511:
=={{header|Ruby}}==
'''Brute force approach:''' simple but very slow
<langsyntaxhighlight lang="ruby">def partition(mask)
return [[]] if mask.empty?
[*1..mask.inject(:+)].permutation.map {|perm|
mask.map {|num_elts| perm.shift(num_elts).sort }
}.uniq
end</langsyntaxhighlight>
 
'''Recursive version:''' faster
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def part(s, args)
return [[]] if args.empty?
s.combination(args[0]).each_with_object([]) do |c, res|
Line 2,242 ⟶ 2,529:
return [[]] if args.empty?
part((1..args.inject(:+)).to_a, args)
end</langsyntaxhighlight>
 
'''Test:'''
<langsyntaxhighlight lang="ruby">[[],[0,0,0],[1,1,1],[2,0,2]].each do |test_case|
puts "partitions #{test_case}:"
partition(test_case).each{|part| p part }
puts
end</langsyntaxhighlight>
{{Output}}
<pre>
Line 2,273 ⟶ 2,560:
[[2, 4], [], [1, 3]]
[[3, 4], [], [1, 2]]
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use itertools::Itertools;
 
type NArray = Vec<Vec<Vec<usize>>>;
 
fn generate_partitions(args: &[usize]) -> NArray {
// calculate the sum of all partitions
let max = args.iter().sum();
 
// generate combinations with the given lengths
// for each partition
let c = args.iter().fold(vec![], |mut acc, arg| {
acc.push((1..=max).combinations(*arg).collect::<Vec<_>>());
acc
});
 
// create a cartesian product of all individual combinations
// filter/keep only where all the elements are there and exactly once
c.iter()
.map(|i| i.iter().cloned())
.multi_cartesian_product()
.unique()
.filter(|x| x.iter().cloned().flatten().unique().count() == max)
.collect::<Vec<_>>()
}
 
#[allow(clippy::clippy::ptr_arg)]
fn print_partitions(result: &NArray) {
println!("Partitions:");
for partition in result {
println!("{:?}", partition);
}
}
fn main() {
print_partitions(generate_partitions(&[2, 0, 2]).as_ref());
print_partitions(generate_partitions(&[1, 1, 1]).as_ref());
print_partitions(generate_partitions(&[2, 3]).as_ref());
print_partitions(generate_partitions(&[0]).as_ref());
}
</syntaxhighlight>
{{out}}
<pre>
Partitions:
[[1, 2], [], [3, 4]]
[[1, 3], [], [2, 4]]
[[1, 4], [], [2, 3]]
[[2, 3], [], [1, 4]]
[[2, 4], [], [1, 3]]
[[3, 4], [], [1, 2]]
Partitions:
[[1], [2], [3]]
[[1], [3], [2]]
[[2], [1], [3]]
[[2], [3], [1]]
[[3], [1], [2]]
[[3], [2], [1]]
Partitions:
[[1, 2], [3, 4, 5]]
[[1, 3], [2, 4, 5]]
[[1, 4], [2, 3, 5]]
[[1, 5], [2, 3, 4]]
[[2, 3], [1, 4, 5]]
[[2, 4], [1, 3, 5]]
[[2, 5], [1, 3, 4]]
[[3, 4], [1, 2, 5]]
[[3, 5], [1, 2, 4]]
[[4, 5], [1, 2, 3]]
Partitions:
[[]]
</pre>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func part(_, {.is_empty}) { [[]] }
func partitions({.is_empty}) { [[]] }
 
Line 2,283 ⟶ 2,642:
gather {
s.combinations(args[0], { |*c|
part(s - c, args.ftslice(1)).each{|r| take([c] + r) }
})
}
Line 2,296 ⟶ 2,655:
partitions(test_case).each{|part| say part }
print "\n"
}</langsyntaxhighlight>
 
{{out}}
Line 2,325 ⟶ 2,684:
=={{header|Tcl}}==
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::set
 
Line 2,376 ⟶ 2,735:
 
return [buildPartitions $startingSet {*}$args]
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">puts [partitions 1 1 1]
puts [partitions 2 2]
puts [partitions 2 0 2]
puts [partitions 2 2 0]</langsyntaxhighlight>
Output:
<pre>
Line 2,391 ⟶ 2,750:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 2,398 ⟶ 2,757:
-+
~&art^?\~&alNCNC ^|JalSPfarSPMplrDSL/~& ^DrlPrrPlXXS/~&rt ^DrlrjXS/~&l choices@lrhPX,
^\~& nrange/1+ sum:-0+-</langsyntaxhighlight>
The library function <code>choices</code> used in this solution takes a pair <math>(s,k)</math> and returns the set of all subsets of <math>s</math> having cardinality <math>k</math>. The library function <code>nrange</code> takes a pair of natural numbers to the minimum consecutive sequence containing them. The <code>sum</code> function adds a pair of natural numbers.<langsyntaxhighlight Ursalalang="ursala">#cast %nLLL
 
test = opart <2,0,2></langsyntaxhighlight>
output:
<pre><
Line 2,413 ⟶ 2,772:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">import "os" for Process
 
var genPart // recursive so predeclare
Line 2,460 ⟶ 2,819:
i = i + 1
}
orderedPart.call(n)</langsyntaxhighlight>
 
{{out}}
Line 2,497 ⟶ 2,856:
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn partitions(args){
args=vm.arglist;
s:=(1).pump(args.sum(0),List); // (1,2,3,...)
Line 2,509 ⟶ 2,868:
res
}(s,args)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">args:=vm.arglist.apply("toInt"); // aka argv[1..]
if(not args) args=T(2,0,2);
partitions(args.xplode()).pump(Console.println,Void);
// or: foreach p in (partitions(1,1,1)){ println(p) }</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits