Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Complete Equation by Filling Missing Operator in JavaScript
We are required to write a JavaScript function that takes in a bunch of numbers and returns the correct sequence of operations to satisfy the equation. The operators that can be used are (+, ?, *, /, ^, %).
For example ?
Input : 5 3 8 Output : 5+3=8 Input : 9 27 3 Output : 9=27/3 Input : 5 2 25 , 1 5 2 Output : 5^2=25 , 1=5%2
For each input, there is at least one possible sequence, we are required to return at least one correct sequence.
Algorithm
The algorithm we are going to use to solve this problem is:
Use brute force approach to try random operator combinations
Replace spaces with random operators from the set (+, ?, *, /, ^, %, =)
Evaluate the resulting equation to check if it's mathematically correct
Store valid equations and avoid duplicates
Example
The code for this will be:
const arr = ["5 3 8", "9 27 3", "5 2 25", "1 5 2", "3 3 3 30"];
const findCombination = (arr = []) => {
const answers = [];
for(let i = 0; i < arr.length; i++){
const el = arr[i];
// using brute force to try solutions
for(let n = 0; n < 1000; n++){
const s = el.replace(/ /g, () =>
"+-*/^%="[Math.floor(Math.random() * 7)]);
if(eval(s.replace(/=/g, "===").replace(/\^/g, "**")) === true
&& answers.indexOf(s) === -1){
answers.push(s);
};
};
}
return answers;
};
console.log(findCombination(arr));
Output
And the output in the console will be:
[
'5+3=8',
'9=27/3',
'5^2=25',
'1=5%2',
'3=3%3^30',
'3^3+3=30',
'3+3^3=30'
]
How It Works
The function uses a brute force approach where it randomly replaces spaces with operators and checks if the resulting equation is valid. The eval() function evaluates the mathematical expression after converting = to === for comparison and ^ to ** for exponentiation in JavaScript.
Key Points
The algorithm tries up to 1000 random combinations for each input
Duplicate solutions are filtered out using
indexOf()JavaScript uses
**for exponentiation, so^is convertedThe modulo operator
%works as expected in JavaScript
Conclusion
This brute force approach effectively finds valid mathematical equations by randomly trying operator combinations. While not the most efficient method, it guarantees finding solutions when they exist.
