A Fader Darkly
A Fader Darkly

Reputation: 3636

In Ruby I need to split a sentence into sub-sentences

Given the string:

"See Spot Run"

I need to return an array with:

[ "See", "Spot", "run", "See Spot", "Spot run", "See Spot Run" ]

So far I have:

term = "The cat sat on the mat"
#=> "The cat sat on the mat" 

arr = term.split(" ")
#=> ["The", "cat", "sat", "on", "the", "mat"] 

arr.length.times.map { |i| (arr.length - i).times.map { |j| arr[j..j+i].join(" ") } }.flatten(1)
#=> ["The", "cat", "sat", "on", "the", "mat", "The cat", "cat sat", "sat on", "on the", "the mat", "The cat sat", "cat sat on", "sat on the", "on the mat", "The cat sat on", "cat sat on the", "sat on the mat", "The cat sat on the", "cat sat on the mat", "The cat sat on the mat"] 

This is going to happen a lot of times, so can you think of a way to make it more efficient?

Upvotes: 0

Views: 58

Answers (2)

Wand Maker
Wand Maker

Reputation: 18762

Here is one more way to do this, may be not as elegant as other answer.

str = "The cat sat on the mat"
words = str.split
puts words.flat_map.with_index { |i, idx| 
    words.
        repeated_combination(idx + 1).
        select{ |*x| str[x.join(' ')]}.
        collect {|x| x.join(' ') }
}

Output

The
cat
sat
on
the
mat
The cat
cat sat
sat on
on the
the mat
The cat sat
cat sat on
sat on the
on the mat
The cat sat on
cat sat on the
sat on the mat
The cat sat on the
cat sat on the mat
The cat sat on the mat

Upvotes: 0

Stefan
Stefan

Reputation: 114188

I'd use each_cons in a loop: (although it's not any faster)

arr = %w[The cat sat on the mat]
(1..arr.size).flat_map { |i| arr.each_cons(i).map { |words| words.join(' ') } }
#=> ["The", "cat", "sat", "on", "the", "mat",
#    "The cat", "cat sat", "sat on", "on the", "the mat",
#    "The cat sat", "cat sat on", "sat on the", "on the mat",
#    "The cat sat on", "cat sat on the", "sat on the mat",
#    "The cat sat on the", "cat sat on the mat",
#    "The cat sat on the mat"]

Upvotes: 5

Related Questions