我有以下数组:
arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
在不更改值顺序的情况下,我需要在每次出现0
时将arr
细分为较小的数组,这样结果将是:
arr = [ [0, 1, 1, 2, 3, 1], [0], [0, 1] ]
如果arr
是一个字符串,我可以使用.split("0")
,然后将分隔符附加到每个子数组。对于数组,在普通 Ruby 中.split()
最有效的等价物是什么?
Enumerable#slice_before
这样做:
arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
p arr.slice_before(0).to_a
# => [[0, 1, 1, 2, 3, 1], [0], [0, 1]]
在 repl.it 上看到它:https://repl.it/FBhg
由于 ActiveSupport 在 Ruby 中定义了一个 Array#split 方法,我们可以将其用作起点:
class Array
def split(value = nil)
arr = dup
result = []
if block_given?
while (idx = arr.index { |i| yield i })
result << arr.shift(idx)
arr.shift
end
else
while (idx = arr.index(value))
result << arr.shift(idx)
arr.shift
end
end
result << arr
end
end
# then, using the above to achieve your goal:
arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
arr.split(0).map { |sub| sub.unshift(0) }
# => [[0], [0, 1, 1, 2, 3, 1], [0], [0, 1]]
请注意,算法的口头措辞(拆分和前置)是这里发生的事情,但您的预期输出是不同的(由于split
的工作方式,还有一个额外的零)。
你想在每个零之前分裂吗?为此,您可以使用 slice_before
.
是否要拆分但删除空数组?这可以通过在预置前快速compact
来完成,但您将丢失[0]
子数组。
是否要拆分但删除第一个元素(如果为空)?
你想在/0+/
上分裂吗?