Combinations with repetitions: Difference between revisions

→‎Concise recursive: Changed to Wren S/H
(Added 11l)
(→‎Concise recursive: Changed to Wren S/H)
 
(26 intermediate revisions by 16 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!}}==
<syntaxhighlight lang="action!">PROC PrintComb(BYTE ARRAY c BYTE len)
BYTE i,ind
 
FOR i=0 TO len-1
DO
IF i>0 THEN Put('+) FI
ind=c(i)
IF ind=0 THEN
Print("iced")
ELSEIF ind=1 THEN
Print("jam")
ELSE
Print("plain")
FI
OD
PutE()
RETURN
 
BYTE FUNC NotDecreasing(BYTE ARRAY c BYTE len)
BYTE i
 
IF len<2 THEN RETURN (1) FI
 
FOR i=0 TO len-2
DO
IF c(i)>c(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
 
BYTE FUNC NextComb(BYTE ARRAY c BYTE n,k)
INT pos,i
 
DO
pos=k-1
DO
c(pos)==+1
IF c(pos)<n THEN
EXIT
ELSE
pos==-1
IF pos<0 THEN RETURN (0) FI
FI
FOR i=pos+1 TO k-1
DO
c(i)=c(pos)
OD
OD
UNTIL NotDecreasing(c,k)
OD
RETURN (1)
 
PROC Comb(BYTE n,k,show)
BYTE ARRAY c(10)
BYTE i,count
 
IF k>n THEN
Print("Error! k is greater than n.")
Break()
FI
 
PrintF("Choices of %B from %B:%E",k,n)
FOR i=0 TO k-1
DO
c(i)=0
OD
 
count=0
DO
count==+1
IF show THEN
PrintF(" %B. ",count)
PrintComb(c,k)
FI
UNTIL NextComb(c,n,k)=0
OD
PrintF("Total choices %B%E%E",count)
RETURN
 
PROC Main()
Comb(3,2,1)
Comb(10,3,0)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Combinations_with_repetitions.png Screenshot from Atari 8-bit computer]
<pre>
Choices of 2 from 3:
1. iced+iced
2. iced+jam
3. iced+plain
4. jam+jam
5. jam+plain
6. plain+plain
Total choices 6
 
Choices of 3 from 10:
Total choices 220
</pre>
 
Line 162 ⟶ 299:
 
combinations.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Combinations is
 
Line 225 ⟶ 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 240 ⟶ 377:
{{Trans|Haskell}}
{{Trans|Python}}
<langsyntaxhighlight lang="applescript">--------------- combsWithRepCOMBINATIONS ::WITH IntREPETITION -> [a] -> [kTuple a]-----------
 
on combsWithRep(k, xs)
-- combinationsWithRepetition :: Int -> [a] -> [kTuple a]
-- A list of lists, representing
on combinationsWithRepetition(k, xs)
-- A list of lists, representing
-- sets of cardinality k, with
-- members drawn from xs.
script combsBySizecombinationsBySize
script f
on |λ|(a, x)
Line 260 ⟶ 399:
end |λ|
end script
scanl1(go, a)
end |λ|
Line 269 ⟶ 409:
end script
|Just| of |index|(|λ|(xs) of combsBySizecombinationsBySize, 1 + k)
end combinationsWithRepetition
end combsWithRep
 
 
-- TEST -------------------------- TEST -------------------------
on run
{length of combsWithRepcombinationsWithRepetition(3, enumFromTo(0, 9)), ¬
combsWithRepcombinationsWithRepetition(2, {"iced", "jam", "plain"})}
end run
 
 
-- GENERIC ------------------------ GENERIC ------------------------
 
-- Just :: a -> Maybe a
Line 286 ⟶ 426:
{type:"Maybe", Nothing:false, Just:x}
end Just
 
 
-- Nothing :: Maybe a
Line 291 ⟶ 432:
{type:"Maybe", Nothing:true}
end Nothing
 
 
-- enumFromTo :: (Int, Int) -> [Int]
Line 304 ⟶ 446:
end if
end enumFromTo
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 316 ⟶ 459:
end tell
end foldl
 
 
-- index (!!) :: [a] -> Int -> Maybe a
Line 338 ⟶ 482:
end if
end |index|
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 350 ⟶ 495:
end tell
end map
 
 
-- min :: Ord a => a -> a -> a
Line 359 ⟶ 505:
end if
end min
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 371 ⟶ 518:
end if
end mReturn
 
 
-- repeat :: a -> Generator [a]
Line 395 ⟶ 543:
end tell
end scanl
 
 
-- scanl1 :: (a -> a -> a) -> [a] -> [a]
Line 436 ⟶ 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 458 ⟶ 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 478 ⟶ 637:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f COMBINATIONS_WITH_REPETITIONS.AWK
BEGIN {
Line 502 ⟶ 661:
exit(0)
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 514 ⟶ 673:
</pre>
 
=={{header|BBC BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">arraybase 0
print "Enter n comb m. "
input integer "n: ", n
input integer "m: ", m
outstr$ = ""
dim names$(m)
 
for i = 0 to m - 1
print "Name for item "; i; ": ";
input string names$[i]
next i
call iterate (outstr$, 0, m-1, n-1, names$)
end
 
subroutine iterate(curr$, start, stp, depth, names$)
for i = start to stp
if depth = 0 then
print curr$; " "; names$[i]
else
call iterate (curr$ & " " & names$[i], i, stp, depth-1, names$)
end if
next i
return
end subroutine</syntaxhighlight>
 
==={{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 542 ⟶ 728:
c% += FNchoose(n% + 1, l%, i%, m%, g%(), n$())
NEXT
= c%</langsyntaxhighlight>
{{out}}
<pre>
Line 557 ⟶ 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 578 ⟶ 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 584 ⟶ 784:
 
=={{header|C}}==
Non recursive solution
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">
#include <stdio.h>
 
const char *donuts[] = {"iced", "jam", "plain",
"something completely different"};
int pos[] = {0, 0, 0, 0};
 
void printDonuts(int k) {
for (size_t i = 1; i < k + 1; i += 1) // offset: i:1..N, N=k+1
printf("%s\t", donuts[pos[i]]); // str:0..N-1
printf("\n");
}
 
// idea: custom number system with 2s complement like 0b10...0==MIN stop case
void combination_with_repetiton(int n, int k) {
while (1) {
for (int i = k; i > 0; i -= 1) {
if (pos[i] > n - 1) // if number spilled over: xx0(n-1)xx
{
pos[i - 1] += 1; // set xx1(n-1)xx
for (int j = i; j <= k; j += 1)
pos[j] = pos[j - 1]; // set xx11..1
}
}
if (pos[0] > 0) // stop condition: 1xxxx
break;
printDonuts(k);
pos[k] += 1; // xxxxN -> xxxxN+1
}
}
 
int main() {
combination_with_repetiton(3, 2);
return 0;
}
</syntaxhighlight>
 
<syntaxhighlight lang="c">#include <stdio.h>
 
const char * donuts[] = { "iced", "jam", "plain", "something completely different" };
Line 616 ⟶ 854:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}<pre>iced iced
iced jam
Line 629 ⟶ 867:
{{trans|PHP}}
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 688 ⟶ 926:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 701 ⟶ 939:
 
Recursive version
<langsyntaxhighlight lang="csharp">
using System;
class MultiCombination
Line 725 ⟶ 963:
}
 
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
 
Non recursive version.
<langsyntaxhighlight lang="cpp">
#include <cstdioiostream>
#include <vectorstring>
#include <stringvector>
 
void print_vector(const std::vector<int> &pos,
using namespace std;
const std::vector<std::string> &str) {
for (size_t i = 1; i < pos.size(); ++i) // offset: i:1..N
void print_vector(const vector<int> &v, size_t n, const vector<string> &s){
printf("%s\t", str[pos[i]].c_str()); // str: 0..N-1
for (size_t i = 0; i < n; ++i)
printf("%s\tn", s[v[i]].c_str());
printf("\n");
}
void combination_with_repetiton(int sabores, int bolas, const vector<string>& v_sabores){
sabores--;
vector<int> v(bolas+1, 0);
while (true){
for (int i = 0; i < bolas; ++i){ //vai um
if (v[i] > sabores){
v[i + 1] += 1;
for (int k = i; k >= 0; --k){
v[k] = v[i + 1];
}
//v[i] = v[i + 1];
}
}
if (v[bolas] > 0)
break;
print_vector(v, bolas, v_sabores);
v[0] += 1;
}
}
 
// idea: custom number system with 2s complement like 0b10...0==MIN stop case
int main(){
void combination_with_repetiton(int n, int k,
vector<string> options{ "iced", "jam", "plain" };
const std::vector<std::string> &str) {
combination_with_repetiton(3, 2, options);
std::vector<int> pos(k + 1, 0);
return 0;
while (true) {
for (int i = k; i > 0; i -= 1) {
if (pos[i] > n - 1) // if number spilled over: xx0(n-1)xx
{
pos[i - 1] += 1; // set xx1(n-1)xx
for (int j = i; j <= k; j += 1)
pos[j] = pos[j - 1]; // set xx11..1
}
}
if (pos[0] > 0) // stop condition: 1xxxx
break;
print_vector(pos, str);
pos[k] += 1; // xxxxN -> xxxxN+1
}
}
 
</lang>
int main() {
std::vector<std::string> str{"iced", "jam", "plain"};
combination_with_repetiton(3, 2, str);
return 0;
}
</syntaxhighlight>
 
{{out}}
<pre>
iced iced
jam iced jam
plain iced plain
jam jam
jam plain
plain jam
plain plain
</pre>
 
Line 784 ⟶ 1,020:
{{trans|Scheme}}
 
<langsyntaxhighlight lang="clojure">
(defn combinations [coll k]
(when-let [[x & xs] coll]
Line 791 ⟶ 1,027:
(concat (map (partial cons x) (combinations coll (dec k)))
(combinations xs k)))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 800 ⟶ 1,036:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
combos = (arr, k) ->
return [ [] ] if k == 0
Line 813 ⟶ 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 829 ⟶ 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 837 ⟶ 1,073:
(combinations xs (1- k)))
(combinations (cdr xs) k))))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 845 ⟶ 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 852 ⟶ 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 868 ⟶ 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 956 ⟶ 1,192:
writeln("Ways to select 3 from 10 types is ",
CombRep(10, 3).length);
}</langsyntaxhighlight>
{{out}}
<pre> iced iced
Line 967 ⟶ 1,203:
 
===Short Recursive Version===
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm;
 
T[][] combsRep(T)(T[] lst, in int k) {
Line 982 ⟶ 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 989 ⟶ 1,225:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>items$[] = [ "iced" "jam" "plain" ]
items$[] = [ "iced" "jam" "plain" ]
n = len items$[]
k = 2
Line 995 ⟶ 1,232:
n_results = 0
#
funcproc output . .
n_results += 1
if len items$[] > 0
s$ = ""
for i range= 1 to k
s$ &= items$[result[i]] & " "
.
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,022 ⟶ 1,259:
items$[] = [ ]
n_results = 0
call combine 01 01
print ""
print n_results & " results with 10 donuts"</lang>
</syntaxhighlight>
 
{{out}}
Line 1,040 ⟶ 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,083 ⟶ 1,321:
→ 220
 
</syntaxhighlight>
</lang>
 
=={{header|Egison}}==
 
<langsyntaxhighlight lang="egison">
(define $comb/rep
(lambda [$n $xs]
Line 1,094 ⟶ 1,332:
 
(test (comb/rep 2 {"iced" "jam" "plain"}))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,102 ⟶ 1,340:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def comb_rep(0, _), do: [[]]
def comb_rep(_, []), do: []
Line 1,113 ⟶ 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,128 ⟶ 1,366:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(comb).
-compile(export_all).
Line 1,138 ⟶ 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,150 ⟶ 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,207 ⟶ 1,463:
 
end program main
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,221 ⟶ 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,243 ⟶ 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,261 ⟶ 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,288 ⟶ 1,544:
fmt.Println(len(combrep(3,
[]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"})))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,297 ⟶ 1,553:
===Channel===
Using channel and goroutine, showing how to use synced or unsynced communication.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,354 ⟶ 1,610:
}
fmt.Printf("\npicking 3 of 10: %d\n", count)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,368 ⟶ 1,624:
===Multiset===
This version has proper representation of sets and multisets.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,469 ⟶ 1,725:
}
fmt.Println(len(combrep(3, ten)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,482 ⟶ 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,505 ⟶ 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,514 ⟶ 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,521 ⟶ 1,777:
 
main :: IO ()
main = print $ combsWithRep 2 ["iced", "jam", "plain"]</langsyntaxhighlight>
 
and another approach, using manual recursion:
<syntaxhighlight lang="haskell">--------------- COMBINATIONS WITH REPETITION -------------
<lang haskell>combsWithRep
 
:: (Eq a)
combinationsWithRepetition ::
=> Int -> [a] -> [[a]]
(Eq a) =>
combsWithRep k xs = comb k []
Int ->
[a] ->
[[a]]
combinationsWithRepetition k xs = cmb k []
where
combcmb 0 ys = ys
combcmb n [] = combcmb (pred n) (pure <$> xs)
combcmb n peers = combcmb (pred n) (peers >>= nextLayer)
where
nextLayer ys@(h:_)[] = (: ys) <$> dropWhile (/= h) xs[]
nextLayer ys@(h : _) =
(: ys) <$> dropWhile (/= h) xs
 
 
-------------------------- TESTS -------------------------
main :: IO ()
main = do
print $
print $ combsWithRep 2 ["iced", "jam", "plain"]
combinationsWithRepetition
print $ length $ combsWithRep 3 [0 .. 9]</lang>
2
["iced", "jam", "plain"]
print $ length $ combinationsWithRepetition 3 [0 .. 9]</syntaxhighlight>
{{Out}}
<pre>[["iced","iced"],["jam","iced"],["plain","iced"],["jam","jam"],["plain","jam"],["plain","plain"]]
Line 1,546 ⟶ 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,564 ⟶ 1,831:
}
end
</syntaxhighlight>
</lang>
 
Test procedure:
 
<syntaxhighlight lang="icon">
<lang Icon>
# convenience function
procedure write_list (l)
Line 1,585 ⟶ 1,852:
write ("There are " || count || " possible combinations of 3 from 10")
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,597 ⟶ 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,634 ⟶ 1,887:
└─────┴─────┘
#3 rcomb i.10 NB. # ways to choose 3 items from 10 with repetitions
220</langsyntaxhighlight>
 
===J Alternate implementation===
Line 1,640 ⟶ 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,652 ⟶ 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,685 ⟶ 1,937:
}
} // class
</syntaxhighlight>
</lang>
 
'''MultiCombinations.java'''
<langsyntaxhighlight lang="java">
import com.objectwave.utility.*;
import java.util.*;
Line 1,737 ⟶ 1,989:
}
} // class
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,754 ⟶ 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,777 ⟶ 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,789 ⟶ 2,041:
 
====Functional====
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// n -> [a] -> [[a]]
Line 1,833 ⟶ 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 1,906 ⟶ 2,158:
threeFromTen: length(combsWithRep(3, enumFromTo(0, 9)))
});
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 1,939 ⟶ 2,191:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def pick(n):
def pick(n; m): # pick n, from m onwards
if n == 0 then []
Line 1,946 ⟶ 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 1,967 ⟶ 2,219:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using Combinatorics
 
l = ["iced", "jam", "plain"]
Line 1,975 ⟶ 2,227:
end
 
@show length(with_replacement_combinations(1:10, 3))</langsyntaxhighlight>
 
{{out}}
Line 1,989 ⟶ 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,025 ⟶ 2,277:
val generic10 = "0123456789".chunked(1)
CombsWithReps(3, 10, generic10, true)
}</langsyntaxhighlight>
 
{{out}}
Line 2,047 ⟶ 2,299:
===With List Comprehension===
 
<langsyntaxhighlight lang="lisp">
(defun combinations
(('() _)
Line 2,057 ⟶ 2,309:
(cons head subcoll))
(combinations tail n))))
</syntaxhighlight>
</lang>
===With Map===
 
<langsyntaxhighlight lang="lisp">
(defun combinations
(('() _)
Line 2,070 ⟶ 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,105 ⟶ 2,357:
print count
let extra = choose(map(10):_, 3): _
print extra</langsyntaxhighlight>
{{out}}
<pre>["iced", "iced"]
Line 2,118 ⟶ 2,370:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function GenerateCombinations(tList, nMaxElements, tOutput, nStartIndex, nChosen, tCurrentCombination)
if not nStartIndex then
nStartIndex = 1
Line 2,164 ⟶ 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,173 ⟶ 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,185 ⟶ 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,203 ⟶ 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,212 ⟶ 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,243 ⟶ 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,264 ⟶ 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,272 ⟶ 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,284 ⟶ 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,292 ⟶ 2,544:
{{trans|Haskell}}
 
<langsyntaxhighlight lang="ocaml">let rec combs_with_rep k xxs =
match k, xxs with
| 0, _ -> [[]]
Line 2,298 ⟶ 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,314 ⟶ 2,566:
===Dynamic programming===
 
<langsyntaxhighlight lang="ocaml">let combs_with_rep m xs =
let arr = Array.make (m+1) [] in
arr.(0) <- [[]];
Line 2,322 ⟶ 2,574:
done
) xs;
arr.(m)</langsyntaxhighlight>
 
in the interactive loop:
Line 2,337 ⟶ 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,345 ⟶ 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]]
<syntaxhighlight lang="pascal">program CombWithRep;
//combinations with repetitions
//Limit = count of elements
//Maxval = value of top , lowest is always 0
//so 0..Maxvalue => maxValue+1 elements
{$IFDEF FPC}
// {$R+,O+}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON}
{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
SysUtils;//GetTickCount64
 
var
CombIdx: array of byte;
 
function InitCombIdx(ElemCount: Int32): pbyte;
begin
setlength(CombIdx, ElemCount + 1);
Fillchar(CombIdx[0], sizeOf(CombIdx[0]) * (ElemCount + 1), #0);
Result := @CombIdx[0];
end;
 
function NextCombWithRep(pComb: pByte; MaxVal, ElemCount: UInt32): boolean;
var
i, dgt: NativeInt;
begin
i := -1;
repeat
i += 1;
dgt := pComb[i];
if dgt < MaxVal then
break;
until i > ElemCount;
Result := i >= ElemCount;
dgt +=1;
repeat
pComb[i] := dgt;
i -= 1;
until i < 0;
end;
 
procedure GetDoughnuts(ElemCount: NativeInt);
const
doughnuts: array[0..2] of string = ('iced', 'jam', 'plain');
var
pComb: pByte;
MaxVal, i: Uint32;
begin
if ElemCount < 1 then
EXIT;
MaxVal := High(doughnuts);
writeln('Getting ', ElemCount, ' elements of ', MaxVal + 1, ' different');
pComb := InitCombIdx(ElemCount);
repeat
Write('[');
for i := 0 to ElemCount - 2 do
Write(pComb[i], ',');
Write(pComb[ElemCount - 1], ']');
Write('{');
for i := 0 to ElemCount - 2 do
Write(doughnuts[pComb[i]], ',');
Write(doughnuts[pComb[ElemCount - 1]], '}');
until NextCombWithRep(pComb, MaxVal, ElemCount);
writeln(#10);
end;
 
procedure Check(ElemCount: Int32; ElemRange: Uint32);
var
pComb: pByte;
T0: int64;
rec_cnt: NativeInt;
begin
T0 := GetTickCount64;
rec_cnt := 0;
ElemRange -= 1;
pComb := InitCombIdx(ElemCount);
repeat
Inc(rec_cnt);
until NextCombWithRep(pComb, ElemRange, ElemCount);
T0 := GetTickCount64 - T0;
writeln('Getting ', ElemCount, ' elements of ', ElemRange + 1, ' different');
writeln(rec_cnt: 10, t0: 10,' ms');
end;
 
begin
GetDoughnuts(2);
GetDoughnuts(3);
Check(3, 10);
Check(9, 10);
Check(15, 16);
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end.</syntaxhighlight>
{{out}}
<pre>
TIO.RUN
Getting 2 elements of 3 different
[0,0]{iced,iced}[1,0]{jam,iced}[2,0]{plain,iced}[1,1]{jam,jam}[2,1]{plain,jam}[2,2]{plain,plain}
 
Getting 3 elements of 3 different
[0,0,0]{iced,iced,iced}[1,0,0]{jam,iced,iced}[2,0,0]{plain,iced,iced}[1,1,0]{jam,jam,iced}[2,1,0]{plain,jam,iced}[2,2,0]{plain,plain,iced}[1,1,1]{jam,jam,jam}[2,1,1]{plain,jam,jam}[2,2,1]{plain,plain,jam}[2,2,2]{plain,plain,plain}
 
Getting 3 elements of 10 different
220 0 ms
Getting 9 elements of 10 different
48620 0 ms
Getting 15 elements of 16 different
155117520 735 ms
</pre>
 
=={{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,358 ⟶ 2,723:
 
printf "\nThere are %d ways to pick 7 out of 10\n", pn(7,10);
</syntaxhighlight>
</lang>
 
Prints:
Line 2,371 ⟶ 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,378 ⟶ 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,394 ⟶ 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,406 ⟶ 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,419 ⟶ 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,457 ⟶ 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,472 ⟶ 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,534 ⟶ 2,909:
 
?>
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de combrep (N Lst)
(cond
((=0 N) '(NIL))
Line 2,546 ⟶ 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,555 ⟶ 2,930:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
combinations_of_length(_,[]).
combinations_of_length([X|T],[X|Combinations]):-
Line 2,561 ⟶ 2,936:
combinations_of_length([_|T],[X|Combinations]):-
combinations_of_length(T,[X|Combinations]).
</syntaxhighlight>
</lang>
<pre>
?- [user].
Line 2,598 ⟶ 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,666 ⟶ 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,683 ⟶ 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,690 ⟶ 3,065:
>>> len(list(combinations_with_replacement(range(10), 3)))
220
>>> </langsyntaxhighlight>
 
'''References:'''
Line 2,700 ⟶ 3,075:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Combinations with repetitions'''
 
from itertools import (accumulate, chain, islice, repeat)
Line 2,763 ⟶ 3,138:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[('iced', 'iced'), ('jam', 'iced'), ('jam', 'jam'), ('plain', 'iced'), ('plain', 'jam'), ('plain', 'plain')]
Line 2,775 ⟶ 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 2,852 ⟶ 3,227:
[ echo$ sp ] cr ]
cr
3 10 kcombnums size echo</langsyntaxhighlight>
 
{{out}}
Line 2,867 ⟶ 3,242:
=={{header|R}}==
The idiomatic solution is to just use a library.
<langsyntaxhighlight Rlang="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 2,883 ⟶ 3,258:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (combinations xs k)
Line 2,891 ⟶ 3,266:
(map (λ(x) (cons (first xs) x))
(combinations xs (- k 1))))]))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,899 ⟶ 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 2,917 ⟶ 3,292:
 
{{trans|Haskell}}
<syntaxhighlight lang="raku" perl6line>proto combs_with_rep (UInt, @) {*}
multi combs_with_rep (0, @) { () }
Line 2,933 ⟶ 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 2,946 ⟶ 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 2,965 ⟶ 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 2,985 ⟶ 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,050 ⟶ 3,425:
Say l
End
Return</langsyntaxhighlight>
{{out}}
<pre>----------- 3 doughnut selection taken 2 at a time:
Line 3,073 ⟶ 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,127 ⟶ 3,502:
Say l
End
Return</langsyntaxhighlight>
 
{{out}}
Line 3,148 ⟶ 3,523:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Combinations with repetitions
 
Line 3,212 ⟶ 3,587:
next
return aList
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,227 ⟶ 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,235 ⟶ 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,250 ⟶ 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,321 ⟶ 3,696:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,334 ⟶ 3,709:
=={{header|Scala}}==
Scala has a combinations method in the standard library.
<langsyntaxhighlight lang="scala">
object CombinationsWithRepetition {
 
Line 3,348 ⟶ 3,723:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,362 ⟶ 3,737:
=={{header|Scheme}}==
{{trans|PicoLisp}}
<langsyntaxhighlight lang="scheme">(define (combs-with-rep k lst)
(cond ((= k 0) '(()))
((null? lst) '())
Line 3,374 ⟶ 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,382 ⟶ 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,396 ⟶ 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,405 ⟶ 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,411 ⟶ 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,430 ⟶ 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,440 ⟶ 3,815:
{{trans|Haskell}}
 
<langsyntaxhighlight lang="sml">let rec combs_with_rep k xxs =
match k, xxs with
| 0, _ -> [[]]
Line 3,446 ⟶ 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,461 ⟶ 3,836:
===Dynamic programming===
 
<langsyntaxhighlight lang="sml">fun combs_with_rep (m, xs) = let
val arr = Array.array (m+1, [])
in
Line 3,471 ⟶ 3,846:
) xs;
Array.sub (arr, m)
end</langsyntaxhighlight>
 
in the interactive loop:
Line 3,486 ⟶ 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,504 ⟶ 3,879:
 
a = combrep(1..10,3)
rows(a)</langsyntaxhighlight>
 
'''Output'''
Line 3,521 ⟶ 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,531 ⟶ 3,906:
}
}
print(combosWithRep(["iced", "jam", "plain"], n: 2).map {$0.joinWithSeparator(" and ")}.joinWithSeparator("\n"))</langsyntaxhighlight>
Output:
<pre>plain and plain
Line 3,541 ⟶ 3,916:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc combrepl {set n {presorted no}} {
if {!$presorted} {
Line 3,563 ⟶ 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,571 ⟶ 3,946:
 
=={{header|TXR}}==
<langsyntaxhighlight lang="dos">txr -p "(rcomb '(iced jam plain) 2)"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,577 ⟶ 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,584 ⟶ 3,959:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 3,591 ⟶ 3,966:
#cast %gLSnX
 
main = ^|(~&,length) cwr~~/(<'iced','jam','plain'>,2) ('1234567890',3)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,606 ⟶ 3,981:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Combinations with repetitions - iterative - VBScript
 
Sub printc(vi,n,vs)
Line 3,641 ⟶ 4,016:
combine 10, 3, , False
combine 10, 7, , False
combine 10, 9, , False </langsyntaxhighlight>
{{out}}
<pre>
Line 3,659 ⟶ 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,673 ⟶ 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 3,710 ⟶ 4,106:
Combos(0, 0, 3, 10, [0]);
Text(0, "Combos = "); IntOut(0, Count); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,726 ⟶ 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 3,740 ⟶ 4,136:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 READ n
20 DIM d$(n,5)
30 FOR i=1 TO n
Line 3,750 ⟶ 4,146:
90 PRINT d$(i);" ";d$(j)
100 NEXT j
110 NEXT i</langsyntaxhighlight>
9,476

edits