첫 번째 입력으로 숫자를, 두 번째 입력으로 최대 숫자를 취하는 JavaScript 함수를 작성해야 합니다.
함수는 4개의 난수를 생성해야 하며, 합하면 첫 번째 입력으로 기능하도록 제공된 숫자와 같아야 하며 이 네 개의 숫자 중 어느 것도 두 번째 입력으로 제공된 숫자를 초과해서는 안 됩니다.
예를 들어 - 함수에 대한 인수가 -
인 경우const n = 10; const max = 4;
그런 다음
const output = [3, 2, 3, 2];
유효한 조합입니다.
숫자의 반복이 허용됩니다.
예시
이에 대한 코드는 -
const total = 10;
const max = 4;
const fillWithRandom = (max, total, len = 4) => {
let arr = new Array(len);
let sum = 0;
do {
for (let i = 0; i < len; i++) {
arr[i] = Math.random();
}
sum = arr.reduce((acc, val) => acc + val, 0);
const scale = (total − len) / sum;
arr = arr.map(val => Math.min(max, Math.round(val * scale) + 1));
sum = arr.reduce((acc, val) => acc + val, 0);
} while (sum − total);
return arr;
};
console.log(fillWithRandom(max, total)); 출력
콘솔의 출력은 -
[ 3, 3, 2, 2 ]
출력은 각 실행에서 다를 것으로 예상됩니다.