You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数字10拆分为4个1-4的随机数?现有代码求和不足

Got it, let's fix this! Your current code doesn't account for the remaining sum needed to hit 10, which is why you're getting arrays that add up to less than the target. Here's a solid approach to generate valid arrays every time:

The Core Idea

We need 4 numbers, each between 1 and 4, that sum exactly to 10. The key constraint is that when picking each number, we have to leave enough room for the remaining elements to each be at least 1 (since they can't be 0) and never let any number exceed 4.

Working Code

let formation = [];
let total = 0;

// Generate the first 3 elements with controlled bounds
for (let i = 0; i < 3; i++) {
    // How many elements we still need to add after this one
    const remainingElements = 4 - i - 1;
    // Minimum value is always 1 (can't be 0)
    const minVal = 1;
    // Maximum value is the smaller of 4, or the maximum we can pick without making the remaining sum impossible
    const maxVal = Math.min(4, 10 - total - remainingElements);
    
    // Pick a random integer between minVal and maxVal inclusive
    const randomNum = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
    
    formation.push(randomNum);
    total += randomNum;
}

// The fourth element is exactly what's left to reach 10
formation.push(10 - total);

console.log(formation);
console.log('Sum:', formation.reduce((a, b) => a + b, 0)); // Will always log 10

Why This Works

  • For each of the first three elements, we calculate a safe upper bound: it can't exceed 4, and it can't be so large that the remaining elements (each needing at least 1) can't add up to the remaining sum.
  • The fourth element is automatically the perfect value to hit 10, and because we constrained the first three properly, it will always be between 1 and 4 (no need for extra checks).

Example Valid Outputs

This code will generate arrays like:

  • [2, 3, 3, 2]
  • [4, 1, 4, 1]
  • [1, 4, 3, 2]

All of which meet your requirements: 4 elements, no zeros, no values over 4, sum exactly to 10.

内容的提问来源于stack exchange,提问作者MikeHrn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:22:53