Combinations with repetitions: Difference between revisions

Content added Content deleted
m (→‎{{header|Sidef}}: updated code)
Line 2,899: Line 2,899:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>func p (n, a, l) { n>0 ? (l.range.map{p(n-1, a+[l[_]], l.ft(_))}) : a };
<lang ruby>func cwr (n, l, a = []) {
func f (n) { n>0 ? (n * f(n - 1)) : 1 };
n>0 ? (^l -> map {|k| __FUNC__(n-1, l.slice(k), [a..., l[k]]) }) : a
func n (n, m) { f(n + m - 1) / f(n) / f(m - 1) };

p(2, [], %w(iced jam plain)).each { |a|
say a.map{|pair| pair.join(" ")}.join("\n");
}
}


cwr(2, %w(iced jam plain)).each {|a|
printf("\nThere are %d ways to pick 7 out of 10\n", n(7, 10));</lang>
say a.map{ .join(' ') }.join("\n")
}</lang>

Also built-in:

<lang ruby>%w(iced jam plain).combinations_with_repetition(2, {|*a|
say a.join(' ')
})</lang>


{{out}}
{{out}}
Line 2,917: Line 2,921:
jam plain
jam plain
plain plain
plain plain
</pre>


Efficient count of the total number of combinations with repetition:
There are 11440 ways to pick 7 out of 10
<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))</lang>
{{out}}
<pre>
There are 11440 ways to pick 7 out of 10 with repetition
</pre>
</pre>