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