Permutations with repetitions: Difference between revisions
Content added Content deleted
(Permutations with repetitions in BASIC256 and QBasic. And bundled BASIC languages.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 17: | Line 17: | ||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="11l">V n = 3 |
||
V values = [‘A’, ‘B’, ‘C’, ‘D’] |
V values = [‘A’, ‘B’, ‘C’, ‘D’] |
||
V k = values.len |
V k = values.len |
||
Line 39: | Line 39: | ||
i++ |
i++ |
||
I i == n |
I i == n |
||
^L.break</ |
^L.break</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 59: | Line 59: | ||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}} |
{{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''.}} |
{{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'''< |
'''File: prelude_permutations_with_repetitions.a68'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- # |
||
MODE PERMELEMLIST = FLEX[0]PERMELEM; |
MODE PERMELEMLIST = FLEX[0]PERMELEM; |
||
Line 89: | Line 89: | ||
); |
); |
||
SKIP</ |
SKIP</syntaxhighlight>'''File: test_permutations_with_repetitions.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script # |
||
# -*- coding: utf-8 -*- # |
# -*- coding: utf-8 -*- # |
||
Line 114: | Line 114: | ||
# OD #)); |
# OD #)); |
||
done: SKIP |
done: SKIP |
||
)</ |
)</syntaxhighlight>'''Output:''' |
||
<pre> |
<pre> |
||
Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; |
Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; Chris Ciaffa; |
||
Line 134: | 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. |
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})) -> |
||
-- {{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1}, |
-- {{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1}, |
||
-- {2, 1, 2}, {2, 2, 1}, {2, 2, 2}} |
-- {2, 1, 2}, {2, 2, 1}, {2, 2, 2}} |
||
Line 208: | Line 208: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="applescript">{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</syntaxhighlight> |
||
===Lazy evaluation with a generator=== |
===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: |
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" |
||
use framework "Foundation" |
use framework "Foundation" |
||
use scripting additions |
use scripting additions |
||
Line 397: | Line 397: | ||
end tell |
end tell |
||
return xs |
return xs |
||
end unfoldr</ |
end unfoldr</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Permutation 589 of 1024: CRACK |
<pre>Permutation 589 of 1024: CRACK |
||
Line 404: | Line 404: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Use the function from http://rosettacode.org/wiki/Permutations#Alternate_Version with opt=1 |
Use the function from http://rosettacode.org/wiki/Permutations#Alternate_Version with opt=1 |
||
< |
<syntaxhighlight 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 |
;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" |
; to process with a different min index, pass a delimited list, e.g. "0`n1`n2" |
||
Line 436: | Line 436: | ||
. P(n,k-1,opt,delim,str . A_LoopField . delim) |
. P(n,k-1,opt,delim,str . A_LoopField . delim) |
||
Return s |
Return s |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f PERMUTATIONS_WITH_REPETITIONS.AWK |
# syntax: GAWK -f PERMUTATIONS_WITH_REPETITIONS.AWK |
||
# converted from C |
# converted from C |
||
Line 470: | Line 470: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 481: | Line 481: | ||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
{{trans|FreeBASIC}} |
{{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"}} |
DIM list2$(1 TO 2, 1 TO 3) '= {{"1", "2", "3"}, {"1", "2", "3"}} |
||
Line 497: | Line 497: | ||
NEXT n |
NEXT n |
||
PRINT |
PRINT |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as FreeBASIC entry.</pre> |
<pre>Same as FreeBASIC entry.</pre> |
||
Line 503: | Line 503: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="basic256">arraybase 1 |
||
dim list1 = {{"a", "b", "c"}, {"a", "b", "c"}} |
dim list1 = {{"a", "b", "c"}, {"a", "b", "c"}} |
||
dim list2 = {{"1", "2", "3"}, {"1", "2", "3"}} |
dim list2 = {{"1", "2", "3"}, {"1", "2", "3"}} |
||
Line 519: | Line 519: | ||
next n |
next n |
||
print |
print |
||
end subroutine</ |
end subroutine</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as FreeBASIC entry.</pre> |
<pre>Same as FreeBASIC entry.</pre> |
||
==={{header|FreeBASIC}}=== |
==={{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"}} |
Dim As String list2(1 To 2, 1 To 3) = {{"1", "2", "3"}, {"1", "2", "3"}} |
||
Line 540: | Line 540: | ||
Print |
Print |
||
permutation(list2()) |
permutation(list2()) |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a a |
<pre>a a |
||
Line 564: | Line 564: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="d">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 597: | Line 597: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{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> |
<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++}}== |
=={{header|C++}}== |
||
<syntaxhighlight lang="d"> |
|||
<lang d> |
|||
#include <stdio.h> |
#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 677: | Line 677: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 686: | Line 686: | ||
===opApply Version=== |
===opApply Version=== |
||
{{trans|Scala}} |
{{trans|Scala}} |
||
< |
<syntaxhighlight lang="d">import std.array; |
||
struct PermutationsWithRepetitions(T) { |
struct PermutationsWithRepetitions(T) { |
||
Line 727: | Line 727: | ||
import std.stdio, std.array; |
import std.stdio, std.array; |
||
[1, 2, 3].permutationsWithRepetitions(2).array.writeln; |
[1, 2, 3].permutationsWithRepetitions(2).array.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]</pre> |
<pre>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]</pre> |
||
Line 733: | Line 733: | ||
===Generator Range Version=== |
===Generator Range Version=== |
||
{{trans|Scala}} |
{{trans|Scala}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.array, std.concurrency; |
||
Generator!(T[]) permutationsWithRepetitions(T)(T[] data, in uint n) |
Generator!(T[]) permutationsWithRepetitions(T)(T[] data, in uint n) |
||
Line 753: | Line 753: | ||
void main() { |
void main() { |
||
[1, 2, 3].permutationsWithRepetitions(2).writeln; |
[1, 2, 3].permutationsWithRepetitions(2).writeln; |
||
}</ |
}</syntaxhighlight> |
||
The output is the same. |
The output is the same. |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'sequences) ;; (indices ..) |
(lib 'sequences) ;; (indices ..) |
||
(lib 'list) ;; (list-permute ..) |
(lib 'list) ;; (list-permute ..) |
||
Line 789: | Line 789: | ||
(list-permute '(a b c d e) #(1 0 1 0 3 2 1)) |
(list-permute '(a b c d e) #(1 0 1 0 3 2 1)) |
||
→ (b a b a d c b) |
→ (b a b a d c b) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang="elixir">defmodule RC do |
||
def perm_rep(list), do: perm_rep(list, length(list)) |
def perm_rep(list), do: perm_rep(list, length(list)) |
||
Line 806: | Line 806: | ||
Enum.each(1..3, fn n -> |
Enum.each(1..3, fn n -> |
||
IO.inspect RC.perm_rep(list,n) |
IO.inspect RC.perm_rep(list,n) |
||
end)</ |
end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 819: | Line 819: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">-module(permute). |
||
-export([permute/1]). |
-export([permute/1]). |
||
Line 825: | Line 825: | ||
permute([],_) -> [[]]; |
permute([],_) -> [[]]; |
||
permute(_,0) -> [[]]; |
permute(_,0) -> [[]]; |
||
permute(L,I) -> [[X|Y] || X<-L, Y<-permute(L,I-1)].</ |
permute(L,I) -> [[X|Y] || X<-L, Y<-permute(L,I-1)].</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 868: | Line 868: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 884: | Line 884: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (replicateM) |
||
main = mapM_ print (replicateM 2 [1,2,3])</ |
main = mapM_ print (replicateM 2 [1,2,3])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 904: | Line 904: | ||
Position in the sequence is an integer from <code>i.n^k</code>, for example: |
Position in the sequence is an integer from <code>i.n^k</code>, for example: |
||
< |
<syntaxhighlight lang="j"> i.3^2 |
||
0 1 2 3 4 5 6 7 8</ |
0 1 2 3 4 5 6 7 8</syntaxhighlight> |
||
The sequence itself is expressed using <code>(k#n)#: position</code>, for example: |
The sequence itself is expressed using <code>(k#n)#: position</code>, for example: |
||
< |
<syntaxhighlight lang="j"> (2#3)#:i.3^2 |
||
0 0 |
0 0 |
||
0 1 |
0 1 |
||
Line 918: | Line 918: | ||
2 0 |
2 0 |
||
2 1 |
2 1 |
||
2 2</ |
2 2</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="j"> (2#3)#:3 4 5 |
||
1 0 |
1 0 |
||
1 1 |
1 1 |
||
1 2</ |
1 2</syntaxhighlight> |
||
We might express this as a verb |
We might express this as a verb |
||
< |
<syntaxhighlight lang="j">perm=: # #: i.@^~</syntaxhighlight> |
||
with example use: |
with example use: |
||
< |
<syntaxhighlight lang="j"> 2 perm 3 |
||
0 0 |
0 0 |
||
0 1 |
0 1 |
||
0 2 |
0 2 |
||
1 0 |
1 0 |
||
...</ |
...</syntaxhighlight> |
||
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. |
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 944: | Line 944: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|8}} |
{{works with|Java|8}} |
||
< |
<syntaxhighlight lang="java">import java.util.function.Predicate; |
||
public class PermutationsWithRepetitions { |
public class PermutationsWithRepetitions { |
||
Line 980: | Line 980: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 996: | Line 996: | ||
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. |
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="javascript">(function () { |
||
'use strict'; |
'use strict'; |
||
Line 1,057: | Line 1,057: | ||
//--> [[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]] |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="javascript">[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]</syntaxhighlight> |
||
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: |
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="javascript">(function () { |
||
'use strict'; |
'use strict'; |
||
Line 1,166: | Line 1,166: | ||
return show(range(30, 35) |
return show(range(30, 35) |
||
.map(curry(nthPermutationWithRepn)(['X', 'Y', 'Z'], 4))); |
.map(curry(nthPermutationWithRepn)(['X', 'Y', 'Z'], 4))); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,178: | Line 1,178: | ||
A (strict) analogue of the (lazy) replicateM in Haskell. |
A (strict) analogue of the (lazy) replicateM in Haskell. |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,217: | Line 1,217: | ||
); |
); |
||
// -> [[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]] |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="javascript">[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]</syntaxhighlight> |
||
Line 1,225: | Line 1,225: | ||
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: |
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: |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,355: | Line 1,355: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Generated 589 of 1024 possible permutations, |
<pre>Generated 589 of 1024 possible permutations, |
||
Line 1,369: | Line 1,369: | ||
We shall define permutations_with_replacements(n) in terms of a more general filter, combinations/0, defined as follows: |
We shall define permutations_with_replacements(n) in terms of a more general filter, combinations/0, defined as follows: |
||
< |
<syntaxhighlight lang="jq"># Input: an array, $in, of 0 or more arrays |
||
# Output: a stream of arrays, c, with c[i] drawn from $in[i]. |
# Output: a stream of arrays, c, with c[i] drawn from $in[i]. |
||
def combinations: |
def combinations: |
||
Line 1,382: | Line 1,382: | ||
# Output: a stream of arrays of length n with elements drawn from the input array. |
# Output: a stream of arrays of length n with elements drawn from the input array. |
||
def permutations_with_replacements(n): |
def permutations_with_replacements(n): |
||
. as $in | [range(0; n) | $in] | combinations;</ |
. as $in | [range(0; n) | $in] | combinations;</syntaxhighlight> |
||
'''Example 1: Enumeration''': |
'''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. |
Count the number of 4-combinations of [0,1,2] by enumerating them, i.e., without creating a data structure to store them all. |
||
< |
<syntaxhighlight lang="jq">def count(stream): reduce stream as $i (0; .+1); |
||
count([0,1,2] | permutations_with_replacements(4)) |
count([0,1,2] | permutations_with_replacements(4)) |
||
# output: 81</ |
# output: 81</syntaxhighlight> |
||
Line 1,397: | Line 1,397: | ||
Counting from 1, and terminating the generator when the item is found, what is the sequence number of ["c", "a", "b"] in the stream |
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"]? |
of 3-combinations of ["a","b","c"]? |
||
< |
<syntaxhighlight lang="jq"># Input: the item to be matched |
||
# Output: the index of the item in the stream (counting from 1); |
# Output: the index of the item in the stream (counting from 1); |
||
# emit null if the item is not found |
# emit null if the item is not found |
||
Line 1,408: | Line 1,408: | ||
["c", "a", "b"] | sequence_number( ["a","b","c"] | permutations_with_replacements(3)) |
["c", "a", "b"] | sequence_number( ["a","b","c"] | permutations_with_replacements(3)) |
||
# output: 20</ |
# output: 20</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 1,415: | Line 1,415: | ||
Implements a simil-Combinatorics.jl API. |
Implements a simil-Combinatorics.jl API. |
||
< |
<syntaxhighlight lang="julia">struct WithRepetitionsPermutations{T} |
||
a::T |
a::T |
||
t::Int |
t::Int |
||
Line 1,442: | Line 1,442: | ||
println("Permutations of [4, 5, 6] in 3:") |
println("Permutations of [4, 5, 6] in 3:") |
||
foreach(println, collect(with_repetitions_permutations([4, 5, 6], 3)))</ |
foreach(println, collect(with_repetitions_permutations([4, 5, 6], 3)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,476: | Line 1,476: | ||
=={{header|K}}== |
=={{header|K}}== |
||
enlist each from x on the left and each from x on the right where x is range 10 |
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 |
,/x/:\:x:!10 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,508: | Line 1,508: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,525: | Line 1,525: | ||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
a=("A","B","C","D") |
a=("A","B","C","D") |
||
Line 1,560: | Line 1,560: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="height:30ex;overflow:scroll"> |
<pre style="height:30ex;overflow:scroll"> |
||
Line 1,576: | Line 1,576: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Tuples[{1, 2, 3}, 2]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</pre> |
<pre>{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</pre> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">apply(cartesian_product,makelist({1,2,3}, 2));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]}</pre> |
<pre>{[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]}</pre> |
||
Line 1,587: | Line 1,587: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="nim">import strutils |
||
Line 1,620: | Line 1,620: | ||
permute("ABCD", 3)</ |
permute("ABCD", 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,638: | Line 1,638: | ||
Create a list of indices into what ever you want, one by one. |
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. |
Doing it by addig one to a number with k-positions to base n. |
||
< |
<syntaxhighlight lang="pascal">program PermuWithRep; |
||
//permutations with repetitions |
//permutations with repetitions |
||
//http://rosettacode.org/wiki/Permutations_with_repetitions |
//http://rosettacode.org/wiki/Permutations_with_repetitions |
||
Line 1,733: | Line 1,733: | ||
until Not(NextPermWithRep(p)); |
until Not(NextPermWithRep(p)); |
||
writeln('k: ',k,' n: ',n,' count ',cnt); |
writeln('k: ',k,' n: ',n,' count ',cnt); |
||
end.</ |
end.</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,756: | Line 1,756: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use Algorithm::Combinatorics qw/tuples_with_repetition/; |
||
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";</ |
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[A A] [A B] [A C] [B A] [B B] [B C] [C A] [C B] [C C]</pre> |
<pre>[A A] [A B] [A C] [B A] [B B] [B C] [C A] [C B] [C C]</pre> |
||
Solving the crack problem: |
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 $iter = tuples_with_repetition([qw/A C K R/], 5); |
||
my $tries = 0; |
my $tries = 0; |
||
Line 1,768: | Line 1,768: | ||
$tries++; |
$tries++; |
||
die "Found the combination after $tries tries!\n" if join("",@$p) eq "CRACK"; |
die "Found the combination after $tries tries!\n" if join("",@$p) eq "CRACK"; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Found the combination after 455 tries!</pre> |
<pre>Found the combination after 455 tries!</pre> |
||
Line 1,776: | Line 1,776: | ||
Asking for the 0th permutation just returns the total number of permutations (ie "").<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. |
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;">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: #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> |
||
Line 1,828: | Line 1,828: | ||
<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: #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> |
<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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,843: | Line 1,843: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
function permutate($values, $size, $offset) { |
function permutate($values, $size, $offset) { |
||
$count = count($values); |
$count = count($values); |
||
Line 1,867: | Line 1,867: | ||
echo join(',', $permutation)."\n"; |
echo join(',', $permutation)."\n"; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,882: | Line 1,882: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de permrep (N Lst) |
||
(if (=0 N) |
(if (=0 N) |
||
(cons NIL) |
(cons NIL) |
||
Line 1,888: | Line 1,888: | ||
'((X) |
'((X) |
||
(mapcar '((Y) (cons Y X)) Lst) ) |
(mapcar '((Y) (cons Y X)) Lst) ) |
||
(permrep (dec N) Lst) ) ) )</ |
(permrep (dec N) Lst) ) ) )</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
Line 1,896: | Line 1,896: | ||
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: |
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}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Permutations of n elements drawn from k values''' |
||
from itertools import product |
from itertools import product |
||
Line 1,971: | Line 1,971: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Permutations of two elements, drawn from three values: |
<pre>Permutations of two elements, drawn from three values: |
||
Line 1,981: | Line 1,981: | ||
====Applying itertools.product==== |
====Applying itertools.product==== |
||
< |
<syntaxhighlight lang="python">from itertools import product |
||
# check permutations until we find the word 'crack' |
# check permutations until we find the word 'crack' |
||
Line 1,987: | Line 1,987: | ||
w = ''.join(x) |
w = ''.join(x) |
||
print w |
print w |
||
if w.lower() == 'crack': break</ |
if w.lower() == 'crack': break</syntaxhighlight> |
||
====Writing a generator==== |
====Writing a generator==== |
||
Line 1,993: | Line 1,993: | ||
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'): |
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}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Generator-based permutations with repetition''' |
||
from itertools import (chain, repeat) |
from itertools import (chain, repeat) |
||
Line 2,150: | Line 2,150: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Search for a 5 char permutation drawn from 'ACKR' matching "crack": |
<pre>Search for a 5 char permutation drawn from 'ACKR' matching "crack": |
||
Line 2,164: | Line 2,164: | ||
Generators are not defined in Quackery, but are easy enough to create, requiring a single line of code. |
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. |
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>. |
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 ( --> )</ |
[ ' [ 0 1 ] resetgen fibonacci ] is resetfib ( --> )</syntaxhighlight> |
||
And so to the task: |
And so to the task: |
||
< |
<syntaxhighlight lang="quackery"> [ 1 & ] is odd ( n --> b ) |
||
[ ]this[ take ]'[ do ]this[ put ]done[ ] is generator ( --> ) |
[ ]this[ take ]'[ do ]this[ put ]done[ ] is generator ( --> ) |
||
Line 2,211: | Line 2,211: | ||
dup size odd if |
dup size odd if |
||
[ dup echo$ cr ] |
[ dup echo$ cr ] |
||
$ "two two two" = until ]</ |
$ "two two two" = until ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,237: | Line 2,237: | ||
===As a sequence=== |
===As a sequence=== |
||
First we define a procedure that defines the sequence of the permutations. |
First we define a procedure that defines the sequence of the permutations. |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (permutations-with-repetitions/proc size items) |
(define (permutations-with-repetitions/proc size items) |
||
(define items-vector (list->vector items)) |
(define items-vector (list->vector items)) |
||
Line 2,270: | Line 2,270: | ||
continue-after-pos+val?)))) |
continue-after-pos+val?)))) |
||
(sequence->list (permutations-with-repetitions/proc 2 '(1 2 3)))</ |
(sequence->list (permutations-with-repetitions/proc 2 '(1 2 3)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3))</pre> |
<pre>'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3))</pre> |
||
Line 2,276: | Line 2,276: | ||
===As a sequence with for clause support=== |
===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. |
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. |
||
< |
<syntaxhighlight lang="racket">(require (for-syntax racket)) |
||
(define-sequence-syntax in-permutations-with-repetitions |
(define-sequence-syntax in-permutations-with-repetitions |
||
Line 2,312: | Line 2,312: | ||
(for/list ([element (in-permutations-with-repetitions 2 '(1 2 3))]) |
(for/list ([element (in-permutations-with-repetitions 2 '(1 2 3))]) |
||
element) |
element) |
||
(sequence->list (in-permutations-with-repetitions 2 '(1 2 3)))</ |
(sequence->list (in-permutations-with-repetitions 2 '(1 2 3)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3)) |
<pre>'((1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3)) |
||
Line 2,324: | Line 2,324: | ||
{{works with|rakudo|2016.07}} |
{{works with|rakudo|2016.07}} |
||
<lang |
<syntaxhighlight lang="raku" line>my @k = <a b c>; |
||
.say for @k X @k;</ |
.say for @k X @k;</syntaxhighlight> |
||
For arbitrary <math>n</math>: |
For arbitrary <math>n</math>: |
||
{{works with|rakudo|2016.07}} |
{{works with|rakudo|2016.07}} |
||
<lang |
<syntaxhighlight lang="raku" line>my @k = <a b c>; |
||
my $n = 2; |
my $n = 2; |
||
.say for [X] @k xx $n;</ |
.say for [X] @k xx $n;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,350: | Line 2,350: | ||
{{works with|rakudo|2016.07}} |
{{works with|rakudo|2016.07}} |
||
<lang |
<syntaxhighlight lang="raku" line>my @k = <a b c>; |
||
my $n = 2; |
my $n = 2; |
||
say @k[.polymod: +@k xx $n-1] for ^@k**$n</ |
say @k[.polymod: +@k xx $n-1] for ^@k**$n</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,368: | Line 2,368: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm generates/displays all permutations of N different objects taken M at a time.*/ |
||
parse arg things bunch inbetweenChars names |
parse arg things bunch inbetweenChars names |
||
/* ╔════════════════════════════════════════════════════════════════╗ */ |
/* ╔════════════════════════════════════════════════════════════════╗ */ |
||
Line 2,399: | Line 2,399: | ||
@.?= $.q; call .permSet ?+1 |
@.?= $.q; call .permSet ?+1 |
||
end /*q*/ |
end /*q*/ |
||
return /*this is meant to be an anonymous sub.*/</ |
return /*this is meant to be an anonymous sub.*/</syntaxhighlight> |
||
{{out|output|text= when using the default inputs of: <tt> 3 2 </tt>}} |
{{out|output|text= when using the default inputs of: <tt> 3 2 </tt>}} |
||
<pre> |
<pre> |
||
Line 2,432: | Line 2,432: | ||
<br> Say 'too large for this Rexx version' |
<br> 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.: '''11 2''' |
<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.: '''11 2''' |
||
< |
<syntaxhighlight lang="rexx">/* REXX *************************************************************** |
||
* Arguments and output as in REXX version 1 (for the samples shown there) |
* Arguments and output as in REXX version 1 (for the samples shown there) |
||
* For other elements (such as 11 2), please specify a separator |
* For other elements (such as 11 2), please specify a separator |
||
Line 2,467: | Line 2,467: | ||
a=a||'Say' p 'permutations' |
a=a||'Say' p 'permutations' |
||
/* Say a */ |
/* Say a */ |
||
Interpret a</ |
Interpret a</syntaxhighlight> |
||
===version 3=== |
===version 3=== |
||
Line 2,475: | Line 2,475: | ||
This version could easily be extended to '''N''' up to 15 (using hexadecimal arithmetic). |
This version could easily be extended to '''N''' up to 15 (using hexadecimal arithmetic). |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm gens all permutations with repeats of N objects (<10) taken M at a time. */ |
||
parse arg N M . |
parse arg N M . |
||
z= N**M |
z= N**M |
||
Line 2,484: | Line 2,484: | ||
t= t+1 |
t= t+1 |
||
say j |
say j |
||
end /*j*/ /*stick a fork in it, we're all done. */</ |
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output|text= when using the following inputs: <tt> 3 2 </tt>}} |
{{out|output|text= when using the following inputs: <tt> 3 2 </tt>}} |
||
<pre> |
<pre> |
||
Line 2,499: | Line 2,499: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Permutations with repetitions |
# Project : Permutations with repetitions |
||
Line 2,514: | Line 2,514: | ||
next |
next |
||
see nl |
see nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,540: | Line 2,540: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
This is built in (Array#repeated_permutation): |
This is built in (Array#repeated_permutation): |
||
< |
<syntaxhighlight 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]] |
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: |
#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]]</ |
p rp.take_while{|(a, b)| a + b < 5} #=>[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2]]</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust"> |
||
struct PermutationIterator<'a, T: 'a> { |
struct PermutationIterator<'a, T: 'a> { |
||
universe: &'a [T], |
universe: &'a [T], |
||
Line 2,613: | Line 2,613: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,627: | Line 2,627: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">package permutationsRep |
||
object PermutationsRepTest extends Application { |
object PermutationsRepTest extends Application { |
||
Line 2,643: | Line 2,643: | ||
} |
} |
||
println(permutationsWithRepetitions(List(1, 2, 3), 2)) |
println(permutationsWithRepetitions(List(1, 2, 3), 2)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,650: | Line 2,650: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var k = %w(a b c) |
||
var n = 2 |
var n = 2 |
||
cartesian([k] * n, {|*a| say a.join(' ') })</ |
cartesian([k] * n, {|*a| say a.join(' ') })</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,670: | Line 2,670: | ||
===Iterative version=== |
===Iterative version=== |
||
{{trans|PHP}} |
{{trans|PHP}} |
||
< |
<syntaxhighlight lang="tcl"> |
||
proc permutate {values size offset} { |
proc permutate {values size offset} { |
||
set count [llength $values] |
set count [llength $values] |
||
Line 2,693: | Line 2,693: | ||
# Usage |
# Usage |
||
permutations [list 1 2 3 4] 3 |
permutations [list 1 2 3 4] 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Version without additional libraries=== |
===Version without additional libraries=== |
||
{{works with|Tcl|8.6}} |
{{works with|Tcl|8.6}} |
||
{{trans|Scala}} |
{{trans|Scala}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6 |
||
# Utility function to make procedures that define generators |
# Utility function to make procedures that define generators |
||
Line 2,727: | Line 2,727: | ||
# Demonstrate usage |
# Demonstrate usage |
||
set g [permutationsWithRepetitions {1 2 3} 2] |
set g [permutationsWithRepetitions {1 2 3} 2] |
||
while 1 {puts [$g]}</ |
while 1 {puts [$g]}</syntaxhighlight> |
||
===Alternate version with extra library package=== |
===Alternate version with extra library package=== |
||
{{tcllib|generator}} |
{{tcllib|generator}} |
||
{{works with|Tcl|8.6}} |
{{works with|Tcl|8.6}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6 |
||
package require generator |
package require generator |
||
Line 2,754: | Line 2,754: | ||
generator foreach val [permutationsWithRepetitions {1 2 3} 2] { |
generator foreach val [permutationsWithRepetitions {1 2 3} 2] { |
||
puts $val |
puts $val |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="ecmascript">var n = 3 |
||
var values = ["A", "B", "C", "D"] |
var values = ["A", "B", "C", "D"] |
||
var k = values.count |
var k = values.count |
||
Line 2,787: | Line 2,787: | ||
if (i == n) return // all permutations generated |
if (i == n) return // all permutations generated |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |