# Checking validity of equations in JavaScript

JavascriptWeb DevelopmentFront End Technology

## 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 −

Live Demo

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;
const Y = item;
map[X] = map[X] || X;
map[Y] = map[Y] || Y;
len[X] = len[X] || 1;
len[Y] = len[Y] || 1;
if(item === '!'){
inValids.push([X, Y]);
}else{
console.log(validateEquations(arr));
false