给出字符串:
"See Spot Run"
我需要返回一个数组:
[ "See", "Spot", "run", "See Spot", "Spot run", "See Spot Run" ]
到目前为止,我有:
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"]
这种情况会发生很多次,所以你能想出一种提高效率的方法吗?
答案 0 :(得分:5)
我在循环中使用each_cons
:(虽然它没有更快)
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"]
答案 1 :(得分:0)
这是另外一种方法,可能不如其他答案那么优雅。
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(' ') }
}
输出
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