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[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
raja
Published on 09-Apr-2021 08:37:06
Advertisements