gpt4 book ai didi

将随机数添加或减去数组的算法,以便没有数字的差异超过 8

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:09:41 28 4
gpt4 key购买 nike

有一系列 16 个数字可以从以下数字集合 {-8,-4,0,4,8} 中随机添加,但考虑到新生成的系列不应该有任何两个数字相差超过 8。

我正在尝试一种高效的算法,该算法可以生成应在不违反约束的情况下添加的数字集。

最佳答案

如果您可以使用连续的范围,问题会稍微容易一些。这是一个用 Ruby 编写的带有大量注释的实现:

# Note that generating from the set {-8, -4, 0, 4, 8} is equivalent to
# generating integers in the range -2..2 and scaling by 4. Working with
# contiguous ranges is easier, just upscale before using or printing.

MAX_DELTA = 8 / 4 # specified maximum difference between any pair of values in scaled range
N = 16 # number of values to generate

data = [] # start with an empty array
data << rand(-2..2) # generate first (anchor) value in rescaled range
(N - 1).times do # generate remaining N-1 values by...
range_min, range_max = data.minmax # finding min & max of current set
# determine new range based on the current range + absolute constraints
new_range_min = [range_max - MAX_DELTA, -2].max
new_range_max = [range_min + MAX_DELTA, 2].min
# generate and store new value
data << rand(new_range_min..new_range_max)
end

# remap results to actual desired range
data.map! { |i| 4 * i }
# print results separated by commas.
puts data.join(', ')

这会产生如下输出:

4, -4, -4, 4, -4, 4, 0, 0, -4, -4, -4, 0, 0, 4, 4, -4

4, 8, 8, 8, 8, 4, 4, 4, 0, 4, 8, 0, 0, 0, 4, 0

关于将随机数添加或减去数组的算法,以便没有数字的差异超过 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51694428/

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