0

我需要生成一个由 8 个数字块组成的序列。块大小可以在 28 到 32 之间变化。我卡住的部分是所有块的总和必须是一个特定的数字。假设是 243。

我逐块尝试了一个循环块,其中块大小是在这些值之间随机生成的,但最后一个块在大多数情况下要么变大要么变小。我可以保持这个运行,直到我得到一些工作,但它不是那么有效。

我确信有更好的方法。感谢您的帮助 最良好的祝愿

4

1 回答 1

0

Calculate 8 blocks as you are doing at the moment. The sum of all these blocks will then be more, or less, than the desired sum.

Then, add all the blocks together and find actual sum. E.g:

blocks = randn(8,28);
actual_sum = sum(sum(blocks));
desired_sum = 243;

Then you calculate ratio that you must multiply all the values with to achieve the desired sum. E.g:

ratio = desired_sum/actual_sum;

Then you just multiply all your blocks with this ratio, and you will achieve your goal. E.g:

blocks = blocks * ratio;

This will result in values with decimals (or floats). If you want integers then just round all the values, and adjust the last block a little with the difference this created. E.g:

blocks = round(blocks,0);
diff = sum(sum(blocks)) - desired_sum;
blocks(1,1) = blocks(1,1) - diff;
if sum(sum(blocks))==desired_sum
    fprintf("It works!");
end

Disclaimer: I don't have Matlab with me, so you might need to fix some function names or so. The method behind it should be solid.

于 2018-06-05T18:20:41.557 回答