随机分布在动态数组中

时间:2016-04-17 17:39:57

标签: java arrays random

我有一个动态数组和一个Integer,其值为数组长度的3倍

Integer = array.length*3

例如,如果数组有4个单元格,那么整数值为12,分布可以是[8] [1] [2] [1],[5] [3] [0] [4],[0] ] [12] [0] [0]。

如何在数组的每个单元格之间分配Integer值?

2 个答案:

答案 0 :(得分:1)

Random r = new Random();
int max = array.length * 3;
for(int i = 0; i < max; i++) {
    array[r.nextInt(array.length)] += 1;
}

答案 1 :(得分:0)

鉴于你是一名学生,这就像家庭作业一样,我会向你展示一个带有大量注释的版本,我用另一种语言(Ruby)实现它,让你自己将它翻译成Java。 / p>

# Method to populate an array with values that sum to 3 * the array length
def populate(array)
  total = 3 * array.length    # determine the value to sum to
  # the following allocates a temporary array with one more element
  # than the input array, and populates it with random integers
  # between zero and total, inclusive
  tmp = Array.new(array.length + 1) { rand(total + 1) }
  # replace the first entry with zero, the last with total.
  # in reality, any two entries could be used, but values of
  # zero and total are critical to the algorithm
  tmp[0] = 0
  tmp[-1] = total
  # sort the temp array into ascending order
  tmp.sort!
  # since the smallest entry in tmp is zero, and the largest is total,
  # and the array is in ascending order, successive differences between
  # tmp entries will sum to total
  array.each_index { |i| array[i] = tmp[i + 1] - tmp[i] }
  # return the resulting array
  return array
end

运行时,会产生

等结果
[0, 0, 4, 8]
[3, 4, 0, 5]
[2, 1, 6, 3]

基础算法 - 生成n+1值,包括范围为[0,total]的0,n-1total随机值,排序,并找到n连续的差异 - 可以直接用任何语言实现。