Permutations with repetitions: Difference between revisions

Add SML
(Add Rust implementation)
(Add SML)
(12 intermediate revisions by 9 users not shown)
Line 17:
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="11l">V n = 3
V values = [‘A’, ‘B’, ‘C’, ‘D’]
V k = values.len
Line 39:
i++
I i == n
^L.break</langsyntaxhighlight>
 
{{out}}
Line 59:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude_permutations_with_repetitions.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
MODE PERMELEMLIST = FLEX[0]PERMELEM;
Line 89:
);
 
SKIP</langsyntaxhighlight>'''File: test_permutations_with_repetitions.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 114:
# OD #));
done: SKIP
)</langsyntaxhighlight>'''Output:'''
<pre>
Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Line 134:
Permutations with repetitions, using strict evaluation, generating the entire set (where system constraints permit) with some degree of efficiency. For lazy or interruptible evaluation, see the second example below.
 
<langsyntaxhighlight AppleScriptlang="applescript">-- e.g. replicateM(3, {1, 2})) ->
-- {{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1},
-- {2, 1, 2}, {2, 2, 1}, {2, 2, 2}}
Line 208:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</langsyntaxhighlight>
 
===Lazy evaluation with a generator===
Permutations with repetition by treating the <math>n^k</math> elements as an ordered set, and writing a function from a zero-based index to the nth permutation. This allows us terminate a repeated generation on some condition, or explore a sub-set without needing to generate the whole set:
<langsyntaxhighlight AppleScriptlang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 397:
end tell
return xs
end unfoldr</langsyntaxhighlight>
{{Out}}
<pre>Permutation 589 of 1024: CRACK
Found after searching from AAAAA thru ARACK</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">decide: function [pc]->
and? pc\0 = `B`
pc\1 = `C`
 
permutation: function [vals, n][
k: size vals
pn: array.of:n 0
p: array.of:n `0`
 
while [true][
loop.with:'i pn 'x -> p\[i]: vals\[x]
print p
if decide p -> return ø
i: 0
while [true][
pn\[i]: pn\[i] + 1
if pn\[i] < k -> break
pn\[i]: 0
i: i + 1
if i = n -> return ø
]
]
]
 
permutation "ABCD" 3</syntaxhighlight>
 
{{out}}
 
<pre>A A A
B A A
C A A
D A A
A B A
B B A
C B A
D B A
A C A
B C A</pre>
 
=={{header|AutoHotkey}}==
Use the function from http://rosettacode.org/wiki/Permutations#Alternate_Version with opt=1
<langsyntaxhighlight lang="ahk">P(n,k="",opt=0,delim="",str="") { ; generate all n choose k permutations lexicographically
;1..n = range, or delimited list, or string to parse
; to process with a different min index, pass a delimited list, e.g. "0`n1`n2"
Line 436 ⟶ 476:
. P(n,k-1,opt,delim,str . A_LoopField . delim)
Return s
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PERMUTATIONS_WITH_REPETITIONS.AWK
# converted from C
Line 470 ⟶ 511:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
(111)(112)(113)(114)(121)(122)(123)(124)(131)(132)(133)(134)(141)(142)(143)(144)(211)(212)(213)(214)(221)(222)(223)(224)(231)(232)(233)(234)(241)(242)(243)(244)(311)(312)(313)(314)(321)(322)(323)(324)(331)(332)(333)(334)(341)(342)(343)(344)(411)(412)(413)(414)(421)(422)(423)(424)(431)(432)(433)(434)(441)(442)(443)(444)
</pre>
 
=={{header|BASIC}}==
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">DIM list1$(1 TO 2, 1 TO 3) '= {{"a", "b", "c"}, {"a", "b", "c"}}
DIM list2$(1 TO 2, 1 TO 3) '= {{"1", "2", "3"}, {"1", "2", "3"}}
 
permutation$(list1$())
PRINT
permutation$(list2$())
END
 
SUB permutation$(list1$())
FOR n = 1 TO UBOUND(list1$,1)
FOR m = 1 TO UBOUND(list1$,2)
PRINT list1$(1, n); " "; list1$(2, m)
NEXT m
NEXT n
PRINT
END SUB</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">arraybase 1
dim list1 = {{"a", "b", "c"}, {"a", "b", "c"}}
dim list2 = {{"1", "2", "3"}, {"1", "2", "3"}}
 
call permutation(list1)
print
call permutation(list2)
end
 
subroutine permutation(list1)
for n = 1 to list1[][?]
for m = 1 to list1[][?]
print list1[1, n]; " "; list1[2, m]
next m
next n
print
end subroutine</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">Dim As String list1(1 To 2, 1 To 3) = {{"a", "b", "c"}, {"a", "b", "c"}}
Dim As String list2(1 To 2, 1 To 3) = {{"1", "2", "3"}, {"1", "2", "3"}}
 
Sub permutation(list() As String)
Dim As Integer n, m
For n = Lbound(list,2) To Ubound(list,2)
For m = Lbound(list,2) To Ubound(list,2)
Print list(1, n); " "; list(2, m)
Next m
Next n
Print
End Sub
 
permutation(list1())
Print
permutation(list2())
Sleep</syntaxhighlight>
{{out}}
<pre>a a
a b
a c
b a
b b
b c
c a
c b
c c
 
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3</pre>
 
 
=={{header|C}}==
<langsyntaxhighlight lang="d">#include <stdio.h>
#include <stdlib.h>
 
Line 510 ⟶ 638:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>(111)(112)(113)(114)(121)(122)(123)(124)(131)(132)(133)(134)(141)(142)(143)(144)(211)(212)(213)(214)(221)(222)(223)(224)(231)(232)(233)(234)(241)(242)(243)(244)(311)(312)(313)(314)(321)(322)(323)(324)(331)(332)(333)(334)(341)(342)(343)(344)(411)(412)(413)(414)(421)(422)(423)(424)(431)(432)(433)(434)(441)(442)(443)(444)</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="d">
<lang d>
#include <stdio.h>
#include <stdlib.h>
Line 590 ⟶ 718:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 599 ⟶ 727:
===opApply Version===
{{trans|Scala}}
<langsyntaxhighlight lang="d">import std.array;
 
struct PermutationsWithRepetitions(T) {
Line 640 ⟶ 768:
import std.stdio, std.array;
[1, 2, 3].permutationsWithRepetitions(2).array.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]</pre>
Line 646 ⟶ 774:
===Generator Range Version===
{{trans|Scala}}
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.concurrency;
 
Generator!(T[]) permutationsWithRepetitions(T)(T[] data, in uint n)
Line 666 ⟶ 794:
void main() {
[1, 2, 3].permutationsWithRepetitions(2).writeln;
}</langsyntaxhighlight>
The output is the same.
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'sequences) ;; (indices ..)
(lib 'list) ;; (list-permute ..)
Line 702 ⟶ 830:
(list-permute '(a b c d e) #(1 0 1 0 3 2 1))
→ (b a b a d c b)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def perm_rep(list), do: perm_rep(list, length(list))
Line 719 ⟶ 847:
Enum.each(1..3, fn n ->
IO.inspect RC.perm_rep(list,n)
end)</langsyntaxhighlight>
 
{{out}}
Line 732 ⟶ 860:
 
=={{header|Erlang}}==
<langsyntaxhighlight Erlanglang="erlang">-module(permute).
-export([permute/1]).
 
Line 738 ⟶ 866:
permute([],_) -> [[]];
permute(_,0) -> [[]];
permute(L,I) -> [[X|Y] || X<-L, Y<-permute(L,I-1)].</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 781 ⟶ 909:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 797 ⟶ 925:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
 
main = mapM_ print (replicateM 2 [1,2,3])</langsyntaxhighlight>
{{out}}
<pre>
Line 817 ⟶ 945:
Position in the sequence is an integer from <code>i.n^k</code>, for example:
 
<langsyntaxhighlight lang="j"> i.3^2
0 1 2 3 4 5 6 7 8</langsyntaxhighlight>
 
The sequence itself is expressed using <code>(k#n)#: position</code>, for example:
 
<langsyntaxhighlight lang="j"> (2#3)#:i.3^2
0 0
0 1
Line 831 ⟶ 959:
2 0
2 1
2 2</langsyntaxhighlight>
 
Partial sequences belong in a context where they are relevant and the sheer number of such possibilities make it inadvisable to generalize outside of those contexts. But anything that can generate integers will do. For example:
 
<langsyntaxhighlight lang="j"> (2#3)#:3 4 5
1 0
1 1
1 2</langsyntaxhighlight>
 
We might express this as a verb
 
<langsyntaxhighlight lang="j">perm=: # #: i.@^~</langsyntaxhighlight>
 
with example use:
 
<langsyntaxhighlight lang="j"> 2 perm 3
0 0
0 1
0 2
1 0
...</langsyntaxhighlight>
 
but the structural requirements of this task (passing intermediate results "when needed") mean that we are not looking for a word that does it all, but are instead looking for components that we can assemble in other contexts. This means that the language primitives are what's needed here.
Line 857 ⟶ 985:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.function.Predicate;
 
public class PermutationsWithRepetitions {
Line 893 ⟶ 1,021:
}
}
}</langsyntaxhighlight>
 
Output:
Line 909 ⟶ 1,037:
Permutations with repetitions, using strict evaluation, generating the entire set (where system constraints permit) with some degree of efficiency. For lazy or interruptible evaluation, see the second example below.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 970 ⟶ 1,098:
 
//--> [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]</langsyntaxhighlight>
 
Permutations with repetition by treating the <math>n^k</math> elements as an ordered set, and writing a function from a zero-based index to the nth permutation. This allows us terminate a repeated generation on some condition, or explore a sub-set without needing to generate the whole set:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,079 ⟶ 1,207:
return show(range(30, 35)
.map(curry(nthPermutationWithRepn)(['X', 'Y', 'Z'], 4)));
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,091 ⟶ 1,219:
A (strict) analogue of the (lazy) replicateM in Haskell.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,130 ⟶ 1,258:
);
// -> [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]</langsyntaxhighlight>
 
 
Line 1,138 ⟶ 1,266:
Permutations with repetition by treating the <math>n^k</math> elements as an ordered set, and writing a function from a zero-based index to the nth permutation. Wrapping this function in a generator allows us terminate a repeated generation on some condition, or explore a sub-set without needing to generate the whole set:
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,268 ⟶ 1,396:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Generated 589 of 1024 possible permutations,
Line 1,282 ⟶ 1,410:
We shall define permutations_with_replacements(n) in terms of a more general filter, combinations/0, defined as follows:
 
<langsyntaxhighlight lang="jq"># Input: an array, $in, of 0 or more arrays
# Output: a stream of arrays, c, with c[i] drawn from $in[i].
def combinations:
Line 1,295 ⟶ 1,423:
# Output: a stream of arrays of length n with elements drawn from the input array.
def permutations_with_replacements(n):
. as $in | [range(0; n) | $in] | combinations;</langsyntaxhighlight>
'''Example 1: Enumeration''':
 
Count the number of 4-combinations of [0,1,2] by enumerating them, i.e., without creating a data structure to store them all.
<langsyntaxhighlight lang="jq">def count(stream): reduce stream as $i (0; .+1);
 
count([0,1,2] | permutations_with_replacements(4))
# output: 81</langsyntaxhighlight>
 
 
Line 1,310 ⟶ 1,438:
Counting from 1, and terminating the generator when the item is found, what is the sequence number of ["c", "a", "b"] in the stream
of 3-combinations of ["a","b","c"]?
<langsyntaxhighlight lang="jq"># Input: the item to be matched
# Output: the index of the item in the stream (counting from 1);
# emit null if the item is not found
Line 1,321 ⟶ 1,449:
["c", "a", "b"] | sequence_number( ["a","b","c"] | permutations_with_replacements(3))
 
# output: 20</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,328 ⟶ 1,456:
Implements a simil-Combinatorics.jl API.
 
<langsyntaxhighlight lang="julia">struct WithRepetitionsPermutations{T}
a::T
t::Int
Line 1,355 ⟶ 1,483:
 
println("Permutations of [4, 5, 6] in 3:")
foreach(println, collect(with_repetitions_permutations([4, 5, 6], 3)))</langsyntaxhighlight>
 
{{out}}
Line 1,389 ⟶ 1,517:
=={{header|K}}==
enlist each from x on the left and each from x on the right where x is range 10
<syntaxhighlight lang="k">
<lang k>
,/x/:\:x:!10
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 1,421 ⟶ 1,549:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,438 ⟶ 1,566:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
a=("A","B","C","D")
Line 1,473 ⟶ 1,601:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,488 ⟶ 1,616:
</pre >
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Tuples[{1, 2, 3}, 2]</langsyntaxhighlight>
{{out}}
<pre>{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">apply(cartesian_product,makelist({1,2,3}, 2));</langsyntaxhighlight>
{{out}}
<pre>{[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]}</pre>
 
=={{header|Nim}}==
{{trans|Go}}
<syntaxhighlight lang="nim">import strutils
 
 
func decide(pc: openArray[char]): bool =
## Terminate when first two characters of the
## permutation are 'B' and 'C' respectively.
pc[0] == 'B' and pc[1] == 'C'
 
 
proc permute(values: openArray[char]; n: Positive) =
 
let k = values.len
var
pn = newSeq[int](n)
p = newSeq[char](n)
 
while true:
# Generate permutation
for i, x in pn: p[i] = values[x]
# Show progress.
echo p.join(" ")
# Pass to deciding function.
if decide(p): return # Terminate early.
# Increment permutation number.
var i = 0
while true:
inc pn[i]
if pn[i] < k: break
pn[i] = 0
inc i
if i == n: return # All permutations generated.
 
 
permute("ABCD", 3)</syntaxhighlight>
 
{{out}}
<pre>A A A
B A A
C A A
D A A
A B A
B B A
C B A
D B A
A C A
B C A</pre>
 
=={{header|Pascal}}==
Line 1,502 ⟶ 1,679:
Create a list of indices into what ever you want, one by one.
Doing it by addig one to a number with k-positions to base n.
<langsyntaxhighlight lang="pascal">program PermuWithRep;
//permutations with repetitions
//http://rosettacode.org/wiki/Permutations_with_repetitions
Line 1,597 ⟶ 1,774:
until Not(NextPermWithRep(p));
writeln('k: ',k,' n: ',n,' count ',cnt);
end.</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,620 ⟶ 1,797:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Algorithm::Combinatorics qw/tuples_with_repetition/;
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";</langsyntaxhighlight>
{{out}}
<pre>[A A] [A B] [A C] [B A] [B B] [B C] [C A] [C B] [C C]</pre>
 
Solving the crack problem:
<langsyntaxhighlight lang="perl">use Algorithm::Combinatorics qw/tuples_with_repetition/;
my $iter = tuples_with_repetition([qw/A C K R/], 5);
my $tries = 0;
Line 1,632 ⟶ 1,809:
$tries++;
die "Found the combination after $tries tries!\n" if join("",@$p) eq "CRACK";
}</langsyntaxhighlight>
{{out}}
<pre>Found the combination after 455 tries!</pre>
Line 1,640 ⟶ 1,817:
Asking for the 0th permutation just returns the total number of permutations (ie "").<br>
Results can be generated in any order, hence early termination is quite simply a non-issue.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function permrep(sequence set, integer n, idx=0)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer base = length(set),
<span style="color: #008080;">function</span> <span style="color: #000000;">permrep</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
nperm = power(base,n)
<span style="color: #004080;">integer</span> <span style="color: #000000;">base</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set</span><span style="color: #0000FF;">),</span>
if idx=0 then
<span style="color: #000000;">nperm</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
-- return the number of permutations
<span style="color: #008080;">if</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
return nperm
<span style="color: #000080;font-style:italic;">-- return the number of permutations</span>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">nperm</span>
-- return the idx'th [1-based] permutation
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if idx<1 or idx>nperm then ?9/0 end if
<span style="color: #000080;font-style:italic;">-- return the idx'th [1-based] permutation</span>
idx -= 1 -- make it 0-based
<span style="color: #008080;">if</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">or</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">></span><span style="color: #000000;">nperm</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
sequence res = ""
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- make it 0-based</span>
for i=1 to n do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
res = prepend(res,set[mod(idx,base)+1])
<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;">n</span> <span style="color: #008080;">do</span>
idx = floor(idx/base)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
end for
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">/</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
if idx!=0 then ?9/0 end if -- sanity check
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">if</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- sanity check</span>
end function</lang>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
Some slightly excessive testing:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<lang Phix>procedure show_all(sequence set, integer n)
integer l = permrep(set,n)
<span style="color: #000080;font-style:italic;">-- Some slightly excessive testing:</span>
sequence s = repeat(0,l)
for i=1 to l do
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_all</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">set</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lo</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hi</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
s[i] = permrep(set,n,i)
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">permrep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">if</span> <span style="color: #000000;">hi</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">hi</span><span style="color: #0000FF;">=</span><span style="color: #000000;">l</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
?s
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</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>
end procedure
<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>
 
<span style="color: #000000;">s</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: #000000;">permrep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
show_all("123",1)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
show_all("123",2)
<span style="color: #004080;">string</span> <span style="color: #000000;">mx</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">=</span><span style="color: #000000;">l</span><span style="color: #0000FF;">?</span><span style="color: #008000;">""</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"/%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)),</span>
show_all("123",3)
<span style="color: #000000;">pof</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"perms[%d..%d%s] of %v"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">lo</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">set</span><span style="color: #0000FF;">})</span>
show_all("456",3)
<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;">"Len %d %-35s: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pof</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">lo</span><span style="color: #0000FF;">..</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">],</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)})</span>
show_all({1,2,3},3)
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
show_all({"bat","fox","cow"},2)
 
<span style="color: #000000;">show_all</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"123"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
sequence s = {}
<span style="color: #000000;">show_all</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"123"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
for i=31 to 36 do
<span style="color: #000000;">show_all</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"123"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
s = append(s,permrep("XYZ",4,i))
<span style="color: #000000;">show_all</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"456"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">show_all</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;">3</span><span style="color: #0000FF;">)</span>
?s
<span style="color: #000000;">show_all</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"bat"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"fox"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cow"</span><span style="color: #0000FF;">},</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">show_all</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"XYZ"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">31</span><span style="color: #0000FF;">,</span><span style="color: #000000;">36</span><span style="color: #0000FF;">)</span>
integer l = permrep("ACKR",5)
for i=1 to l do
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">permrep</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ACKR"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
if permrep("ACKR",5,i)="CRACK" then -- 455
<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>
printf(1,"Permutation %d of %d: CRACK\n",{i,l})
<span style="color: #008080;">if</span> <span style="color: #000000;">permrep</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ACKR"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)=</span><span style="color: #008000;">"CRACK"</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- 455</span>
exit
<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;">"Len 5 perm %d/%d of \"ACKR\" : CRACK\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">})</span>
end if
<span style="color: #008080;">exit</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
--The 590th (one-based) permrep is KCARC, ie reverse(CRACK), matching the 589 result of 0-based idx solutions
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"reverse(permrep(\"ACKR\",5,589+1):%s\n",{reverse(permrep("ACKR",5,590))})</lang>
<span style="color: #000080;font-style:italic;">--The 590th (one-based) permrep is KCARC, ie reverse(CRACK), matching the 589 result of 0-based idx solutions</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;">"reverse(permrep(\"ACKR\",5,589+1):%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">permrep</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ACKR"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">590</span><span style="color: #0000FF;">))})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Len 1 perms[1..3] of "123" : {"1","2","3"}
Len 2 perms[1..9] of "123" : {"11","12","13","21","22","23...","31","32","33"}
Len 3 perms[1..27] of "123" : {"111","112","113","...","331","332","333"}
{"111","112","113","121","122","123","131","132","133","211","212","213","221","222","223","231","232","233","311","312","313","321","322","323","331","332","333"}
Len 3 perms[1..27] of "456" : {"444","445","446","...","664","665","666"}
{"444","445","446","454","455","456","464","465","466","544","545","546","554","555","556","564","565","566","644","645","646","654","655","656","664","665","666"}
{{1,1,1},{1,1,2},{1,1,Len 3},{ perms[1,2,1},{1,2,2},..27] of {1,2,3}, : {1,3,1},{1,3,2},{1,3,3},{2,1,1},{2,1,2},{2,1,3},{2,2,1},{2,2,2},{2,2,3},{2,3,1},{2,3,2},{2,3,3},{3,1,1},{3,1,2},{3,1,3},{3,2,1},{3,2,2},{3,2,3}"...",{3,3,1},{3,3,2},{3,3,3}}
{{"bat","bat"},Len 2 perms[1..9] of {"bat","fox"},{"bat","cow"}, : {{"foxbat","bat"},{"foxbat","fox"},{"foxbat","cow"},"...",{"cow","bat"},{"cow","fox"},{"cow","cow"}}
Len 4 perms[31..36/81] of "XYZ" : {"YXYX","YXYY","YXYZ","YXZX","YXZY","YXZZ"}
PermutationLen 5 perm 455/1024 of 1024"ACKR" : CRACK
reverse(permrep("ACKR",5,589+1):CRACK
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
function permutate($values, $size, $offset) {
$count = count($values);
Line 1,728 ⟶ 1,908:
echo join(',', $permutation)."\n";
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,743 ⟶ 1,923:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de permrep (N Lst)
(if (=0 N)
(cons NIL)
Line 1,749 ⟶ 1,929:
'((X)
(mapcar '((Y) (cons Y X)) Lst) )
(permrep (dec N) Lst) ) ) )</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,757 ⟶ 1,937:
To evaluate the whole set of permutations, without the option to make complete evaluation conditional, we can reach for a generic replicateM function for lists:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Permutations of n elements drawn from k values'''
 
from itertools import product
Line 1,832 ⟶ 2,012:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Permutations of two elements, drawn from three values:
Line 1,842 ⟶ 2,022:
====Applying itertools.product====
 
<langsyntaxhighlight lang="python">from itertools import product
 
# check permutations until we find the word 'crack'
Line 1,848 ⟶ 2,028:
w = ''.join(x)
print w
if w.lower() == 'crack': break</langsyntaxhighlight>
 
====Writing a generator====
Line 1,854 ⟶ 2,034:
Or, composing our own generator, by wrapping a function '''from''' an index in the range ''0 .. ((distinct items to the power of groupSize) - 1)'' '''to''' a unique permutation. (Each permutation is equivalent to a 'number' in the base of the size of the set of distinct items, in which each distinct item functions as a 'digit'):
{{Works with|Python|3.7}}
<langsyntaxhighlight Pythonlang="python">'''Generator-based permutations with repetition'''
 
from itertools import (chain, repeat)
Line 2,011 ⟶ 2,191:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Search for a 5 char permutation drawn from 'ACKR' matching "crack":
 
Permutation 589 of 1024: CRACK</pre>
 
=={{header|Quackery}}==
 
A scenario for the task: An executive has forgotten the "combination" to unlock one of the clasps on their executive briefcase. It is 222 but they can't remember that. Unlikely as it may seem, they do remember that it does not have any zeros, or any numbers greater than 6. Also, the combination, when written as English words, "two two two" requires an odd number of letters. You'd think that, remembering details like that, they'd be able to recall the number itself, but such is the nature of programming tasks. <shrug>
 
Stepping through all the possibilities from 000 to 999 would take 3^10 steps, and is just a matter of counting from 0 to 999 inclusive, left padding the small numbers with zeros as required. As we know that some numbers are precluded we can reduce this to stepping from 000 to 444 in base 4, mapping the digits 0 to 4 onto the words "one" to "five", and printing only the resultant strings which have an odd number of characters.
 
Generators are not defined in Quackery, but are easy enough to create, requiring a single line of code.
 
<syntaxhighlight lang="quackery"> [ ]this[ take ]'[ do ]this[ put ]done[ ] is generator ( --> )</syntaxhighlight>
 
An explanation of how this works is beyond the scope of this task, but the use of "meta-words" (i.e. those wrapped in ]reverse-brackets[) is explored in [https://github.com/GordonCharlton/Quackery The Book of Quackery]. How <code>generator</code> can be used is illustrated in the somewhat trivial instance used in this task, <code>counter</code>, which returns 0 the first time is is called, and one more in every subsequent call. As a convenience we also define <code>resetgen</code>, which can be used to reset a generator word to a specified state.
 
<syntaxhighlight lang="quackery"> [ ]'[ replace ] is resetgen ( x --> )</syntaxhighlight>
 
As a microscopically less trivial example of words defined using <code>generator</code> and <code>resetgen</code>, the word <code>fibonacci</code> will return subsequent numbers on the Fibonacci sequence - 0, 1, 1, 2, 3, 5, 8… on each invocation, and can be restarted by calling <code>resetfib</code>.
 
<syntaxhighlight lang="quackery"> [ generator [ do 2dup + join ] [ 0 1 ] ] is fibonacci ( --> n )
 
[ ' [ 0 1 ] resetgen fibonacci ] is resetfib ( --> )</syntaxhighlight>
 
And so to the task:
 
<syntaxhighlight lang="quackery"> [ 1 & ] is odd ( n --> b )
 
[ ]this[ take ]'[ do ]this[ put ]done[ ] is generator ( --> )
 
[ ]'[ replace ] is resetgen ( x --> )
 
[ generator [ dup 1+ ] 0 ] is counter ( --> n )
[ 0 resetgen counter ] is resetcounter ( --> n )
 
[ [] unrot times
[ base share /mod rot join swap ]
drop ] is ndigits ( n n --> [ )
 
[ [] unrot
over size base put
counter swap ndigits
witheach
[ dip dup peek
rot swap join
space join swap ]
drop
-1 split drop
base release ] is nextperm ( [ n --> [ )
 
[ [ $ "one two three four five"
nest$ ] constant
3 nextperm ] is task ( --> [ )
 
resetcounter
[ task
dup size odd if
[ dup echo$ cr ]
$ "two two two" = until ]</syntaxhighlight>
 
{{out}}
 
<pre>one one one
one one two
one one three
one two one
one two two
one two three
one three one
one three two
one three three
one four four
one four five
one five four
one five five
two one one
two one two
two one three
two two one
two two two</pre>
 
=={{header|Racket}}==
===As a sequence===
First we define a procedure that defines the sequence of the permutations.
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (permutations-with-repetitions/proc size items)
(define items-vector (list->vector items))
Line 2,053 ⟶ 2,311:
continue-after-pos+val?))))
(sequence->list (permutations-with-repetitions/proc 2 '(1 2 3)))</langsyntaxhighlight>
{{out}}
<pre>'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3))</pre>
Line 2,059 ⟶ 2,317:
===As a sequence with for clause support===
Now we define a more general version that can be used efficiently in as a for clause. In other uses it falls back to the sequence implementation.
<langsyntaxhighlight Racketlang="racket">(require (for-syntax racket))
(define-sequence-syntax in-permutations-with-repetitions
Line 2,095 ⟶ 2,353:
(for/list ([element (in-permutations-with-repetitions 2 '(1 2 3))])
element)
(sequence->list (in-permutations-with-repetitions 2 '(1 2 3)))</langsyntaxhighlight>
{{out}}
<pre>'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3))
Line 2,107 ⟶ 2,365:
 
{{works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>my @k = <a b c>;
 
.say for @k X @k;</langsyntaxhighlight>
 
For arbitrary <math>n</math>:
 
{{works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>my @k = <a b c>;
my $n = 2;
 
.say for [X] @k xx $n;</langsyntaxhighlight>
 
{{out}}
Line 2,133 ⟶ 2,391:
 
{{works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>my @k = <a b c>;
my $n = 2;
 
say @k[.polymod: +@k xx $n-1] for ^@k**$n</langsyntaxhighlight>
 
{{out}}
Line 2,151 ⟶ 2,409:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX pgm generates/displays all permutations of N different objects taken M at a time.*/
parse arg things bunch inbetweenChars names
/* ╔════════════════════════════════════════════════════════════════╗ */
Line 2,182 ⟶ 2,440:
@.?= $.q; call .permSet ?+1
end /*q*/
return /*this is meant to be an anonymous sub.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs of: &nbsp; &nbsp; <tt> 3 &nbsp; 2 </tt>}}
<pre>
Line 2,215 ⟶ 2,473:
<br>&nbsp;&nbsp;Say 'too large for this Rexx version'
<br>Also note that the output isn't the same as REXX version 1 when the 1st argument is two digits or more, i.e.: &nbsp; '''11 &nbsp; 2'''
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Arguments and output as in REXX version 1 (for the samples shown there)
* For other elements (such as 11 2), please specify a separator
Line 2,250 ⟶ 2,508:
a=a||'Say' p 'permutations'
/* Say a */
Interpret a</langsyntaxhighlight>
 
===version 3===
Line 2,258 ⟶ 2,516:
 
This version could easily be extended to '''N''' up to 15 &nbsp; (using hexadecimal arithmetic).
<langsyntaxhighlight lang="rexx">/*REXX pgm gens all permutations with repeats of N objects (<10) taken M at a time. */
parse arg N M .
z= N**M
Line 2,267 ⟶ 2,525:
t= t+1
say j
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text= &nbsp; when using the following inputs: &nbsp; &nbsp; <tt> 3 &nbsp; 2 </tt>}}
<pre>
Line 2,282 ⟶ 2,540:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Permutations with repetitions
Line 2,297 ⟶ 2,555:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,323 ⟶ 2,581:
=={{header|Ruby}}==
This is built in (Array#repeated_permutation):
<langsyntaxhighlight lang="ruby">rp = [1,2,3].repeated_permutation(2) # an enumerator (generator)
p rp.to_a #=>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
 
#yield permutations until their sum happens to exceed 4, then quit:
p rp.take_while{|(a, b)| a + b < 5} #=>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2]]</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
struct PermutationIterator<'a, T: 'a> {
universe: &'a [T],
Line 2,396 ⟶ 2,654:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,410 ⟶ 2,668:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">package permutationsRep
 
object PermutationsRepTest extends Application {
Line 2,426 ⟶ 2,684:
}
println(permutationsWithRepetitions(List(1, 2, 3), 2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,433 ⟶ 2,691:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var k = %w(a b c)
var n = 2
 
cartesian([k] * n, {|*a| say a.join(' ') })</langsyntaxhighlight>
{{out}}
<pre>
Line 2,449 ⟶ 2,707:
c c
</pre>
 
=={{header|Standard ML}}==
{{trans|Erlang}}
<syntaxhighlight lang="sml">
fun multiperms [] _ = [[]]
| multiperms _ 0 = [[]]
| multiperms xs n =
let
val rest = multiperms xs (n-1)
in
List.concat (List.map (fn a => (List.map (fn b => a::b) rest)) xs)
end
</syntaxhighlight>
 
=={{header|Tcl}}==
===Iterative version===
{{trans|PHP}}
<langsyntaxhighlight lang="tcl">
proc permutate {values size offset} {
set count [llength $values]
Line 2,476 ⟶ 2,747:
# Usage
permutations [list 1 2 3 4] 3
</syntaxhighlight>
</lang>
 
===Version without additional libraries===
{{works with|Tcl|8.6}}
{{trans|Scala}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# Utility function to make procedures that define generators
Line 2,510 ⟶ 2,781:
# Demonstrate usage
set g [permutationsWithRepetitions {1 2 3} 2]
while 1 {puts [$g]}</langsyntaxhighlight>
===Alternate version with extra library package===
{{tcllib|generator}}
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require generator
 
Line 2,537 ⟶ 2,808:
generator foreach val [permutationsWithRepetitions {1 2 3} 2] {
puts $val
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">var n = 3
var values = ["A", "B", "C", "D"]
var k = values.count
Line 2,570 ⟶ 2,841:
if (i == n) return // all permutations generated
}
}</langsyntaxhighlight>
 
{{out}}
<pre>
[A, A, A]
[B, A, A]
[C, A, A]
[D, A, A]
[A, B, A]
[B, B, A]
[C, B, A]
[D, B, A]
[A, C, A]
[B, C, A]
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">func Decide(PC);
\Terminate when first two characters of permutation are 'B' and 'C' respectively
int PC;
return PC(0)=^B & PC(1)=^C;
 
def N=3, K=4;
int Values, PN(N), PC(N), I, X;
[Values:= [^A, ^B, ^C, ^D];
for I:= 0 to N-1 do PN(I):= 0;
loop [for I:= 0 to N-1 do
[X:= PN(I);
PC(I):= Values(X);
];
ChOut(0, ^[); \show progress
for I:= 0 to N-1 do
[if I # 0 then Text(0, ", "); ChOut(0, PC(I))];
ChOut(0, ^]); CrLf(0);
\pass to deciding function
if Decide(PC) then return; \terminate early
I:= 0; \increment permutation number
loop [PN(I):= PN(I)+1;
if PN(I) < K then quit;
PN(I):= 0;
I:= I+1;
if I = N then return; \all permutations generated
];
];
]</syntaxhighlight>
{{out}}
<pre>
23

edits