有一系列16个数字,可以从以下一组数字{-8,-4,0,4,8}中随机添加,但要考虑到新生成的系列不应有任何两个数字相差超过8。
我正在尝试一种高效的算法,该算法可以生成应该添加的数字集而不违反约束。
答案 0 :(得分:1)
如果可以使用连续范围,则此问题会稍微容易一些。这是一个在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
答案 1 :(得分:0)
此方面的内容:
const numbers = [-8, -4, 0 , 4, 8];
function getRandomNumber() {
return numbers[Math.floor(Math.random() * numbers.length)]
}
function difference(a, b) {
return Math.abs(a - b);
}
function calculateNewArray() {
const values = [];
while (values.length < 16) {
const random = getRandomNumber();
// add any number the first iteration
if (values.length === 0) values.push(random);
if (difference(values[values.length -1], random) < 9) {
values.push(random)
}
}
return values;
}
calculateNewArray()
// [0, 0, 4, -4, 0, -4, 4, -4, 0, -4, -4, -4, -4, -8, -8, -4]
我根本没有测试它,感谢任何反馈。