Feature #4907

enumerable#permutation and combination

Added by Ondrej Bilka almost 3 years ago. Updated over 1 year ago.

[ruby-core:37231]
Status:Assigned
Priority:Low
Assignee:Kenta Murata
Category:-
Target version:next minor

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=toenum.withindex
_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 Updated by Yusuke Endoh about 2 years ago

  • Status changed from Open to Assigned
  • Assignee set to Kenta Murata

#2 Updated by Yusuke Endoh over 1 year ago

  • Priority changed from Normal to Low
  • Target version set to next minor

This will not work for an enumerator created from IO.

Yusuke Endoh mame@tsg.ne.jp

Also available in: Atom PDF