![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking validity of equations in JavaScript
Problem
We are required to write a JavaScript function that takes in an array, arr, as the first and the only argument.
The array arr consists of string equations of one of the two following kinds −
‘X ===Y’
X!==Y’
Here, X and Y can be any variables.
Our function is supposed to check whether for all the equations in the array, we can assign some number so that all the equations in the array yield true.
For example, if the input to the function is −
const arr = ['X===Y', 'Y!==Z', 'X===Z'];
Then the output should be −
const output = false;
Output Explanation:
No matter what value we choose for X, Y and Z. All three equations can never be satisfied.
Example
The code for this will be −
const arr = ['X===Y', 'Y!==Z', 'X===Z']; const validateEquations = (arr = []) => { const map = {}; const len = {}; const inValids = []; const find = (item) => { while(map[item] && item !== map[item]){ map[item] = map[map[item]]; item = map[item]; }; return item; }; const add = (a, b) => { const first = find(a); const second = find(b); if(first === second){ return; }; if(len[first] < len[second]){ map[first] = second; len[second] += len[first]; }else{ map[second] = first; len[first] += len[second]; } } arr.forEach((item) => { const X = item[0]; const Y = item[4]; map[X] = map[X] || X; map[Y] = map[Y] || Y; len[X] = len[X] || 1; len[Y] = len[Y] || 1; if(item[1] === '!'){ inValids.push([X, Y]); }else{ add(X, Y); }; }); return inValids.every(([a, b]) => find(a) !== find(b)) }; console.log(validateEquations(arr));
Output
And the output in the console will be −
false
Advertisements