Problem
We are required to write a JavaScript function that takes in an array of exactly 4 numbers, arr, as the first argument and a target as the second argument.
Our function need to judge whether the numbers in the array arr could operated through *, /, +, -, (, ) to get the value equal to target.
For example, if the input to the function is
Input
const arr = [5, 3, 2, 1]; const target = 4;
Output
const output = true;
Output Explanation
Because we can achieve 4 like this −
(5 - 1) * (3 - 2) = 4
Example
Following is the code −
const arr = [5, 3, 2, 1]; const target = 4; const canOperate = (arr = [], target = 1) => { const isValid = x => Math.abs(x - target) < 0.0000001 const helper = (arr = []) => { if (arr.length === 1) { return isValid(arr[0]) } let valid = false for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { const nextArr = arr.filter((x, index) => index !== i && index !== j) valid = valid || helper([...nextArr, arr[i] + arr[j]]) || helper([...nextArr, arr[i] - arr[j]]) || helper([...nextArr, arr[j] - arr[i]]) || helper([...nextArr, arr[i] * arr[j]]) || helper([...nextArr, arr[i] / arr[j]]) || helper([...nextArr, arr[j] / arr[i]]) } } return valid } return helper(arr) } console.log(canOperate(arr, target));
Output
true