Declarations and operators issue

Viewed 61

Hey guys how can I reorder the declaration of operators such that the result is 0 when logged??

numbers = [23, 12, 71, 10]
operators = [
(a, b) => a + b,
(a, b) => a / b,
(a, b) => a * b,
(a, b) => a - b
];
var result = 1;
operators.forEach(function(op) {
result = Math.floor(op(result, numbers[operators.indexOf(op)]))
});
console.log(result);

I'm halfway there but something just isn't clicking??

Cheers

2 Answers

Looks like this works!

numbers = [23, 12, 71, 10]
operators = [
  (a, b) => a + b,
  (a, b) => a - b,
  (a, b) => a / b,
  (a, b) => a * b
];

result = 1;
operators.forEach(function(op) {
result = Math.floor(op(result, numbers[operators.indexOf(op)]))
});
console.log(result);

I brute-forced this ordering to find it -- while result doesn't equal 0, shuffle operators, set result back to 1, and run the forEach, over and over, until result = 0. Here's the code to do it:

// From https://www.w3docs.com/snippets/javascript/how-to-randomize-shuffle-a-javascript-array.html
function shuffleArray(array) {
  let curId = array.length;
  // There remain elements to shuffle
  while (0 !== curId) {
    // Pick a remaining element
    let randId = Math.floor(Math.random() * curId);
    curId -= 1;
    // Swap it with the current element.
    let tmp = array[curId];
    array[curId] = array[randId];
    array[randId] = tmp;
  }
  return array;
}

numbers = [23, 12, 71, 10]
operators = [
  (a, b) => a + b,
  (a, b) => a - b,
  (a, b) => a / b,
  (a, b) => a * b
];

let result = 1;

while (result != 0) {
  result = 1;
  operators = shuffleArray(operators);
  operators.forEach(function(op) {
    result = Math.floor(op(result, numbers[operators.indexOf(op)]))
  });
  console.log(result);
}

console.log(operators);

Try to add this code line.

method = ['+','/','*','-']
result = method[operators.indexOf(op)]

Full correct code.

numbers = [23, 12, 71, 10]
method = ['+','/','*','-']
operators = [
(a, b) => a + b,
(a, b) => a / b,
(a, b) => a * b,
(a, b) => a - b
];
var ch = '';
var res = 1
operators.forEach(function(op) {
   res = Math.floor(op(res, numbers[operators.indexOf(op)]))
   if( res == 0) {
       ch = method[operators.indexOf(op)]
   }
});
console.log(res);
console.log(ch);

Related