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


given string:

"see spot run" 

i need return array with:

[ "see", "spot", "run", "see spot", "spot run", "see spot run" ] 

so far have:

term = "the cat sat on mat" #=> "the cat sat on 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 mat", "the cat sat on", "cat sat on the", "sat on mat", "the cat sat on the", "cat sat on mat", "the cat sat on mat"]  

this going happen lot of times, can think of way make more efficient?

i'd use each_cons in loop: (although it's not faster)

arr = %w[the cat sat on 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 mat", #    "the cat sat on", "cat sat on the", "sat on mat", #    "the cat sat on the", "cat sat on mat", #    "the cat sat on mat"] 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -