Zach_is_my_name Zach_is_my_name - 24 days ago 9
Javascript Question

Conditional: If all numbers in array are divisors without remainder

My problem states:


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”.


In the function below, I seem to be able to produce conditions for one of the numbers in the array (by iterating through the array) and the base case (none are evenly divisible). I'm seeking help with the middle case (if all are divisible), it seems the inside loop is not appropriate for this... an additional
for...in
doesn't really jibe with arrays... any ideas to complete the function? (Or optimize it entirely)

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);

Answer

You could just count the matches and see what you have after the inner loop:

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);

A more condensed variant

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);

Comments