gpt4 book ai didi

Ruby 数组迭代和变异

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:26 25 4
gpt4 key购买 nike

我有一个类似对象的数组,其属性 a 可以有值 bc。该数组可以被视为行的集合,其中数组中的每对项目代表一行。为了简单起见,我刚刚列出了属性 a 的值,示例:

array = [c, b, b, c, c, c, b]
# array[0], array[1] is one row (c, b)
# array[2], array[3] is another (b, c)
# ...

不能只有 (b, b) 行,如果是这种情况,则必须将其中一个 b 值交换为最接近的 >c 数组中的值。如果没有更多的 c 值,则只要 b 值留在数组末尾,数组就是有效的。

数组的最后行可以只包含一个值,即。 e. (b, ).

例子:

 array = [b, c, b, b, c, b, b, b, c, b, b, c, c]
# becomes
array = [b, c, b, c, b, b, b, b, c, b, b, c, c]
array = [b, c, b, c, b, c, b, b, b, b, b, c, c]
array = [b, c, b, c, b, c, b, c, b, b, b, b, c]
array = [b, c, b, c, b, c, b, c, b, c, b, b, b]
# rows: (b, c), (b, c), (b, c), (b, c), (b, c), (b, b,), (b, )

这是我想出的解决方案,我不太喜欢(因为它非常命令和冗长)

while true do
cand = nil
array.each_slice(2) do |item, nxt|
return if nxt.nil?
# pseudo-code: assume b? returns true for a == b
next unless item.b? && nxt.b?
cand = nxt
break
end
swap_cand = array.slice(array.index(cand), array.length).reject{ |item| item.popular? }.first
return if swap_cand.nil?
old_index, new_index = array.index(cand), array.index(swap_cand)
array[old_index], array[new_index] = array[new_index], array[old_index]
end

我一直遇到的一个问题是我无法在遍历数组时改变数组,这需要两个循环。

编辑 根据@7stud 的建议清理了一些中断语句。

最佳答案

Enumerable#chunk非常适合这个问题。

代码

def valid?(arr, b)
arr.chunk { |e| e }
.map(&:last)[0..-2]
.select { |e| e.first == b }
.max_by(&:size)
.size <= 2
end

示例

b = 0
c = 1
valid?([c, b, b, c, b, b, b], b) #=> true
valid?([c, b, b, b, c, c, b], b) #=> false

解释

b = 0
c = 1
arr = [c, b, b, c, b, b, b]
#=> [1, 0, 0, 1, 0, 0, 0]
enum = arr.chunk { |e| e }
#=> #<Enumerator: #<Enumerator::Generator:0x0000010205aa70>:each>
enum.to_a # Let's examine the elements of `enum`
#=> [[1, [1]], [0, [0, 0]], [1, [1]], [0, [0, 0, 0]]]
a = enum.map(&:last)
#=> [[1], [0, 0], [1], [0, 0, 0]]
d = a[0..-2] # disregard last value, which may or may not be an array of `b`'s
#=> [[1], [0, 0], [1]]
e = d.select { |e| e.first == b }
#=> [[0, 0]]
f = e.max_by(&:size)
#=> [0, 0]
g = f.size
#=> 2
g <= 2
#=> true

关于Ruby 数组迭代和变异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25981311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com