gpt4 book ai didi

ruby - 如何在避免每个切片中出现重复值的同时对数组进行切片?

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:50 24 4
gpt4 key购买 nike

假设我有这个数组:

a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11]

a.each_slice(2).to_a 将生成对,但这些对将包含非唯一值,如 [3,3]。所以我想我正在寻找某种 unique_each_slice 方法。

我想要的是能够继续洗牌这个数组,直到我有一个独特的 2 对(不一定是 2,可以是任何东西),就像这样(以 2 为例) :

[3, 1, 3, 7, 6, 3, 4, 5, 8, 3, 9, 3, 2, 3, 6, 3, 3, 11, 10, 3]

如果你在这个数组上执行 each_slice(2),你会得到唯一的对:

[[3, 1], [3, 7], [6, 3], [4, 5], [8, 3], [9, 3], [2, 3], [6, 3], [3, 11], [10, 3]]

与原来的相比:

[[1, 2], [3, 3], [3, 3], [3, 3], [3, 3], [3, 4], [5, 6], [6, 7], [8, 9], [10, 11]]

每对都有非唯一对,比如 [3,3]

另一个例子,假设我有:

a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11,12,13,14,15,16,17]

现在,假设有一些函数 a.unique_slices_of(3),我会得到:

[[4, 16, 3], [1, 9, 3], [3, 6, 17], [3, 6, 10], [15, 3, 2], [3, 8, 12], [11, 3, 14], [7, 13, 3], [3, 5]]

“唯一切片”是指相同数字不会重复两次的切片:[1,2,3] 是唯一切片,[3,1,3] 不是。

到目前为止,我使用了以下方法,它似乎需要多次迭代才能使事情正确:

class Array
def unique_slices_of!(slices)
loop do
unique = true
self.each_slice(slices) do |slice|
if slice != slice.uniq
self.shuffle!
unique = false # so we know whether to loop again
break
end
end
break if unique # if unique didn't change, that means all slices were equal
if unique == false then unique == true end # reset and start again
end
self
end
end

我的代码的主要问题是 a) 我认为我没有使用一些惯用的 Ruby 方法来将这个过程缩短一半或更多。 b) 如果数组不能包含唯一的切片,则无限循环的可能性。我可能需要在这里使用一些组合理论,但我不确定如何使用。

最佳答案

a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11]

您可以通过以下方式测试切片是否“唯一”:

a.each_slice(2).all?{|x| x == x.uniq}

所以现在你只需洗牌,直到得到你想要的:

a.shuffle! until a.each_slice(2).all?{|x| x == x.uniq}

避免无限循环的最简单方法是使用timeout:

require 'timeout'
# raise an error if it takes more than 1 second
timeout(1){ a.shuffle! until a.each_slice(3).all?{|x| x == x.uniq} }

关于ruby - 如何在避免每个切片中出现重复值的同时对数组进行切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201819/

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