[ruby-core:123185] [Ruby Feature#21564] Extend permutation, repeated_permutation, combination and repeated_combination argument
From:
"nobu (Nobuyoshi Nakada) via ruby-core" <ruby-core@...>
Date:
2025-09-08 04:32:49 UTC
List:
ruby-core #123185
Issue #21564 has been updated by nobu (Nobuyoshi Nakada).
I'm not sure whether this is a natural extension of permutation.
And why not `array.permutation(count1, count2, count3)`?
Is it important to support `Range` without splatting?
----------------------------------------
Feature #21564: Extend permutation, repeated_permutation, combination and repeated_combination argument
https://bugs.ruby-lang.org/issues/21564#change-114516
* Author: toy (Ivan Kuchin)
* Status: Open
----------------------------------------
When using functions `permutation`, `repeated_permutation`, `combination` and `repeated_combination`, often one needs not one, but multiple permutation/combination sizes. Currently all functions accept one Integer argument (for `permutation` it is optional and defaults to array size), and it would be more powerful if it would accept also a range or a Enumerable:
```ruby
a = [1, 2, 3]
a.permutation(1..3).to_a # => [[1], [2], [3],
# [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2],
# [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
a.permutation([1, 3]).to_a # => [[1], [2], [3],
# [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
a.permutation([3, 1]).to_a # => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1],
# [1], [2], [3]]
a.repeated_permutation([2, 1]).to_a # => [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3],
# [1], [2], [3]]
a.combination(1..3).to_a # => [[1], [2], [3],
# [1, 2], [1, 3], [2, 3],
# [1, 2, 3]]
a.repeated_combination(1..3).to_a # => [[1], [2], [3],
# [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3],
# [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]]
```
Ruby code to enhance current `permutation` would be:
```ruby
class Array
alias_method :original_permutation, :permutation
def permutation(counts, &block)
return to_enum(__method__, counts) unless block
if counts.is_a?(Enumerable)
counts.each do |count|
original_permutation(count, &block)
end
else
original_permutation(counts, &block)
end
end
end
```
--
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/