
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 operator 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.
The algorithm we are going to use to solve this problem is −
Firstly, we choose the bigger number on one of the sides like in 1 4 7 it would be 7
Then we put an equal to facing the middle. Like 1 4 7 it would be 1 4=7
Lastly, we solve the equation
If that doesn't work, we try the other number
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' ]
Advertisements