gpt4 book ai didi

javascript - 有条件的 : If all numbers in array are divisors without remainder

转载 作者:行者123 更新时间:2023-11-30 08:29:11 25 4
gpt4 key购买 nike

我的问题是:

Print all numbers from low to high. If any number being printed is divisible by any divisor number in arr, print the number + the word ¨one_match¨ If the number being printed is divisible by ALL the numbers in the array, it should output the number + “all_match”.

在下面的函数中,我似乎能够为数组中的数字之一(通过遍历数组)和基本情况(没有一个是可整除的)生成条件。我正在寻求中间情况的帮助(如果所有情况都可以整除),似乎内部循环不适合这个...额外的 for...in 并没有真正与数组相提并论...完成功能的任何想法? (或完全优化它)

function check(arr, low, high) { 
for (var i = low; i <= high; i++) {
for (var j = 0; j < arr.length; j++)
if (i % arr[j] === 0)
console.log(i + ' one_match')
// trouble here -> else if (i % arr[j] && ???)
else
console.log(i);
}
};

check([2,3],1,7);

最佳答案

您可以只计算匹配项并查看内部循环后的结果:

function check(arr, low, high) { 
for (var i = low; i <= high; i++) {
var count = 0;
for (var j = 0; j < arr.length; j++) {
if (i % arr[j] === 0) {
count++;
}
}
if (count === arr.length) {
console.log(i + ' all_match');
} else if (count > 0) {
console.log(i + ' one_match');
} else {
console.log(i);
}
}
};

check([2,3],1,7);

更简洁的变体

function check(arr, low, high) { 
for (var i = low; i <= high; i++) {
var count = arr.filter( d => !(i % d) ).length;
console.log(i + (count === arr.length ? ' all_match'
: count > 0 ? ' one_match'
: ''));
}
};

check([2,3],1,7);

关于javascript - 有条件的 : If all numbers in array are divisors without remainder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40554346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com