Project

General

Profile

Feature #4907

enumerable#permutation and combination

Added by neleai (Ondrej Bilka) about 7 years ago. Updated 4 months ago.

Status:
Rejected
Priority:
Normal
Target version:
-
[ruby-core:37231]

Description

Hello
Methods permutation and combination are defined for array but it make more sense to define them for enumerable.
Here is sample implementation which for simplicity works only with blocks.
Note that implementation works lazily.
It changes traversal order but documentation states that order is unspecified.

module Enumerable
def perm(n)
comb(n){|ary|
ary.permutation{|p| yield(p)}
}
end
def comb(n,&m)
ary=[]
e=to_enum.with_index
_comb(e,n-1,1.0/0.0,ary,m)
end
def _comb(e,n,bound,ary,m)
e.each{|el,i|
return if i>=bound
ary[n]=el
if n==0
m.call(ary)
else
_comb(e,n-1,i,ary,m)
end
}
end

end
[1,2,4,3,5].comb(2){|a| puts a.inspect}
(1..4).comb(2){|a| puts a.inspect}
(1..4).perm(2){|a| puts a.inspect}

History

#1 [ruby-core:43637] Updated by mame (Yusuke Endoh) about 6 years ago

  • Status changed from Open to Assigned
  • Assignee set to mrkn (Kenta Murata)

#2 [ruby-core:49713] Updated by mame (Yusuke Endoh) over 5 years ago

  • Priority changed from Normal to 3
  • Target version set to 2.6

This will not work for an enumerator created from IO.

--
Yusuke Endoh mame@tsg.ne.jp

#3 Updated by naruse (Yui NARUSE) 6 months ago

  • Target version deleted (2.6)

#4 [ruby-core:86040] Updated by mrkn (Kenta Murata) 4 months ago

  • Status changed from Assigned to Closed

No use case is shown, so I close this issue.

#5 Updated by mrkn (Kenta Murata) 4 months ago

  • Status changed from Closed to Rejected

Also available in: Atom PDF