user3210918
user3210918

Reputation: 3

All ways to split a string in k parts in ruby

What is the best way to get an array that contains an array for every way to split a string in k factors, where the factors might also be empty? As an example, if k is 3 and the string is

Hello

then I would like a return value as follows:

[ ["", "", "Hello"], ["","H","ello"], ["", "He", "llo"], ..., ["H", "e", "llo"], ["H", "el", "lo"], ..., ["Hello","",""] ]

And I would like to have this in a function, so that k is parameter (for a fixed k I would just write k-1 loops). Is there a nice way to do that in ruby?

Thanks for your help!

Upvotes: 0

Views: 117

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

Using recursion:

def doit(s, k, b = [], r = [])
  case k
  when 0
    r << b
  when 1
    doit( [], 0, b + [s], r )
  else  
    (0..s.size).each { |i| doit( s[i..-1], k-1, b + [s[0,i]], r ) }     
  end
  r
end

v = doit('Hello', 3)
 #=> [["", "", "Hello"],["", "H", "ello"],["", "He", "llo"],["", "Hel", "lo"],
 #    ["", "Hell", "o"],["", "Hello", ""],["H", "", "ello"],["H", "e", "llo"],
 #    ["H", "el", "lo"],["H", "ell", "o"],["H", "ello", ""],["He", "", "llo"],
 #    ["He", "l", "lo"],["He", "ll", "o"],["He", "llo", ""],["Hel", "", "lo"],
 #    ["Hel", "l", "o"],["Hel", "lo", ""],["Hell", "", "o"],["Hell", "o", ""],
 #    ["Hello", "", ""]] 

Upvotes: 0

sawa
sawa

Reputation: 168209

s = "Hello"
k = 3
(0..s.length).to_a.repeated_combination(k - 1)
.map{|a| [0, *a, -1].each_cons(2).map{|i, j| "#{s} "[i...j]}}

result:

[
  ["", "", "Hello"],
  ["", "H", "ello"],
  ["", "He", "llo"],
  ["", "Hel", "lo"],
  ["", "Hell", "o"],
  ["", "Hello", ""],
  ["H", "", "ello"],
  ["H", "e", "llo"],
  ["H", "el", "lo"],
  ["H", "ell", "o"],
  ["H", "ello", ""],
  ["He", "", "llo"],
  ["He", "l", "lo"],
  ["He", "ll", "o"],
  ["He", "llo", ""],
  ["Hel", "", "lo"],
  ["Hel", "l", "o"],
  ["Hel", "lo", ""],
  ["Hell", "", "o"],
  ["Hell", "o", ""],
  ["Hello", "", ""]
]

Upvotes: 3

Related Questions