Finding all valid word squares in JavaScript


Word Square:

A word square consists of a set of words written out in a square grid, such that the same words can be read both horizontally and vertically.

For instance, once valid word square is −

H E A R T
E M B E R
A B U S E
R E S I N
T R E N D

We are required to write a JavaScript function that takes in an array of words. The function should return true if the array given as input forms a valid word square, false otherwise.

For example −

If the input word array is −

const arr = [
   "abcd",
   "bnrt",
   "crmy",
   "dtye"
];

Then the output should be −

const output = true;

Example

The code for this will be −

 Live Demo

const arr = [
   "abcd",
   "bnrt",
   "crm",
   "dt"
];
const findValidSquares = (arr = []) => {
   for(let i = 0; i < arr.length; i++){
      for(let j = 0; j < arr[i].length; j++){
         if(i >= arr.length || j >= arr.length || j >= arr[i].length || i >= arr[j].length){
            return false;
         };
         if(arr[i][j] !== arr[j][i]){
            return false;
         }
      }
   };
   return true;
};
console.log(findValidSquares(arr));

Output

And the output in the console will be −

true

Updated on: 27-Feb-2021

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements