Skip to content

Commit bd31e71

Browse files
committed
combinations_with_replacement
1 parent bea9568 commit bd31e71

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
function X = combinations_with_replacement(x, k)
2+
[m, n] = size(x);
3+
% It should be a row vector
4+
if m > 1
5+
x = x.';
6+
end
7+
[m, n] = size(x);
8+
if m > 1
9+
error('Input must be a row vector');
10+
end
11+
% Number of output rows
12+
rows = nchoosek(n+k-1, k);
13+
X = zeros(rows, k);
14+
% row index for storing a combination
15+
cur_row = 1;
16+
chosen = zeros(1, k);
17+
function iterate(index, r, s, e)
18+
if (index > r)
19+
X(cur_row, :) = x(chosen);
20+
cur_row = cur_row + 1;
21+
return;
22+
end
23+
for i=s:e
24+
chosen(index) = i;
25+
iterate(index + 1, r, i, e);
26+
end
27+
end
28+
iterate(1, k, 1, n);
29+
end

0 commit comments

Comments
 (0)