

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- Checking the validity of parentheses in JavaScript
- Finding the validity of a hex code in JavaScript
- HTML5 validity of nested tables
- Satisfiability of Equality Equations in C++
- Checking smooth sentences in JavaScript
- Checking for special type of Arrays in JavaScript
- Checking for permutation of a palindrome in JavaScript
- Checking for uniqueness of a string in JavaScript
- Checking for squared similarly of arrays in JavaScript
- Checking for particular types of matrix in JavaScript
- Checking progressive array - JavaScript
- Checking semiprime numbers - JavaScript
- Defining validity of initial password in SAP HANA
- Setting validity of a user in SAP HANA
- Checking the intensity of shuffle of an array - JavaScript
Advertisements