【问题标题】:How to divide an integer into an array of roughly equal and evenly distributed parts that sum to the original integer?如何将一个整数分成大致相等且分布均匀的部分数组,这些部分总和为原始整数?
【发布时间】:2022-11-19 20:22:39
【问题描述】:

给定一个整数n,有什么算法可以将它分成d部分的数组,其成员和原始整数n的性质大致相等,并且相当均匀分布在整个阵列?例如将 13 分成 10 个部分看起来像这样:

[1, 1, 2, 1, 1, 2, 1, 1, 2, 1]

【问题讨论】:

标签: arrays algorithm division integer-division


【解决方案1】:

一种方法是使用动态比率 (a/b) 与大值与小值 (c/r) 的比率,以确定除法后余数的分布:

function split(n, d)
{
  if(d === 0)
    return [];

  // Integer division spelled in JavaScript
  const q = Math.floor(n / d);
  const r = n % d;
  const c = d - r;
  
  let out = Array(d);
  let a = 1;
  let b = 1;
  
  for(let i = 0; i < d; i++)
  {
    // Make the ratio a/b tend towards c/r
    if((a * r) < (b * c))
    {
      a++;
      out[i] = q;
    }
    else
    {
      b++;
      out[i] = q + 1;
    }
  }
  
  // Check the array sums to n
  console.log(out, n === out.reduce((a, b) => a + b, 0));

  return out;
}

split(11, 10);
split(173, 9);
split(13, 10);
split(1773, 19);

这会产生输出:

[1, 1, 1, 1, 1, 1, 1, 1, 2, 1], true
[19, 19, 19, 20, 19, 19, 19, 20, 19], true
[1, 1, 2, 1, 1, 2, 1, 1, 2, 1], true
[93, 93, 94, 93, 93, 94, 93, 93, 94, 93, 93, 94, 93, 93, 94, 93, 93, 94, 93], true

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2014-09-06
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多