Combinations with repetitions: Difference between revisions

→‎Concise recursive: Changed to Wren S/H
(→‎Concise recursive: Changed to Wren S/H)
 
(15 intermediate revisions by 10 users not shown)
Line 28:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F combsReps(lst, k)
T Ty = T(lst[0])
I k == 0
Line 37:
 
print(combsReps([‘iced’, ‘jam’, ‘plain’], 2))
print(combsReps(Array(1..10), 3).len)</langsyntaxhighlight>
 
{{out}}
Line 46:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Combinations with repetitions - 16/04/2019
COMBREP CSECT
USING COMBREP,R13 base register
Line 144:
XDEC DS CL12 temp for xdeco
REGEQU
END COMBREP </langsyntaxhighlight>
{{out}}
<pre>
Line 156:
cwr( 3, 2)= 6
cwr(10, 3)= 220
</pre>
 
=={{header|Acornsoft Lisp}}==
{{trans|Scheme}}
 
<syntaxhighlight lang="lisp">
(defun samples (k items)
(cond
((zerop k) '(()))
((null items) '())
(t (append
(mapc '(lambda (c) (cons (car items) c))
(samples (sub1 k) items))
(samples k (cdr items))))))
 
(defun append (a b)
(cond ((null a) b)
(t (cons (car a) (append (cdr a) b)))))
 
(defun length (list (len . 0))
(map '(lambda (e) (setq len (add1 len)))
list)
len)
</syntaxhighlight>
 
{{Out}}
 
<pre>
Evaluate : (samples 2 '(iced jam plain))
 
Value is : ((iced iced) (iced jam) (iced plain) (jam jam)
(jam plain) (plain plain))
 
Evaluate : (length (samples 3 '(1 2 3 4 5 6 7 8 9 10)))
 
Value is : 220
</pre>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintComb(BYTE ARRAY c BYTE len)
BYTE i,ind
 
Line 242 ⟶ 278:
Comb(3,2,1)
Comb(10,3,0)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Combinations_with_repetitions.png Screenshot from Atari 8-bit computer]
Line 263 ⟶ 299:
 
combinations.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Combinations is
 
Line 326 ⟶ 362:
Ada.Text_IO.Put_Line ("Total Donuts:" & Natural'Image (Donut_Count));
Ada.Text_IO.Put_Line ("Total Tens:" & Natural'Image (Ten_Count));
end Combinations;</langsyntaxhighlight>
 
{{out}}
Line 341 ⟶ 377:
{{Trans|Haskell}}
{{Trans|Python}}
<langsyntaxhighlight lang="applescript">--------------- COMBINATIONS WITH REPETITION -------------
 
-- combinationsWithRepetition :: Int -> [a] -> [kTuple a]
Line 549 ⟶ 585:
missing value
end if
end take</langsyntaxhighlight>
{{Out}}
<pre>{220, {{"iced", "iced"}, {"jam", "iced"}, {"jam", "jam"}, {"plain", "iced"}, {"plain", "jam"}, {"plain", "plain"}}}</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">print combine.repeated.by:2 ["iced" "jam" "plain"]
 
print combine.count.repeated.by:3 @1..10</syntaxhighlight>
 
{{out}}
 
<pre>[iced iced] [iced jam] [iced plain] [jam jam] [jam plain] [plain plain]
220</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">;===========================================================
; based on "https://www.geeksforgeeks.org/combinations-with-repetitions/"
;===========================================================
Line 571 ⟶ 617:
while (i <= arr.count())
chosen[Index]:=i, CombinationRepetitionUtil(arr, k, Delim, chosen, result, index+1, i++)
} ;===========================================================</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">result := CombinationRepetition(["iced","jam","plain"], 2, " + ")
for k, v in result
res .= v "`n"
res := trim(res, ",") "`n"
MsgBox % result.count() " Combinations with Repetition found:`n" res
MsgBox % CombinationRepetition([0,1,2,3,4,5,6,7,8,9], 3).Count()</langsyntaxhighlight>
Outputs:<pre>---------------------------
6 Combinations with Repetition found:
Line 591 ⟶ 637:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f COMBINATIONS_WITH_REPETITIONS.AWK
BEGIN {
Line 615 ⟶ 661:
exit(0)
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 627 ⟶ 673:
</pre>
 
=={{header|BASIC}}==
 
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">arraybase 0
print "Enter n comb m. "
input integer "n: ", n
Line 652 ⟶ 698:
next i
return
end subroutine</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM list$(2), chosen%(2)
list$() = "iced", "jam", "plain"
PRINT "Choices of 2 from 3:"
Line 682 ⟶ 728:
c% += FNchoose(n% + 1, l%, i%, m%, g%(), n$())
NEXT
= c%</langsyntaxhighlight>
{{out}}
<pre>
Line 697 ⟶ 743:
Total choices = 220
</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Combinat.bas"
110 READ N
120 STRING D$(1 TO N)*5
130 FOR I=1 TO N
140 READ D$(I)
150 NEXT
160 FOR I=1 TO N
170 FOR J=I TO N
180 PRINT D$(I);" ";D$(J)
190 NEXT
200 NEXT
210 DATA 3,iced,jam,plain</syntaxhighlight>
 
=={{header|Bracmat}}==
This minimalist solution expresses the answer as a sum of products. Bracmat automatically normalises such expressions: terms and factors are sorted alphabetically, products containing a sum as a factor are decomposed in a sum of factors (unless the product is not itself term in a multiterm expression). Like factors are converted to a single factor with an appropriate exponent, so <code>ice^2</code> is to be understood as ice twice.
<langsyntaxhighlight lang="bracmat">( ( choices
= n things thing result
. !arg:(?n.?things)
Line 718 ⟶ 778:
& out$(choices$(2.iced jam plain))
& out$(choices$(3.iced jam plain butter marmite tahin fish salad onion grass):?+[?N&!N)
);</langsyntaxhighlight>
{{out}}
<pre>iced^2+jam^2+plain^2+iced*jam+iced*plain+jam*plain
Line 725 ⟶ 785:
=={{header|C}}==
Non recursive solution
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
 
Line 760 ⟶ 820:
return 0;
}
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
const char * donuts[] = { "iced", "jam", "plain", "something completely different" };
Line 794 ⟶ 854:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}<pre>iced iced
iced jam
Line 807 ⟶ 867:
{{trans|PHP}}
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 866 ⟶ 926:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 879 ⟶ 939:
 
Recursive version
<langsyntaxhighlight lang="csharp">
using System;
class MultiCombination
Line 903 ⟶ 963:
}
 
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
 
Non recursive version.
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <string>
Line 945 ⟶ 1,005:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 960 ⟶ 1,020:
{{trans|Scheme}}
 
<langsyntaxhighlight lang="clojure">
(defn combinations [coll k]
(when-let [[x & xs] coll]
Line 967 ⟶ 1,027:
(concat (map (partial cons x) (combinations coll (dec k)))
(combinations xs k)))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 976 ⟶ 1,036:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
combos = (arr, k) ->
return [ [] ] if k == 0
Line 989 ⟶ 1,049:
console.log combos arr, 2
console.log "#{combos([1..10], 3).length} ways to order 3 donuts given 10 types"
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,005 ⟶ 1,065:
=={{header|Common Lisp}}==
The code below is a modified version of the Clojure solution.
<langsyntaxhighlight lang="lisp">(defun combinations (xs k)
(let ((x (car xs)))
(cond
Line 1,013 ⟶ 1,073:
(combinations xs (1- k)))
(combinations (cdr xs) k))))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,021 ⟶ 1,081:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">possible_doughnuts = ["iced", "jam", "plain"].repeated_combinations(2)
puts "There are #{possible_doughnuts.size} possible doughnuts:"
possible_doughnuts.each{|doughnut_combi| puts doughnut_combi.join(" and ")}
Line 1,028 ⟶ 1,088:
possible_doughnuts = (1..10).to_a.repeated_combinations(3)
# size returns the size of the enumerator, or nil if it can’t be calculated lazily.
puts "", "#{possible_doughnuts.size} ways to order 3 donuts given 10 types."</langsyntaxhighlight>
{{out}}
<pre>
Line 1,044 ⟶ 1,104:
=={{header|D}}==
Using [http://www.graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation lexicographic next bit permutation] to generate combinations with repetitions.
<langsyntaxhighlight lang="d">import std.stdio, std.range;
 
const struct CombRep {
Line 1,132 ⟶ 1,192:
writeln("Ways to select 3 from 10 types is ",
CombRep(10, 3).length);
}</langsyntaxhighlight>
{{out}}
<pre> iced iced
Line 1,143 ⟶ 1,203:
 
===Short Recursive Version===
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm;
 
T[][] combsRep(T)(T[] lst, in int k) {
Line 1,158 ⟶ 1,218:
["iced", "jam", "plain"].combsRep(2).writeln;
10.iota.array.combsRep(3).length.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[["iced", "iced"], ["iced", "jam"], ["iced", "plain"], ["jam", "jam"], ["jam", "plain"], ["plain", "plain"]]
Line 1,165 ⟶ 1,225:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>items$[] = [ "iced" "jam" "plain" ]
items$[] = [ "iced" "jam" "plain" ]
n = len items$[]
k = 2
Line 1,171 ⟶ 1,232:
n_results = 0
#
funcproc output . .
n_results += 1
if len items$[] > 0
for r ins$ result[]= ""
writefor items$[r]i &= "1 "to k
s$ &= items$[result[i]] & " "
.
print "" .
print s$
.
.
.
funcproc combine pos val . .
if pos => k
call output
else
for i = val to n - 1
result[pos] = i
call combine pos + 1 i
.
.
.
call combine 01 01
#
n = 10
Line 1,197 ⟶ 1,259:
items$[] = [ ]
n_results = 0
call combine 01 01
print ""
print n_results & " results with 10 donuts"</lang>
</syntaxhighlight>
 
{{out}}
Line 1,215 ⟶ 1,278:
=={{header|EchoLisp}}==
We can use the native '''combinations/rep''' function, or use a '''combinator''' iterator, or implement the function.
<langsyntaxhighlight lang="scheme">
;;
;; native function : combinations/rep in list.lib
Line 1,258 ⟶ 1,321:
→ 220
 
</syntaxhighlight>
</lang>
 
=={{header|Egison}}==
 
<langsyntaxhighlight lang="egison">
(define $comb/rep
(lambda [$n $xs]
Line 1,269 ⟶ 1,332:
 
(test (comb/rep 2 {"iced" "jam" "plain"}))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,277 ⟶ 1,340:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def comb_rep(0, _), do: [[]]
def comb_rep(_, []), do: []
Line 1,288 ⟶ 1,351:
Enum.each(RC.comb_rep(2, s), fn x -> IO.inspect x end)
 
IO.puts "\nExtra credit: #{length(RC.comb_rep(3, Enum.to_list(1..10)))}"</langsyntaxhighlight>
 
{{out}}
Line 1,303 ⟶ 1,366:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(comb).
-compile(export_all).
Line 1,313 ⟶ 1,376:
comb_rep(N,[H|T]=S) ->
[[H|L] || L <- comb_rep(N-1,S)]++comb_rep(N,T).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,325 ⟶ 1,388:
95> length(comb:comb_rep(3,lists:seq(1,10))).
220
</pre>
 
=={{header|Factor}}==
See the implementation of <code>all-combinations-with-replacement</code> [https://docs.factorcode.org/content/word-all-combinations-with-replacement,math.combinatorics.html here].
{{works with|Factor|0.99 2022-04-03}}
<syntaxhighlight lang=factor>USING: math.combinatorics prettyprint qw ;
 
qw{ iced jam plain } 2 all-combinations-with-replacement .</syntaxhighlight>
{{out}}
<pre>
{
{ "iced" "iced" }
{ "iced" "jam" }
{ "iced" "plain" }
{ "jam" "jam" }
{ "jam" "plain" }
{ "plain" "plain" }
}
</pre>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
program main
integer :: chosen(4)
Line 1,382 ⟶ 1,463:
 
end program main
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,396 ⟶ 1,477:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">sub iterate( byval curr as string, byval start as uinteger,_
byval stp as uinteger, byval depth as uinteger,_
names() as string )
Line 1,418 ⟶ 1,499:
input names(i)
next i
iterate outstr, 0, m-1, n-1, names()</langsyntaxhighlight>
{{out}}<pre>
Enter n comb m. 2,3
Line 1,436 ⟶ 1,517:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
UnorderedTuples(["iced", "jam", "plain"], 2);</langsyntaxhighlight>
 
=={{header|Go}}==
===Concise recursive===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,463 ⟶ 1,544:
fmt.Println(len(combrep(3,
[]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"})))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,472 ⟶ 1,553:
===Channel===
Using channel and goroutine, showing how to use synced or unsynced communication.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,529 ⟶ 1,610:
}
fmt.Printf("\npicking 3 of 10: %d\n", count)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,543 ⟶ 1,624:
===Multiset===
This version has proper representation of sets and multisets.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,644 ⟶ 1,725:
}
fmt.Println(len(combrep(3, ten)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,657 ⟶ 1,738:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">-- Return the combinations, with replacement, of k items from the
-- list. We ignore the case where k is greater than the length of
-- the list.
Line 1,680 ⟶ 1,761:
main = do
print $ combsWithRep 2 ["iced", "jam", "plain"]
print $ countCombsWithRep 3 [1 .. 10]</langsyntaxhighlight>
{{out}}
<pre>[["iced","iced"],["iced","jam"],["iced","plain"],["jam","jam"],["jam","plain"],["plain","plain"]]
Line 1,689 ⟶ 1,770:
The first solution is inefficient because it repeatedly calculates the same subproblem in different branches of recursion. For example, <code>combsWithRep k (x:xs)</code> involves computing <code>combsWithRep (k-1) (x:xs)</code> and <code>combsWithRep k xs</code>, both of which (separately) compute <code>combsWithRep (k-1) xs</code>. To avoid repeated computation, we can use dynamic programming:
 
<langsyntaxhighlight lang="haskell">combsWithRep :: Int -> [a] -> [[a]]
combsWithRep k xs = combsBySize xs !! k
where
Line 1,696 ⟶ 1,777:
 
main :: IO ()
main = print $ combsWithRep 2 ["iced", "jam", "plain"]</langsyntaxhighlight>
 
and another approach, using manual recursion:
<langsyntaxhighlight lang="haskell">--------------- COMBINATIONS WITH REPETITION -------------
 
combinationsWithRepetition ::
Line 1,724 ⟶ 1,805:
2
["iced", "jam", "plain"]
print $ length $ combinationsWithRepetition 3 [0 .. 9]</langsyntaxhighlight>
{{Out}}
<pre>[["iced","iced"],["jam","iced"],["plain","iced"],["jam","jam"],["plain","jam"],["plain","plain"]]
Line 1,732 ⟶ 1,813:
 
Following procedure is a generator, which generates each combination of length n in turn:
<syntaxhighlight lang="icon">
<lang Icon>
# generate all combinations of length n from list L,
# including repetitions
Line 1,750 ⟶ 1,831:
}
end
</syntaxhighlight>
</lang>
 
Test procedure:
 
<syntaxhighlight lang="icon">
<lang Icon>
# convenience function
procedure write_list (l)
Line 1,771 ⟶ 1,852:
write ("There are " || count || " possible combinations of 3 from 10")
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,783 ⟶ 1,864:
There are 220 possible combinations of 3 from 10
</pre>
 
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "Combinat.bas"
110 READ N
120 STRING D$(1 TO N)*5
130 FOR I=1 TO N
140 READ D$(I)
150 NEXT
160 FOR I=1 TO N
170 FOR J=I TO N
180 PRINT D$(I);" ";D$(J)
190 NEXT
200 NEXT
210 DATA 3,iced,jam,plain</lang>
 
=={{header|J}}==
Cartesian product, the monadic j verb { solves the problem. The rest of the code handles the various data types, order, and quantity to choose, and makes a set from the result.
 
<langsyntaxhighlight lang="j">rcomb=: >@~.@:(/:~&.>)@,@{@# <</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> 2 rcomb ;:'iced jam plain'
┌─────┬─────┐
│iced │iced │
Line 1,820 ⟶ 1,887:
└─────┴─────┘
#3 rcomb i.10 NB. # ways to choose 3 items from 10 with repetitions
220</langsyntaxhighlight>
 
===J Alternate implementation===
Line 1,826 ⟶ 1,893:
Considerably faster:
 
<langsyntaxhighlight lang="j">require 'stats'
rcomb=: (combrep #) { ]</syntaxhighlight>
combr=: i.@[ -"1~ [ comb + - 1:
rcomb=: (combr #) { ]</lang>
 
This definition of <code>rcomb</code> functionsbehaves identically to the previous one, and <code>combrcombrep</code> calculates indices:
 
<langsyntaxhighlight lang="j"> 2 combrcombrep 3
0 0
0 1
Line 1,838 ⟶ 1,904:
1 1
1 2
2 2</langsyntaxhighlight>
 
In other words: we<code>combrep</code> computecomputes <code>2 comb 4 </code> (note that 4 = (2 + 3)-1) and then subtractsubtracts from each column the minimum value in each column (<code>i. 2</code>).
 
=={{header|Java}}==
'''MultiCombinationsTester.java'''
<langsyntaxhighlight lang="java">
import com.objectwave.utility.*;
 
Line 1,871 ⟶ 1,937:
}
} // class
</syntaxhighlight>
</lang>
 
'''MultiCombinations.java'''
<langsyntaxhighlight lang="java">
import com.objectwave.utility.*;
import java.util.*;
Line 1,923 ⟶ 1,989:
}
} // class
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,940 ⟶ 2,006:
===ES5===
====Imperative====
<langsyntaxhighlight lang="javascript"><html><head><title>Donuts</title></head>
<body><pre id='x'></pre><script type="application/javascript">
function disp(x) {
Line 1,963 ⟶ 2,029:
disp(pick(2, [], 0, ["iced", "jam", "plain"], true) + " combos");
disp("pick 3 out of 10: " + pick(3, [], 0, "a123456789".split(''), false) + " combos");
</script></body></html></langsyntaxhighlight>
{{out}}
<pre>iced iced
Line 1,975 ⟶ 2,041:
 
====Functional====
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// n -> [a] -> [[a]]
Line 2,019 ⟶ 2,085:
];
 
})();</langsyntaxhighlight>
 
{{Out}}
 
<syntaxhighlight lang="javascript">[
<lang JavaScript>[
[["iced", "iced"], ["iced", "jam"], ["iced", "plain"],
["jam", "jam"], ["jam", "plain"], ["plain", "plain"]],
220
]</langsyntaxhighlight>
 
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,092 ⟶ 2,158:
threeFromTen: length(combsWithRep(3, enumFromTo(0, 9)))
});
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 2,125 ⟶ 2,191:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def pick(n):
def pick(n; m): # pick n, from m onwards
if n == 0 then []
Line 2,132 ⟶ 2,198:
else ([.[m]] + pick(n-1; m)), pick(n; m+1)
end;
pick(n;0) ;</langsyntaxhighlight>
'''The task''':
<langsyntaxhighlight lang="jq"> "Pick 2:",
(["iced", "jam", "plain"] | pick(2)),
([[range(0;10)] | pick(3)] | length) as $n
| "There are \($n) ways to pick 3 objects with replacement from 10."
</syntaxhighlight>
</lang>
{{Out}}
<pre>$ jq -n -r -c -f pick.jq
Line 2,153 ⟶ 2,219:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using Combinatorics
 
l = ["iced", "jam", "plain"]
Line 2,161 ⟶ 2,227:
end
 
@show length(with_replacement_combinations(1:10, 3))</langsyntaxhighlight>
 
{{out}}
Line 2,175 ⟶ 2,241:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
class CombsWithReps<T>(val m: Int, val n: Int, val items: List<T>, val countOnly: Boolean = false) {
Line 2,211 ⟶ 2,277:
val generic10 = "0123456789".chunked(1)
CombsWithReps(3, 10, generic10, true)
}</langsyntaxhighlight>
 
{{out}}
Line 2,233 ⟶ 2,299:
===With List Comprehension===
 
<langsyntaxhighlight lang="lisp">
(defun combinations
(('() _)
Line 2,243 ⟶ 2,309:
(cons head subcoll))
(combinations tail n))))
</syntaxhighlight>
</lang>
===With Map===
 
<langsyntaxhighlight lang="lisp">
(defun combinations
(('() _)
Line 2,256 ⟶ 2,322:
(combinations coll (- n 1)))
(combinations tail n))))
</syntaxhighlight>
</lang>
 
Output is the same for both:
 
<langsyntaxhighlight lang="lisp">
> (combinations '(iced jam plain) 2)
((iced iced) (iced jam) (iced plain) (jam jam) (jam plain) (plain plain))
</syntaxhighlight>
</lang>
 
=={{header|Lobster}}==
{{trans|C}}
<langsyntaxhighlight Lobsterlang="lobster">import std
 
// set S of length n, choose k
Line 2,291 ⟶ 2,357:
print count
let extra = choose(map(10):_, 3): _
print extra</langsyntaxhighlight>
{{out}}
<pre>["iced", "iced"]
Line 2,304 ⟶ 2,370:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function GenerateCombinations(tList, nMaxElements, tOutput, nStartIndex, nChosen, tCurrentCombination)
if not nStartIndex then
nStartIndex = 1
Line 2,350 ⟶ 2,416:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">with(combinat):
chooserep:=(s,k)->choose([seq(op(s),i=1..k)],k):
chooserep({iced,jam,plain},2);
Line 2,359 ⟶ 2,425:
numbchooserep:=(s,k)->binomial(nops(s)+k-1,k);
numbchooserep({iced,jam,plain},2);
# 6</langsyntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
This method will only work for small set and sample sizes (as it generates all Tuples then filters duplicates - Length[Tuples[Range[10],10]] is already bigger than Mathematica can handle).
<langsyntaxhighlight Mathematicalang="mathematica">DeleteDuplicates[Tuples[{"iced", "jam", "plain"}, 2],Sort[#1] == Sort[#2] &]
->{{"iced", "iced"}, {"iced", "jam"}, {"iced", "plain"}, {"jam", "jam"}, {"jam", "plain"}, {"plain", "plain"}}
 
Line 2,371 ⟶ 2,437:
Combi[10, 3]
->220
</syntaxhighlight>
</lang>
 
 
A better method therefore:
<langsyntaxhighlight Mathematicalang="mathematica">CombinWithRep[S_List, k_] := Module[{occupation, assignment},
occupation =
Flatten[Permutations /@
Line 2,389 ⟶ 2,455:
Out[2]= {{"iced", "iced"}, {"jam", "jam"}, {"plain",
"plain"}, {"iced", "jam"}, {"iced", "plain"}, {"jam", "plain"}}
</syntaxhighlight>
</lang>
 
Which can handle the Length[S] = 10, k=10 situation in still only seconds.
Line 2,398 ⟶ 2,464:
comb.count_choices shows off solutions.aggregate (which allows you to fold over solutions as they're found) rather than list.length and the factorial function.
 
<langsyntaxhighlight Mercurylang="mercury">:- module comb.
:- interface.
:- import_module list, int, bag.
Line 2,429 ⟶ 2,495:
 
:- pred count(T::in, int::in, int::out) is det.
count(_, N0, N) :- N0 + 1 = N.</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight Mercurylang="mercury">:- module comb_ex.
:- interface.
:- import_module io.
Line 2,450 ⟶ 2,516:
mystery, cubed, cream_covered, explosive], 3, N),
io.write(L, !IO), io.nl(!IO),
io.write_string(from_int(N) ++ " choices.\n", !IO).</langsyntaxhighlight>
 
{{out}}
Line 2,458 ⟶ 2,524:
=={{header|Nim}}==
{{trans|D}}
<langsyntaxhighlight lang="nim">import sugar, sequtils
 
proc combsReps[T](lst: seq[T], k: int): seq[seq[T]] =
Line 2,470 ⟶ 2,536:
 
echo(@["iced", "jam", "plain"].combsReps(2))
echo toSeq(1..10).combsReps(3).len</langsyntaxhighlight>
{{out}}
<pre>@[@[iced, iced], @[iced, jam], @[iced, plain], @[jam, jam], @[jam, plain], @[plain, plain]]
Line 2,478 ⟶ 2,544:
{{trans|Haskell}}
 
<langsyntaxhighlight lang="ocaml">let rec combs_with_rep k xxs =
match k, xxs with
| 0, _ -> [[]]
Line 2,484 ⟶ 2,550:
| k, x::xs ->
List.map (fun ys -> x::ys) (combs_with_rep (k-1) xxs)
@ combs_with_rep k xs</langsyntaxhighlight>
 
in the interactive loop:
Line 2,500 ⟶ 2,566:
===Dynamic programming===
 
<langsyntaxhighlight lang="ocaml">let combs_with_rep m xs =
let arr = Array.make (m+1) [] in
arr.(0) <- [[]];
Line 2,508 ⟶ 2,574:
done
) xs;
arr.(m)</langsyntaxhighlight>
 
in the interactive loop:
Line 2,523 ⟶ 2,589:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">ways(k,v,s=[])={
if(k==0,return([]));
if(k==1,return(vector(#v,i,concat(s,[v[i]]))));
Line 2,531 ⟶ 2,597:
};
xc(k,v)=binomial(#v+k-1,k);
ways(2, ["iced","jam","plain"])</langsyntaxhighlight>
 
=={{header|Pascal}}==
used in [[Munchausen_numbers]] or [[Own_digits_power_sum]]
<langsyntaxhighlight lang="pascal">program CombWithRep;
//combinations with repetitions
//Limit = count of elements
Line 2,628 ⟶ 2,694:
readln;
{$ENDIF}
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,648 ⟶ 2,714:
=={{header|Perl}}==
The highly readable version:
<langsyntaxhighlight lang="perl">sub p { $_[0] ? map p($_[0] - 1, [@{$_[1]}, $_[$_]], @_[$_ .. $#_]), 2 .. $#_ : $_[1] }
sub f { $_[0] ? $_[0] * f($_[0] - 1) : 1 }
sub pn{ f($_[0] + $_[1] - 1) / f($_[0]) / f($_[1] - 1) }
Line 2,657 ⟶ 2,723:
 
printf "\nThere are %d ways to pick 7 out of 10\n", pn(7,10);
</syntaxhighlight>
</lang>
 
Prints:
Line 2,670 ⟶ 2,736:
 
With a module:
<langsyntaxhighlight lang="perl">use Algorithm::Combinatorics qw/combinations_with_repetition/;
my $iter = combinations_with_repetition([qw/iced jam plain/], 2);
while (my $p = $iter->next) {
Line 2,677 ⟶ 2,743:
# Not an efficient way: generates them all in an array!
my $count =()= combinations_with_repetition([1..10],7);
print "There are $count ways to pick 7 out of 10\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_choices</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;">at</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">={})</span>
Line 2,693 ⟶ 2,759:
<span style="color: #000000;">show_choices</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"iced"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"jam"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"plain"</span><span style="color: #0000FF;">},</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,705 ⟶ 2,771:
The second part suggests enough differences (collecting and showing vs only counting) to strike me as ugly and confusing.
While I could easily, say, translate the C version, I'd rather forego the extra credit and use a completely different routine:
<!--<langsyntaxhighlight Phixlang="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;">count_choices</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">set_size</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">at</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">taken</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
Line 2,718 ⟶ 2,784:
<span style="color: #0000FF;">?</span><span style="color: #000000;">count_choices</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
220
</pre>
As of 1.0.2 there is a builtin combinations_with_repetitions() function. Using a string here for simplicity and neater output, but it works with any sequence:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">combinations_with_repetitions</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ijp"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #008000;">','</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">combinations_with_repetitions</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">),</span><span style="color: #000000;">3</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
"ii,ij,ip,jj,jp,pp"
220
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
function combos($arr, $k) {
if ($k == 0) {
Line 2,756 ⟶ 2,832:
$num_donut_combos = count(combos($donuts, 3));
echo "$num_donut_combos ways to order 3 donuts given 10 types";
?></langsyntaxhighlight>
{{out}} in the browser:
<pre>
Line 2,771 ⟶ 2,847:
You must set k n variables and fill arrays b and c.
 
<syntaxhighlight lang="php">
<lang PHP>
<?php
//Author Ivan Gavryushin @dcc0
Line 2,833 ⟶ 2,909:
 
?>
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de combrep (N Lst)
(cond
((=0 N) '(NIL))
Line 2,845 ⟶ 2,921:
'((X) (cons (car Lst) X))
(combrep (dec N) Lst) )
(combrep N (cdr Lst)) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (combrep 2 '(iced jam plain))
Line 2,854 ⟶ 2,930:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
combinations_of_length(_,[]).
combinations_of_length([X|T],[X|Combinations]):-
Line 2,860 ⟶ 2,936:
combinations_of_length([_|T],[X|Combinations]):-
combinations_of_length(T,[X|Combinations]).
</syntaxhighlight>
</lang>
<pre>
?- [user].
Line 2,897 ⟶ 2,973:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure nextCombination(Array combIndex(1), elementCount)
;combIndex() must be dimensioned to 'k' - 1, elementCount equals 'n' - 1
;combination produced includes repetition of elements and is represented by the array combIndex()
Line 2,965 ⟶ 3,041:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf </langsyntaxhighlight>The nextCombination() procedure operates on an array of indexes to produce the next combination. This generalization allows producing a combination from any collection of elements. nextCombination() returns the value #False when the indexes have reach their maximum values and are then reset.
 
{{out}}
Line 2,982 ⟶ 3,058:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> from itertools import combinations_with_replacement
>>> n, k = 'iced jam plain'.split(), 2
>>> list(combinations_with_replacement(n,k))
Line 2,989 ⟶ 3,065:
>>> len(list(combinations_with_replacement(range(10), 3)))
220
>>> </langsyntaxhighlight>
 
'''References:'''
Line 2,999 ⟶ 3,075:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Combinations with repetitions'''
 
from itertools import (accumulate, chain, islice, repeat)
Line 3,062 ⟶ 3,138:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[('iced', 'iced'), ('jam', 'iced'), ('jam', 'jam'), ('plain', 'iced'), ('plain', 'jam'), ('plain', 'plain')]
Line 3,074 ⟶ 3,150:
 
 
<langsyntaxhighlight Quackerylang="quackery">( nextplain generates the next plaindrome in the
current base by adding one to a given plaindrome,
then replacing each trailing zero with the least
Line 3,151 ⟶ 3,227:
[ echo$ sp ] cr ]
cr
3 10 kcombnums size echo</langsyntaxhighlight>
 
{{out}}
Line 3,166 ⟶ 3,242:
=={{header|R}}==
The idiomatic solution is to just use a library.
<langsyntaxhighlight lang="rsplus">library(gtools)
combinations(3, 2, c("iced", "jam", "plain"), set = FALSE, repeats.allowed = TRUE)
nrow(combinations(10, 3, repeats.allowed = TRUE))</langsyntaxhighlight>
{{out}}
<pre>> combinations(3, 2, c("iced", "jam", "plain"), set = FALSE, repeats.allowed = TRUE)
Line 3,182 ⟶ 3,258:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (combinations xs k)
Line 3,190 ⟶ 3,266:
(map (λ(x) (cons (first xs) x))
(combinations xs (- k 1))))]))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 3,198 ⟶ 3,274:
 
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>my @S = <iced jam plain>;
my $k = 2;
 
.put for [X](@S xx $k).unique(as => *.sort.cache, with => &[eqv])</langsyntaxhighlight>
 
{{out}}
Line 3,216 ⟶ 3,292:
 
{{trans|Haskell}}
<syntaxhighlight lang="raku" perl6line>proto combs_with_rep (UInt, @) {*}
multi combs_with_rep (0, @) { () }
Line 3,232 ⟶ 3,308:
sub combs_with_rep_count ($k, $n) { ($n + $k - 1)! / $k! / ($n - 1)! }
say combs_with_rep_count( 3, 10 );</langsyntaxhighlight>
{{out}}
<pre>(iced iced)
Line 3,245 ⟶ 3,321:
===version 1===
This REXX version uses a type of anonymous recursion.
<langsyntaxhighlight lang="rexx">/*REXX pgm displays combination sets with repetitions for X things taken Y at a time*/
call RcombN 3, 2, 'iced jam plain' /*The 1st part of Rosetta Code task. */
call RcombN -10, 3, 'Iced jam plain' /* " 2nd " " " " " */
Line 3,264 ⟶ 3,340:
if p==z then return .(? -1); do j=? to y; @.j=p; end /*j*/; return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: L=; do c=1 for y; _=@.c; L=L $._; end /*c*/; say L; return</langsyntaxhighlight>
{{out|output}}
<pre>
Line 3,284 ⟶ 3,360:
recursive (taken from version 1)
Reformatted and variable names suitable for OoRexx.
<langsyntaxhighlight lang="rexx">/*REXX compute (and show) combination sets for nt things in ns places*/
debug=0
Call time 'R'
Line 3,349 ⟶ 3,425:
Say l
End
Return</langsyntaxhighlight>
{{out}}
<pre>----------- 3 doughnut selection taken 2 at a time:
Line 3,372 ⟶ 3,448:
===version 3===
iterative (transformed from version 1)
<langsyntaxhighlight lang="rexx">/*REXX compute (and show) combination sets for nt things in ns places*/
Numeric Digits 20
debug=0
Line 3,426 ⟶ 3,502:
Say l
End
Return</langsyntaxhighlight>
 
{{out}}
Line 3,447 ⟶ 3,523:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Combinations with repetitions
 
Line 3,511 ⟶ 3,587:
next
return aList
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,526 ⟶ 3,602:
=={{header|Ruby}}==
{{works with|Ruby|2.0}}
<langsyntaxhighlight lang="ruby">possible_doughnuts = ['iced', 'jam', 'plain'].repeated_combination(2)
puts "There are #{possible_doughnuts.count} possible doughnuts:"
possible_doughnuts.each{|doughnut_combi| puts doughnut_combi.join(' and ')}
Line 3,534 ⟶ 3,610:
# size returns the size of the enumerator, or nil if it can’t be calculated lazily.
puts "", "#{possible_doughnuts.size} ways to order 30 donuts given 1000 types."
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,549 ⟶ 3,625:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
// Iterator for the combinations of `arr` with `k` elements with repetitions.
// Yields the combinations in lexicographical order.
Line 3,620 ⟶ 3,696:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,633 ⟶ 3,709:
=={{header|Scala}}==
Scala has a combinations method in the standard library.
<langsyntaxhighlight lang="scala">
object CombinationsWithRepetition {
 
Line 3,647 ⟶ 3,723:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,661 ⟶ 3,737:
=={{header|Scheme}}==
{{trans|PicoLisp}}
<langsyntaxhighlight lang="scheme">(define (combs-with-rep k lst)
(cond ((= k 0) '(()))
((null? lst) '())
Line 3,673 ⟶ 3,749:
 
(display (combs-with-rep 2 (list "iced" "jam" "plain"))) (newline)
(display (length (combs-with-rep 3 '(1 2 3 4 5 6 7 8 9 10)))) (newline)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,681 ⟶ 3,757:
 
===Dynamic programming===
<langsyntaxhighlight lang="scheme">(define (combs-with-rep m lst)
(define arr (make-vector (+ m 1) '()))
(vector-set! arr 0 '(()))
Line 3,695 ⟶ 3,771:
 
(display (combs-with-rep 2 (list "iced" "jam" "plain"))) (newline)
(display (length (combs-with-rep 3 '(1 2 3 4 5 6 7 8 9 10)))) (newline)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,704 ⟶ 3,780:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func cwr (n, l, a = []) {
n>0 ? (^l -> map {|k| __FUNC__(n-1, l.slice(k), [a..., l[k]]) }) : a
}
Line 3,710 ⟶ 3,786:
cwr(2, %w(iced jam plain)).each {|a|
say a.map{ .join(' ') }.join("\n")
}</langsyntaxhighlight>
 
Also built-in:
 
<langsyntaxhighlight lang="ruby">%w(iced jam plain).combinations_with_repetition(2, {|*a|
say a.join(' ')
})</langsyntaxhighlight>
 
{{out}}
Line 3,729 ⟶ 3,805:
 
Efficient count of the total number of combinations with repetition:
<langsyntaxhighlight lang="ruby">func cwr_count (n, m) { binomial(n + m - 1, m) }
printf("\nThere are %s ways to pick 7 out of 10 with repetition\n", cwr_count(10, 7))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,739 ⟶ 3,815:
{{trans|Haskell}}
 
<langsyntaxhighlight lang="sml">let rec combs_with_rep k xxs =
match k, xxs with
| 0, _ -> [[]]
Line 3,745 ⟶ 3,821:
| k, x::xs ->
List.map (fun ys -> x::ys) (combs_with_rep (k-1) xxs)
@ combs_with_rep k xs</langsyntaxhighlight>
 
in the interactive loop:
Line 3,760 ⟶ 3,836:
===Dynamic programming===
 
<langsyntaxhighlight lang="sml">fun combs_with_rep (m, xs) = let
val arr = Array.array (m+1, [])
in
Line 3,770 ⟶ 3,846:
) xs;
Array.sub (arr, m)
end</langsyntaxhighlight>
 
in the interactive loop:
Line 3,785 ⟶ 3,861:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function combrep(v,k) {
n = cols(v)
a = J(comb(n+k-1,k),k,v[1])
Line 3,803 ⟶ 3,879:
 
a = combrep(1..10,3)
rows(a)</langsyntaxhighlight>
 
'''Output'''
Line 3,820 ⟶ 3,896:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func combosWithRep<T>(var objects: [T], n: Int) -> [[T]] {
if n == 0 { return [[]] } else {
var combos = [[T]]()
Line 3,830 ⟶ 3,906:
}
}
print(combosWithRep(["iced", "jam", "plain"], n: 2).map {$0.joinWithSeparator(" and ")}.joinWithSeparator("\n"))</langsyntaxhighlight>
Output:
<pre>plain and plain
Line 3,840 ⟶ 3,916:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc combrepl {set n {presorted no}} {
if {!$presorted} {
Line 3,862 ⟶ 3,938:
 
puts [combrepl {iced jam plain} 2]
puts [llength [combrepl {1 2 3 4 5 6 7 8 9 10} 3]]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,870 ⟶ 3,946:
 
=={{header|TXR}}==
<langsyntaxhighlight lang="dos">txr -p "(rcomb '(iced jam plain) 2)"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,876 ⟶ 3,952:
</pre>
----
<langsyntaxhighlight lang="dos">txr -p "(length-list (rcomb '(0 1 2 3 4 5 6 7 8 9) 3))"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,883 ⟶ 3,959:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 3,890 ⟶ 3,966:
#cast %gLSnX
 
main = ^|(~&,length) cwr~~/(<'iced','jam','plain'>,2) ('1234567890',3)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,905 ⟶ 3,981:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Combinations with repetitions - iterative - VBScript
 
Sub printc(vi,n,vs)
Line 3,940 ⟶ 4,016:
combine 10, 3, , False
combine 10, 7, , False
combine 10, 9, , False </langsyntaxhighlight>
{{out}}
<pre>
Line 3,958 ⟶ 4,034:
 
=={{header|Wren}}==
===Concise recursive===
{{trans|Go}}
Produces results in no particular order.
<lang ecmascript>var combrep // recursive
combrep<syntaxhighlight lang="wren">var Combrep = Fn.new { |n, lst|
if (n == 0 ) return [[]]
if (lst.count == 0) return []
var r = combrepCombrep.call(n, lst[1..-1])
for (x in combrepCombrep.call(n-1, lst)) {
var y = x.toList
y.add(lst[0])
Line 3,972 ⟶ 4,049:
}
 
System.print(combrepCombrep.call(2, ["iced", "jam", "plain"]))
System.print(combrepCombrep.call(3, (1..10).toList).count)</langsyntaxhighlight>
 
{{out}}
<pre>
[[plain, plain], [plain, jam], [jam, jam], [plain, iced], [jam, iced], [iced, iced]]
220
</pre>
 
===Library based===
{{libheader|Wren-seq}}
{{libheader|Wren-perm}}
Produces results in lexicographic order.
<syntaxhighlight lang="wren">import "./seq" for Lst
import "./perm" for Comb
 
var a = ["iced", "jam", "plain"]
a = Lst.flatten(Lst.zip(a, a))
System.print(Comb.listDistinct(a, 2))
 
a = (1..10).toList
a = Lst.flatten(Lst.zip(Lst.zip(a, a), a))
System.print(Comb.listDistinct(a, 3).count)</syntaxhighlight>
{{out}}
<pre>
[[iced, iced], [iced, jam], [iced, plain], [jam, jam], [jam, plain], [plain, plain]]
220
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11, Text=12;
int Count, Array(10);
 
Line 4,009 ⟶ 4,106:
Combos(0, 0, 3, 10, [0]);
Text(0, "Combos = "); IntOut(0, Count); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,025 ⟶ 4,122:
=={{header|zkl}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="zkl">fcn combosK(k,seq){ // repeats, seq is finite
if (k==1) return(seq);
if (not seq) return(T);
self.fcn(k-1,seq).apply(T.extend.fp(seq[0])).extend(self.fcn(k,seq[1,*]));
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">combosK(2,T("iced","jam","plain")).apply("concat",",");
combosK(3,T(0,1,2,3,4,5,6,7,8,9)).len();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,039 ⟶ 4,136:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 READ n
20 DIM d$(n,5)
30 FOR i=1 TO n
Line 4,049 ⟶ 4,146:
90 PRINT d$(i);" ";d$(j)
100 NEXT j
110 NEXT i</langsyntaxhighlight>
9,479

edits