[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

substrings

Edward Redman

1/19/2006 2:27:00 AM

I am struggling with the following.
Given a sting of a given length example string = 'bkerhcno'
give all the subsets of string of length 4

I don't need all the permutations just the subsets.
I can use the slice method to give me some subsets i.e
s1 = string.slice(0,4)
s2 = string.slice(1,4) etc.
Just how do I generate all the possible combination of 4 characters.

By analagy, would like to extend to finding all combination of length 5,6,
and 7.

Hope someone can help.


1 Answer

Robert Klemme

1/19/2006 8:33:00 AM

0

Ed Redman wrote:
> I am struggling with the following.
> Given a sting of a given length example string = 'bkerhcno'
> give all the subsets of string of length 4
>
> I don't need all the permutations just the subsets.
> I can use the slice method to give me some subsets i.e
> s1 = string.slice(0,4)
> s2 = string.slice(1,4) etc.
> Just how do I generate all the possible combination of 4 characters.
>
> By analagy, would like to extend to finding all combination of length
> 5,6, and 7.
>
> Hope someone can help.

def sub_strings(s,len)
(s.length - len).times do |idx|
yield s[idx,len]
end
end

>> sub_strings( 'bkerhcno', 4 ) {|s| p s}
"bker"
"kerh"
"erhc"
"rhcn"
"hcno"
=> 0..4

Kind regards

robert