Permutations with repetitions: Difference between revisions

Add SML
(Add SML)
(27 intermediate revisions by 15 users not shown)
Line 13:
{{Template:Combinations and permutations}}
<br>
 
=={{header|11l}}==
{{trans|Kotlin}}
 
<syntaxhighlight lang="11l">V n = 3
V values = [‘A’, ‘B’, ‘C’, ‘D’]
V k = values.len
V decide = pc -> pc[0] == ‘B’ & pc[1] == ‘C’
V pn = [0] * n
V pc = ["\0"] * n
L
L(x) pn
pc[L.index] = values[x]
print(pc)
 
I decide(pc)
L.break
 
V i = 0
L
pn[i]++
I pn[i] < k
L.break
pn[i] = 0
i++
I i == n
^L.break</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|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - one minor extension to language used - PRAGMA READ, similar to C's #include directive.}}
{{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'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
MODE PERMELEMLIST = FLEX[0]PERMELEM;
MODE PERMELEMLISTYIELD = PROC(PERMELEMLIST)VOID;
 
PROC perm gen elemlist = (FLEX[]PERMELEMLIST master, PERMELEMLISTYIELD yield)VOID:(
[LWB master:UPB master]INT counter;
[LWB master:UPB master]PERMELEM out;
FOR i FROM LWB counter TO UPB counter DO
INT c = counter[i] := LWB master[i];
out[i] := master[i][c]
OD;
yield(out);
WHILE TRUE DO
INT next i := LWB counter;
counter[next i] +:= 1;
FOR i FROM LWB counter TO UPB counter WHILE counter[i]>UPB master[i] DO
INT c = counter[i] := LWB master[i];
out[i] := master[i][c];
next i := i + 1;
IF next i > UPB counter THEN done FI;
counter[next i] +:= 1
OD;
INT c = counter[next i];
out[next i] := master[next i][c];
yield(out)
OD;
done: SKIP
);
 
SKIP</syntaxhighlight>'''File: test_permutations_with_repetitions.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
MODE PERMELEM = STRING;
PR READ "prelude_permutations_with_repetitions.a68" PR;
 
INT lead actor = 1, co star = 2;
PERMELEMLIST actors list = ("Chris Ciaffa", "Keith Urban","Tom Cruise",
"Katie Holmes","Mimi Rogers","Nicole Kidman");
 
FLEX[0]PERMELEMLIST combination := (actors list, actors list, actors list, actors list);
 
FORMAT partner fmt = $g"; "$;
test:(
# FOR PERMELEMELEM candidate in # perm gen elemlist(combination #) DO (#,
## (PERMELEMLIST candidate)VOID: (
printf((partner fmt,candidate));
IF candidate[lead actor] = "Keith Urban" AND candidate[co star]="Nicole Kidman" OR
candidate[co star] = "Keith Urban" AND candidate[lead actor]="Nicole Kidman" THEN
print((" => Sunday + Faith as extras", new line)); # children #
done
FI;
print(new line)
# OD #));
done: SKIP
)</syntaxhighlight>'''Output:'''
<pre>
Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Keith Urban; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Tom Cruise; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Katie Holmes; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Mimi Rogers; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Nicole Kidman; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Chris Ciaffa; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Keith Urban; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Tom Cruise; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Katie Holmes; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Mimi Rogers; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Nicole Kidman; Keith Urban; Chris Ciaffa; Chris Ciaffa; => Sunday + Faith as extras
</pre>
 
=={{header|AppleScript}}==
===Strict evaluation of the whole set===
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.
 
<syntaxhighlight lang="applescript">-- e.g. replicateM(3, {1, 2})) ->
<lang AppleScript>-- PERMUTATIONS WITH REPETITION ----------------------------------------------
-- {{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1},
-- {2, 1, 2}, {2, 2, 1}, {2, 2, 2}}
 
-- permutationsWithRepetitionreplicateM :: Int -> [a] -> [[a]]
on permutationsWithRepetitionreplicateM(n, xs)
script go
if length of xs > 0 then
script cons
foldl1(curry(my cartesianProduct)'s |λ|(xs), replicate(n, xs))
on |λ|(a, bs)
else
{a} & bs
end if|λ|
end script
end permutationsWithRepetition
on |λ|(x)
if x ≤ 0 then
{{}}
else
liftA2List(cons, xs, |λ|(x - 1))
end if
end |λ|
end script
go's |λ|(n)
end replicateM
 
 
-- TEST ----------------------------------------------------------------------
on run
permutationsWithRepetitionreplicateM(2, {1, 2, 3})
--> {{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}
end run
 
 
-- GENERIC FUNCTIONS ---------------------------------------------------------
 
-- cartesianProductconcatMap :: [(a] -> [b]) -> [[a,] -> [b]]
on cartesianProductconcatMap(xsf, ysxs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & |λ|(item i of xs, i, xs)
end repeat
end tell
return acc
end concatMap
 
-- liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]
on liftA2List(f, xs, ys)
script
property g : mReturn(f)'s |λ|
on |λ|(x)
script
on |λ|(y)
{{g(x} &, y)}
end |λ|
end script
concatMap(result, ys)
end |λ|
end script
concatMap(result, xs)
end liftA2List
end cartesianProduct
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
script append
on |λ|(a, b)
a & b
end |λ|
end script
foldl(append, {}, map(f, xs))
end concatMap
 
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
on |λ|(b)
|λ|(a, b) of mReturn(f)
end |λ|
end script
end |λ|
end script
end curry
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
-- foldl1 :: (a -> a -> a) -> [a] -> a
on foldl1(f, xs)
if length of xs > 0 then
foldl(f, item 1 of xs, tail(xs))
else
{}
end if
end foldl1
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: HandlerFirst-class m => (a -> b) -> m (a -> Scriptb)
on mReturn(f)
if class of f is script then
Line 125 ⟶ 208:
end script
end if
end mReturn</syntaxhighlight>
 
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
-- tail :: [a] -> [a]
on tail(xs)
if length of xs > 1 then
items 2 thru -1 of xs
else
{}
end if
end tail</lang>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</langsyntaxhighlight>
 
===PartialLazy 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:
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
<lang AppleScript>-- Nth PERMUTATION WITH REPETITION -------------------------------------------
use framework "Foundation"
use scripting additions
 
-- permutesWithRepns :: [a] -> Int -> Generator [[a]]
on permutesWithRepns(xs, n)
script
property f : curry3(my nthPermutationWithRepn)'s |λ|(xs)'s |λ|(n)
property limit : (length of xs) ^ n
property i : -1
on |λ|()
set i to 1 + i
if i < limit then
return f's |λ|(i)
else
missing value
end if
end |λ|
end script
end permutesWithRepns
 
 
-- nthPermutationWithRepn :: [a] -> Int -> Int -> [a]
on nthPermutationWithRepn(xs, groupSizeintGroup, iIndexintIndex)
set intBase to length of xs
setif intSetSizeintIndex to< (intBase ^ groupSizeintGroup) then
set ds to baseDigits(intBase, xs, intIndex)
if intBase < 1 or iIndex > intSetSize then
{}
else
set baseElems to inBaseElements(xs, iIndex)
set intZeros to groupSize - (length of baseElems)
if-- intZerosWith >any 0'leading thenzeros' required by length
replicate(intGroup - (length of replicate(intZerosds), item 1 of xs) & baseElemsds
else
missing baseElemsvalue
end if
end if
end nthPermutationWithRepn
 
 
-- inBaseElements :: [a] -> Int -> [String]
-- baseDigits :: Int -> [a] -> [a]
on inBaseElements(xs, n)
on set baseDigits(intBase, to length ofdigits, xsn)
script
script nextDigit on |λ|(v)
on |λ|(residue) if 0 = v then
set {divided, remainder} to quotRemNothing(residue, intBase)
else
{valid:divided > 0, value: Just(Tuple(item (remainder1 + 1(v mod intBase)) of xs)digits, new:divided}¬
v div intBase))
end if
end |λ|
end script
unfoldr(result, n)
end baseDigits
reverse of unfoldr(nextDigit, n)
end inBaseElements
 
 
-- TEST ----------------------------------------------------------------------
on run
set cs to "ACKR"
script
set wordLength to on |λ|(x)5
set gen to permutesWithRepns(cs, wordLength)
nthPermutationWithRepn({"X", "Y", "Z"}, 4, x)
end |λ|
end script
--set 30thi to 35th members of the series0
set v to gen's |λ|() -- First permutation drawn from series
map(result, enumFromTo(30, 35))
set alpha to v
set psi to alpha
repeat while missing value is not v
set s to concat(v)
if "crack" = toLower(s) then
return ("Permutation " & (i as text) & " of " & ¬
(((length of cs) ^ wordLength) as integer) as text) & ¬
": " & s & linefeed & ¬
"Found after searching from " & alpha & " thru " & psi
else
set i to 1 + i
set psi to v
end if
set v to gen's |λ|()
end repeat
end run
 
 
-- GENERIC FUNCTIONS ----------------------------------------------------------
 
-- enumFromToJust :: Inta -> IntMaybe -> [Int]a
on enumFromToJust(m, nx)
{type:"Maybe", Nothing:false, Just:x}
if m > n then
end Just
set d to -1
 
-- Nothing :: Maybe a
on Nothing()
{type:"Maybe", Nothing:true}
end Nothing
 
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
 
-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
set lng to length of xs
if 0 < lng and string is class of (item 1 of xs) then
set acc to ""
else
set dacc to 1{}
end if
setrepeat lstwith i from 1 to {}lng
repeat with i from mset acc to nacc & item i byof dxs
set end of lst to i
end repeat
return lstacc
end enumFromToconcat
 
-- mapcurry3 :: ((a, b, c) -> bd) -> [a] -> [b] -> c -> d
on mapcurry3(f, xs)
tell mReturn(f)script
seton lng to length of xs|λ|(a)
set lst to {} script
repeat with i from 1 to lng on |λ|(b)
set end of lst to |λ|(item i of xs, i, xs)script
end repeat on |λ|(c)
|λ|(a, b, c) of mReturn(f)
return lst
end tell|λ|
end script
end map
end |λ|
end script
end |λ|
end script
end curry3
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: HandlerFirst-class m => (a -> b) -> m (a -> Scriptb)
on mReturn(f)
if class of f is script then
Line 244 ⟶ 354:
end mReturn
 
-- Egyptian multiplication - progressively doubling a list, appending
-- quotRem :: Integral a => a -> a -> (a, a)
-- stages of doubling to an accumulator where needed for binary
on quotRem(m, n)
-- assembly of a target length
{m div n, m mod n}
end quotRem
 
-- replicate :: Int -> a -> [a]
on replicate(n, a)
Line 263 ⟶ 371:
end replicate
 
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower
 
-- > unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
-- > [10,9,8,7,6,5,4,3,2,1]
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
set mfxr to mReturnTuple(fv, v) -- (value, remainder)
set lstxs to {}
set recM to mf's |λ|(v)
repeat while (valid of recM) is true
set end of lst to value of recM
set recM to mf's |λ|(new of recM)
end repeat
lst & value of recM
end unfoldr
 
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
set v to x
tell mReturn(f)
repeat until-- mp'sFunction |λ|(v)applied to remainder.
set vmb to |λ|(v|2| of xr)
if Nothing of mb then
exit repeat
else -- New (value, remainder) tuple,
set xr to Just of mb
-- and value appended to output list.
set end of xs to |1| of xr
end if
end repeat
end tell
return vxs
end |until|unfoldr</langsyntaxhighlight>
{{Out}}
<pre>Permutation 589 of 1024: CRACK
<lang AppleScript>{{"Y", "X", "Y", "X"}, {"Y", "X", "Y", "Y"}, {"Y", "X", "Y", "Z"},
Found after searching from AAAAA thru ARACK</pre>
{"Y", "X", "Z", "X"}, {"Y", "X", "Z", "Y"}, {"Y", "X", "Z", "Z"}}</lang>
 
=={{header|ALGOL 68Arturo}}==
<syntaxhighlight lang="arturo">decide: function [pc]->
{{works with|ALGOL 68|Revision 1 - one minor extension to language used - PRAGMA READ, similar to C's #include directive.}}
and? pc\0 = `B`
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}}
pc\1 = `C`
{{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'''<lang algol68># -*- coding: utf-8 -*- #
 
permutation: function [vals, n][
MODE PERMELEMLIST = FLEX[0]PERMELEM;
k: size vals
MODE PERMELEMLISTYIELD = PROC(PERMELEMLIST)VOID;
pn: array.of:n 0
p: array.of:n `0`
 
while [true][
PROC perm gen elemlist = (FLEX[]PERMELEMLIST master, PERMELEMLISTYIELD yield)VOID:(
loop.with:'i pn 'x -> p\[i]: vals\[x]
[LWB master:UPB master]INT counter;
print p
[LWB master:UPB master]PERMELEM out;
if decide p -> return ø
FOR i FROM LWB counter TO UPB counter DO
INT c = counter[ i] := LWB master[i];0
out[i] := master while [itrue][c]
pn\[i]: pn\[i] + 1
OD;
if pn\[i] < k -> break
yield(out);
pn\[i]: 0
WHILE TRUE DO
INT next i i:= LWBi + counter;1
counter[next if i] +:= 1;n -> return ø
]
FOR i FROM LWB counter TO UPB counter WHILE counter[i]>UPB master[i] DO
]
INT c = counter[i] := LWB master[i];
]
out[i] := master[i][c];
next i := i + 1;
IF next i > UPB counter THEN done FI;
counter[next i] +:= 1
OD;
INT c = counter[next i];
out[next i] := master[next i][c];
yield(out)
OD;
done: SKIP
);
 
permutation "ABCD" 3</syntaxhighlight>
SKIP</lang>'''File: test_permutations_with_repetitions.a68'''<lang algol68>#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
{{out}}
MODE PERMELEM = STRING;
PR READ "prelude_permutations_with_repetitions.a68" PR;
 
<pre>A A A
INT lead actor = 1, co star = 2;
B A A
PERMELEMLIST actors list = ("Chris Ciaffa", "Keith Urban","Tom Cruise",
C A A
"Katie Holmes","Mimi Rogers","Nicole Kidman");
D A A
 
A B A
FLEX[0]PERMELEMLIST combination := (actors list, actors list, actors list, actors list);
B B A
 
C B A
FORMAT partner fmt = $g"; "$;
D B A
test:(
A C A
# FOR PERMELEMELEM candidate in # perm gen elemlist(combination #) DO (#,
B C A</pre>
## (PERMELEMLIST candidate)VOID: (
printf((partner fmt,candidate));
IF candidate[lead actor] = "Keith Urban" AND candidate[co star]="Nicole Kidman" OR
candidate[co star] = "Keith Urban" AND candidate[lead actor]="Nicole Kidman" THEN
print((" => Sunday + Faith as extras", new line)); # children #
done
FI;
print(new line)
# OD #));
done: SKIP
)</lang>'''Output:'''
<pre>
Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Keith Urban; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Tom Cruise; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Katie Holmes; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Mimi Rogers; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Nicole Kidman; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa;
Chris Ciaffa; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Keith Urban; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Tom Cruise; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Katie Holmes; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Mimi Rogers; Keith Urban; Chris Ciaffa; Chris Ciaffa;
Nicole Kidman; Keith Urban; Chris Ciaffa; Chris Ciaffa; => Sunday + Faith as extras
</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 400 ⟶ 476:
. P(n,k-1,opt,delim,str . A_LoopField . delim)
Return s
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f PERMUTATIONS_WITH_REPETITIONS.AWK
# converted from C
BEGIN {
numbers = 3
upto = 4
for (tmp2=1; tmp2<=numbers; tmp2++) {
arr[tmp2] = 1
}
arr[numbers] = 0
tmp1 = numbers
while (1) {
if (arr[tmp1] == upto) {
if (--tmp1 == 0) {
break
}
}
else {
arr[tmp1]++
while (tmp1 < numbers) {
arr[++tmp1] = 1
}
printf("(")
for (tmp2=1; tmp2<=numbers; tmp2++) {
printf("%d",arr[tmp2])
}
printf(")")
}
}
printf("\n")
exit(0)
}
</syntaxhighlight>
{{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 409 ⟶ 611:
int temp;
int numbers=3;
int a[numbers+1], upto = 4, temp2;
for( temp2 = 1 ; temp2 <= numbers; temp2++){
a[temp2]=1;
}
a[numbers]=0;
temp=numbers, temp2;
while(1){
if(a[temp]==upto){
Line 436 ⟶ 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">
#include <stdio.h>
#include <stdlib.h>
 
struct Generator
{
public:
Generator(int s, int v)
: cSlots(s)
, cValues(v)
{
a = new int[s];
 
for (int i = 0; i < cSlots - 1; i++) {
a[i] = 1;
}
a[cSlots - 1] = 0;
 
nextInd = cSlots;
}
 
~Generator()
{
delete a;
}
 
bool doNext()
{
for (;;)
{
if (a[nextInd - 1] == cValues) {
nextInd--;
if (nextInd == 0)
return false;
}
else {
a[nextInd - 1]++;
while (nextInd < cSlots) {
nextInd++;
a[nextInd - 1] = 1;
}
 
return true;
}
}
}
 
void doPrint()
{
printf("(");
for (int i = 0; i < cSlots; i++) {
printf("%d", a[i]);
}
printf(")");
}
 
private:
int *a;
int cSlots;
int cValues;
int nextInd;
};
 
 
int main()
{
Generator g(3, 4);
 
while (g.doNext()) {
g.doPrint();
}
 
return 0;
}
 
</syntaxhighlight>
{{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|D}}==
===opApply Version===
{{trans|Scala}}
<langsyntaxhighlight lang="d">import std.array;
 
struct PermutationsWithRepetitions(T) {
Line 484 ⟶ 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 490 ⟶ 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 510 ⟶ 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 546 ⟶ 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 563 ⟶ 847:
Enum.each(1..3, fn n ->
IO.inspect RC.perm_rep(list,n)
end)</langsyntaxhighlight>
 
{{out}}
Line 576 ⟶ 860:
 
=={{header|Erlang}}==
<langsyntaxhighlight Erlanglang="erlang">-module(permute).
-export([permute/1]).
 
Line 582 ⟶ 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 625 ⟶ 909:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 641 ⟶ 925:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
 
main = mapM_ print (replicateM 2 [1,2,3])</langsyntaxhighlight>
{{out}}
<pre>
Line 661 ⟶ 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 675 ⟶ 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 701 ⟶ 985:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.function.Predicate;
 
public class PermutationsWithRepetitions {
Line 737 ⟶ 1,021:
}
}
}</langsyntaxhighlight>
 
Output:
Line 753 ⟶ 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 814 ⟶ 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 923 ⟶ 1,207:
return show(range(30, 35)
.map(curry(nthPermutationWithRepn)(['X', 'Y', 'Z'], 4)));
})();</langsyntaxhighlight>
 
{{Out}}
Line 935 ⟶ 1,219:
A (strict) analogue of the (lazy) replicateM in Haskell.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 974 ⟶ 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 982 ⟶ 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,112 ⟶ 1,396:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Generated 589 of 1024 possible permutations,
Line 1,126 ⟶ 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,139 ⟶ 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,154 ⟶ 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,165 ⟶ 1,449:
["c", "a", "b"] | sequence_number( ["a","b","c"] | permutations_with_replacements(3))
 
# output: 20</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,172 ⟶ 1,456:
Implements a simil-Combinatorics.jl API.
 
<langsyntaxhighlight lang="julia">struct WithRepetitionsPermutations{T}
a::T
t::Int
Line 1,199 ⟶ 1,483:
 
println("Permutations of [4, 5, 6] in 3:")
foreach(println, collect(with_repetitions_permutations([4, 5, 6], 3)))</langsyntaxhighlight>
 
{{out}}
Line 1,230 ⟶ 1,514:
[5, 6, 6]
[6, 6, 6]</pre>
 
=={{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,264 ⟶ 1,549:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,281 ⟶ 1,566:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
a=("A","B","C","D")
Line 1,316 ⟶ 1,601:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,331 ⟶ 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|PerlMaxima}}==
<syntaxhighlight lang="maxima">apply(cartesian_product,makelist({1,2,3}, 2));</syntaxhighlight>
<lang perl>use Algorithm::Combinatorics qw/tuples_with_repetition/;
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";</lang>
{{out}}
<pre>{[A A1,1] ,[A B1,2] ,[A C1,3] ,[B A2,1] ,[B B2,2] ,[B C2,3] ,[C A3,1] ,[C B3,2] ,[C C3,3]}</pre>
 
=={{header|Nim}}==
Solving the crack problem:
{{trans|Go}}
<lang perl>use Algorithm::Combinatorics qw/tuples_with_repetition/;
<syntaxhighlight lang="nim">import strutils
my $iter = tuples_with_repetition([qw/A C K R/], 5);
my $tries = 0;
while (my $p = $iter->next) {
$tries++;
die "Found the combination after $tries tries!\n" if join("",@$p) eq "CRACK";
}</lang>
{{out}}
<pre>Found the combination after 455 tries!</pre>
 
=={{header|Perl 6}}==
 
func decide(pc: openArray[char]): bool =
We can use the <tt>X</tt> operator ("cartesian product") to cross the list with itself.<br>
## Terminate when first two characters of the
For <math>n=2</math>:
## permutation are 'B' and 'C' respectively.
pc[0] == 'B' and pc[1] == 'C'
 
{{works with|rakudo|2016.07}}
<lang perl6>my @k = <a b c>;
 
proc permute(values: openArray[char]; n: Positive) =
.say for @k X @k;</lang>
 
let k = values.len
For arbitrary <math>n</math>:
var
pn = newSeq[int](n)
p = newSeq[char](n)
 
while true:
{{works with|rakudo|2016.07}}
# Generate permutation
<lang perl6>my @k = <a b c>;
for i, x in pn: p[i] = values[x]
my $n = 2;
# 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.
 
 
.say for [X] @k xx $n;</lang>
permute("ABCD", 3)</syntaxhighlight>
 
{{out}}
<pre>aA aA A
B A A
a b
C A A
a c
D A A
b a
A B A
b b
B B A
b c
C B A
c a
D B A
c b
A C A
c c</pre>
B C A</pre>
 
Here is an other approach, counting all <math>k^n</math> possibilities in base <math>k</math>:
 
{{works with|rakudo|2016.07}}
<lang perl6>my @k = <a b c>;
my $n = 2;
 
say @k[.polymod: +@k xx $n-1] for ^@k**$n</lang>
 
{{out}}
<pre>a a
b a
c a
a b
b b
c b
a c
b c
c c</pre>
=={{header|Pascal}}==
{{works with|Free Pascal}}
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,499 ⟶ 1,774:
until Not(NextPermWithRep(p));
writeln('k: ',k,' n: ',n,' count ',cnt);
end.</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,520 ⟶ 1,795:
//"old" compiler-version
//real 0m3.465s /fpc/2.6.4/ppc386 "%f" -al -Xs -XX -O3</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use Algorithm::Combinatorics qw/tuples_with_repetition/;
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";</syntaxhighlight>
{{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:
<syntaxhighlight lang="perl">use Algorithm::Combinatorics qw/tuples_with_repetition/;
my $iter = tuples_with_repetition([qw/A C K R/], 5);
my $tries = 0;
while (my $p = $iter->next) {
$tries++;
die "Found the combination after $tries tries!\n" if join("",@$p) eq "CRACK";
}</syntaxhighlight>
{{out}}
<pre>Found the combination after 455 tries!</pre>
 
=={{header|Phix}}==
The task is equivalent to simply counting in base=length(set), from 1 to power(base,n).<br>
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)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
<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>
<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: #000080;font-style:italic;">-- return the number of permutations</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">nperm</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000080;font-style:italic;">-- return the idx'th [1-based] permutation</span>
<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>
<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>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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>
<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: #000080;font-style:italic;">-- Some slightly excessive testing:</span>
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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: #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>
<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>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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","...","31","32","33"}
Len 3 perms[1..27] of "123" : {"111","112","113","...","331","332","333"}
Len 3 perms[1..27] of "456" : {"444","445","446","...","664","665","666"}
Len 3 perms[1..27] of {1,2,3} : {{1,1,1},{1,1,2},{1,1,3},"...",{3,3,1},{3,3,2},{3,3,3}}
Len 2 perms[1..9] of {"bat","fox","cow"} : {{"bat","bat"},{"bat","fox"},{"bat","cow"},"...",{"cow","bat"},{"cow","fox"},{"cow","cow"}}
Len 4 perms[31..36/81] of "XYZ" : {"YXYX","YXYY","YXYZ","YXZX","YXZY","YXZZ"}
Len 5 perm 455/1024 of "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,546 ⟶ 1,908:
echo join(',', $permutation)."\n";
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,561 ⟶ 1,923:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de permrep (N Lst)
(if (=0 N)
(cons NIL)
Line 1,567 ⟶ 1,929:
'((X)
(mapcar '((Y) (cons Y X)) Lst) )
(permrep (dec N) Lst) ) ) )</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,574 ⟶ 1,936:
 
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}}
<syntaxhighlight lang="python">'''Permutations of n elements drawn from k values'''
 
<lang python>from functoolsitertools import (reduce)product
 
 
# replicateM :: Applicative m => Int -> m a -> m [a]
def replicateM(n):
'''A functor collecting values accumulated by
n repetitions of m. (List instance only here).
'''
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
 
 
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Permutations of two elements, drawn from three values'''
print(
replicateMfTable(2)([1,main.__doc__ 2,+ 3]':\n')(repr)(showList)(
 
replicateM(2)
 
)([[1, 2, 3], 'abc'])
)
 
 
# GENERIC FUNCTIONS ---------------------------------------
 
# replicateM :: Int -> [a] -> [[a]]
def replicateM(n):
def loop(f):
def go(x):
return [[]] if 0 >= x else (
liftA2List(lambda a, b: [a] + b)(f)(go(x - 1))
)
return go(n)
return lambda f: loop(f)
 
 
# liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]
def liftA2List(f):
'''The binary operator f lifted to a function over two
return lambda xs: lambda ys: concatMap(
lists. f applied to each pair of arguments in the
lambda x: concatMap(lambda y: [f(x, y)])(ys)
cartesian product of xs and ys.
)(xs)
'''
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
 
 
# DISPLAY -------------------------------------------------
 
# concatMapfTable :: (aString -> [b])(a -> [a]String) -> [b]
# (b -> String) -> (a -> b) -> [a] -> String
def concatMap(f):
def fTable(s):
return lambda xs: (
'''Heading -> x display function -> fx display function ->
reduce(lambda a, b: a + b, map(f, xs), [])
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
 
 
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
 
 
# MAIN ---
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
<pre>Permutations of two elements, drawn from three values:
<pre>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]</pre>
 
[1, 2, 3] -> [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
'abc' -> [['a','a'],['a','b'],['a','c'],['b','a'],['b','b'],['b','c'],['c','a'],['c','b'],['c','c']]</pre>
 
===Lazy evaluation with a generator===
====Applying itertools.product====
 
<langsyntaxhighlight lang="python">from itertools import product
 
# check permutations until we find the word 'crack'
Line 1,626 ⟶ 2,028:
w = ''.join(x)
print w
if w.lower() == 'crack': break</langsyntaxhighlight>
 
====Writing a generator====
 
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}}
<lang Python>from functools import (reduce)
<syntaxhighlight lang="python">'''Generator-based permutations with repetition'''
from itertools import (repeat)
 
from itertools import (chain, repeat)
 
# main :: IO ()
def main():
cs = 'ACKR'
wordLength = 5
gen = permutesWithRepns(cs)(wordLength)
for idx, xs in enumerate(gen):
s = ''.join(xs)
if 'crack' == s.lower():
break
print (
'Permutation ' + str(idx) + ' of ' +
str(len(cs)**wordLength) + ':', s
)
 
 
# permutesWithRepnspermsWithRepns :: [a] -> Int -> Generator [[a]]
def permutesWithRepnspermsWithRepns(xs):
'''Generator of permutations of length n, with
elements drawn from the values in xs.
'''
def groupsOfSize(n):
f = nthPermWithRepn(xs)(n)
limit = len(xs)**n
i = 0
while (i < limit):
yield f(i)
i = 1 + i
Line 1,669 ⟶ 2,061:
# nthPermWithRepn :: [a] -> Int -> Int -> [a]
def nthPermWithRepn(xs):
'''Indexed permutation of n values drawn from xs'''
def go(intGroup, index):
vs = list(xs)
Line 1,674 ⟶ 2,067:
intSet = intBase ** intGroup
return (
lambda ds=unfoldr(lambda v: (
(lambda qr=divmod(v,: intBase):(
Just((vs[ lambda qr[1]]=divmod(v, qr[0]))intBase): Just()
) if 0 < v else Nothing (qr[0], vs[qr[1]])
)
)() if 0 < v else Nothing()
)(index): (
list(repeat(vs[0], intGroup - len(ds))) + ds
Line 1,687 ⟶ 2,082:
 
 
# GENERIC FUNCTIONSMAIN ----------------------------------------------------
# main :: IO ()
def main():
'''Search for a 5 char permutation drawn from 'ACKR' matching "crack"'''
 
cs = 'ACKR'
wordLength = 5
target = 'crack'
 
gen = permsWithRepns(cs)(wordLength)
mb = Nothing()
for idx, xs in enumerate(gen):
s = ''.join(xs)
if target == s.lower():
mb = Just((s, idx))
break
 
print(main.__doc__ + ':\n')
print(
maybe('No match found for "{k}"'.format(k=target))(
lambda m: 'Permutation {idx} of {total}: {pm}'.format(
idx=m[1], total=len(cs)**wordLength, pm=s
)
)(mb)
)
 
 
# GENERIC FUNCTIONS -------------------------------------
 
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe(option type) value.'''
return {type: 'Maybe', 'Nothing': False, 'Just': x}
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
 
 
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe(option type) value.'''
return {type: 'Maybe', 'Nothing': True}
return {'type': 'Maybe', 'Nothing': True}
 
 
# concat :: [[a]] -> [a]
# concat :: [String] -> String
def concat(xs):
'''The concatenation of all the elements
in a list or iterable.'''
 
def f(ys):
zs = list(chain(*ys))
return ''.join(zs) if isinstance(ys[0], str) else zs
 
return (
reducef(xs) if isinstance(xs, list) else (
lambda a, b: a + b, chain.from_iterable(xs,)
'' if type(xs[0]) is str else []
) if xs else []
 
 
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
 
 
# maybe :: b -> (a -> b) -> Maybe a -> b
def maybe(v):
'''Either the default value v, if m is Nothing,
or the application of f to x,
where m is Just(x).
'''
return lambda f: lambda m: v if None is m or m.get('Nothing') else (
f(m.get('Just'))
)
 
 
# snd :: (a, b) -> b
# unfoldr(lambda x: Just((x, x - 1)) if 0 != x else Nothing(), 10)]
def snd(tpl):
# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
'''Second member of a pair.'''
return tpl[1]
 
 
# unfoldr(lambda x: Just((x, x - 1)) if 0 != x else Nothing())(10)
# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
'''Dual to reduce or foldr.
Where catamorphism reduces a list to a summary value,
the anamorphic unfoldr builds a list from a seed value.
As long as f returns Just(a, b), a is prepended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns Nothing, the completed list is returned.
'''
def go(v):
xr = (v, v)
xs = []
while True:
mb = f(xr[10])
if mb.get('Nothing'):
return xs
else:
xr = mb.get('Just')
xs.append(xr[01])
return xs
return lambda vx: go(vx)
 
 
# MAIN ---
main()</lang>
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>Search for a 5 char permutation drawn from 'ACKR' matching "crack":
<pre>Permutation 589 of 1024: CRACK</pre>
 
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 1,770 ⟶ 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 1,776 ⟶ 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 1,812 ⟶ 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))
'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3))</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
We can use the <tt>X</tt> operator ("cartesian product") to cross the list with itself.<br>
For <math>n=2</math>:
 
{{works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" line>my @k = <a b c>;
 
.say for @k X @k;</syntaxhighlight>
 
For arbitrary <math>n</math>:
 
{{works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" line>my @k = <a b c>;
my $n = 2;
 
.say for [X] @k xx $n;</syntaxhighlight>
 
{{out}}
<pre>a a
a b
a c
b a
b b
b c
c a
c b
c c</pre>
 
Here is an other approach, counting all <math>k^n</math> possibilities in base <math>k</math>:
 
{{works with|rakudo|2016.07}}
<syntaxhighlight lang="raku" line>my @k = <a b c>;
my $n = 2;
 
say @k[.polymod: +@k xx $n-1] for ^@k**$n</syntaxhighlight>
 
{{out}}
<pre>a a
b a
c a
a b
b b
c b
a c
b c
c c</pre>
 
=={{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 1,850 ⟶ 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 1,883 ⟶ 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 1,918 ⟶ 2,508:
a=a||'Say' p 'permutations'
/* Say a */
Interpret a</langsyntaxhighlight>
 
===version 3===
Line 1,926 ⟶ 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 1,935 ⟶ 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 1,950 ⟶ 2,540:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Permutations with repetitions
Line 1,965 ⟶ 2,555:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,991 ⟶ 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}}==
<syntaxhighlight lang="rust">
struct PermutationIterator<'a, T: 'a> {
universe: &'a [T],
size: usize,
prev: Option<Vec<usize>>,
}
 
fn permutations<T>(universe: &[T], size: usize) -> PermutationIterator<T> {
PermutationIterator {
universe,
size,
prev: None,
}
}
 
fn map<T>(values: &[T], ixs: &[usize]) -> Vec<T>
where
T: Clone,
{
ixs.iter().map(|&i| values[i].clone()).collect()
}
 
impl<'a, T> Iterator for PermutationIterator<'a, T>
where
T: Clone,
{
type Item = Vec<T>;
 
fn next(&mut self) -> Option<Vec<T>> {
let n = self.universe.len();
 
if n == 0 {
return None;
}
 
match self.prev {
None => {
let zeroes: Vec<usize> = std::iter::repeat(0).take(self.size).collect();
let result = Some(map(self.universe, &zeroes[..]));
self.prev = Some(zeroes);
result
}
Some(ref mut indexes) => match indexes.iter().position(|&i| i + 1 < n) {
None => None,
Some(position) => {
for index in indexes.iter_mut().take(position) {
*index = 0;
}
indexes[position] += 1;
Some(map(self.universe, &indexes[..]))
}
},
}
}
}
 
fn main() {
let universe = ["Annie", "Barbie"];
for p in permutations(&universe[..], 3) {
for element in &p {
print!("{} ", element);
}
println!();
}
}
 
</syntaxhighlight>
{{out}}
<pre>
Annie Annie Annie
Barbie Annie Annie
Annie Barbie Annie
Barbie Barbie Annie
Annie Annie Barbie
Barbie Annie Barbie
Annie Barbie Barbie
Barbie Barbie Barbie
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">package permutationsRep
 
object PermutationsRepTest extends Application {
Line 2,014 ⟶ 2,684:
}
println(permutationsWithRepetitions(List(1, 2, 3), 2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,021 ⟶ 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,037 ⟶ 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,064 ⟶ 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,098 ⟶ 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,125 ⟶ 2,808:
generator foreach val [permutationsWithRepetitions {1 2 3} 2] {
puts $val
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">var n = 3
var values = ["A", "B", "C", "D"]
var k = values.count
 
// terminate when first two characters of the permutation are 'B' and 'C' respectively
var decide = Fn.new { |pc| pc[0] == "B" && pc[1] == "C" }
 
var pn = List.filled(n, 0)
var pc = List.filled(n, null)
while (true) {
// generate permutation
var i = 0
for (x in pn) {
pc[i] = values[x]
i = i + 1
}
// show progress
System.print(pc)
// pass to deciding function
if (decide.call(pc)) return // terminate early
// increment permutation number
i = 0
while (true) {
pn[i] = pn[i] + 1
if (pn[i] < k) break
pn[i] = 0
i = i + 1
if (i == n) return // all permutations generated
}
}</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|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>
[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>
23

edits