I aim to cross-reference words within a matrix, yet I struggle to pinpoint every word in all eight directions in the matrix

I have a matrix of characters arranged in such a way that they form meaningful words. Additionally, I also have an array of words with their respective starting and ending positions on the matrix. My goal is to extract an array of strings by combining all the characters at the specified positions. Below is the code snippet:

function findWords(words, matrix) {
  const foundWords = [];

  for (let i = 0; i < words.length; i++) {
    const word = words[i].word;
    const startX = words[i].startX;
    const startY = words[i].startY;
    const endX = words[i].endX;
    const endY = words[i].endY;

    let wordIndex = 0;
    let wordFound = true;

    // Horizontal Check
    if (startX === endX) {
      if (startY > endY) {
        for (let y = endY; y <= startY; y++) {
          if (matrix[startX][y] !== word[wordIndex]) {
            wordFound = false;
            break;
          }
          wordIndex++;
        }
      } else {
        for (let y = startY; y <= endY; y++) {
          if (matrix[startX][y] !== word[wordIndex]) {
            wordFound = false;
            break;
          }
          wordIndex++;
        }
      }
    } 
    // Vertical Check
    else if (startY === endY) {
      if (startX > endX) {
        for (let x = endX; x <= startX; x++) {
          if (matrix[x][startY] !== word[wordIndex]) {
            wordFound = false;
            break;
          }
          wordIndex++;
        }
      } else {
        for (let x = startX; x <= endX; x++) {
          if (matrix[x][startY] !== word[wordIndex]) {
            wordFound = false;
            break;
          }
          wordIndex++;
        }
      }
    } 

    // Diagonal Check
    else if (startX > endX) {
      for (let x = startX, y = startY; x >= endX; x--, y--) {
        if (matrix[x][y] !== word[wordIndex]) {
          wordFound = false;
          break;
        }
        wordIndex++;
      }
    } else {
      for (let x = startX, y = startY; x <= endX; x++, y--) {
        if (matrix[x][y] !== word[wordIndex]) {
          wordFound = false;
          break;
        }
        wordIndex++;
      }
    }

    if (wordFound) {
      foundWords.push(word);
    }
  }
  return foundWords;
}

const solve = [
  { word: "butter", startX: 3, startY: 6, endX: 3, endY: 1 },
  { word: "chicken", startX: 8, startY: 2, endX: 2, endY: 2 },
  { word: "coconut", startX: 9, startY: 10, endX: 3, endY: 4 },
  { word: "gremilins", startX: 1, startY: 0, endX: 9, endY: 8 },
  { word: "ham", startX: 7, startY: 2, endX: 5, endY: 0 },
  { word: "iceland", startX: 10, startY: 1, endX: 4, endY: 1 },
];

const matrix = [
  ["r", "g", "j", "t", "o", "m", "a", "t", "o", "w", "t"],
  ["z", "a", "r", "r", "d", "n", "a", "l", "e", "c", "i"],
  ["e", "m", "n", "e", "k", "c", "i", "h", "c", "f", "b"],
  ["r", "c", "t", "t", "m", "a", "t", "v", "a", "a", "b"],
  ["o", "z", "q", "t", "t", "i", "a", "o", "u", "i", "a"],
  ["p", "j", "z", "u", "u", "e", "l", "u", "z", "b", "r"],
  ["a", "o", "e", "b", "r", "n", "y", "i", "z", "r", "g"],
  ["g", "n", "n", "o", "h", "w", "o", "h", "n", "e", "a"],
  ["n", "q", "k", "u", "w", "o", "h", "c", "y", "s", "p"],
  ["i", "j", "l", "a", "g", "u", "t", "r", "o", "p", "n"],
  ["s", "h", "y", "s", "a", "n", "d", "w", "i", "c", "h"],
];

console.log(findWords(solve, matrix));

The current output only lists some of the found words. But all the provided words are present in the matrix.

Answer №1

It seems there might be a bug lurking within your code, but its exact location is still unclear. Here is a suggested starting point for troubleshooting:

function extractWord(matrix, startX, startY, endX, endY) {
    const xDir = Math.sign(endX - startX); // 1, -1, or 0
    const yDir = Math.sign(endY - startY);
    let word = '';
    for (let x = startX, y = startY;
         (xDir === 1 ? x <= endX : x >= endX) &&
         (yDir === 1 ? y <= endY : y >= endY);
         x += xDir, y += yDir
    ) {
        word += matrix[y][x];
    }
    return word;
}

const matrix = [["r", "g", "j", "t", "o", "m", "a", "t", "o", "w", "t"],["z", "a", "r", "r", "d", "n", "a", "l", "e", "c", "i"],["e", "m", "n", "e", "k", "c", "i", "h", "c", "f", "b"],["r", "c", "t", "t", "m", "a", "t", "v", "a", "a", "b"],["o", "z", "q", "t", "t", "i", "a", "o", "u", "i", "a"],["p", "j", "z", "u", "u", "e", "l", "u", "z", "b", "r"],["a", "o", "e", "b", "r", "n", "y", "i", "z", "r", "g"],["g", "n", "n", "o", "h", "w", "o", "h", "n", "e", "a"],["n", "q", "k", "u", "w", "o", "h", "c", "y", "s", "p"],["i", "j", "l", "a", "g", "u", "t", "r", "o", "p", "n"],["s", "h", "y", "s", "a", "n", "d", "w", "i", "c", "h"]];
const solve = [{ word: "butter", startX: 3, startY: 6, endX: 3, endY: 1 },{ word: "chicken", startX: 8, startY: 2, endX: 2, endY: 2 },{ word: "coconut", startX: 9, startY: 10, endX: 3, endY: 4 },{ word: "gremilins", startX: 1, startY: 0, endX: 9, endY: 8 },{ word: "ham", startX: 7, startY: 2, endX: 5, endY: 0 },{ word: "iceland", startX: 10, startY: 1, endX: 4, endY: 1 },{ word: "italy", startX: 6, startY: 2, endX: 6, endY: 6 },{ word: "korea", startX: 2, startY: 8, endX: 6, endY: 4 },{ word: "portugal", startX: 9, startY: 9, endX: 2, endY: 9 },{ word: "psycho", startX: 10, startY: 8, endX: 5, endY: 8 },{ word: "rabbit", startX: 10, startY: 5, endX: 10, endY: 0 },{ word: "sandwich", startX: 3, startY: 10, endX: 10, endY: 10 },{ word: "serbia", startX: 9, startY: 8, endX: 9, endY: 3 },{ word: "singapore", startX: 0, startY: 10, endX: 0, endY: 2 },{ word: "tomato", startX: 3, startY: 0, endX: 8, endY: 0 }];

console.log(solve.map(s => extractWord(matrix, s.startX, s.startY, s.endX, s.endY)));

Answer №2

To streamline your method, consider simplifying the approach by focusing on just the starting point and direction. Whether it's horizontal, vertical, or diagonal becomes inconsequential in the grand scheme of things.

function findWords(words, matrix) {
  return words.filter(({ word, startX, startY, endX, endY }) => {
    const vx = Math.sign(endX - startX);
    const vy = Math.sign(endY - startY);

    return [...word].every((char, i) => char === matrix[startY + i * vy][startX + i * vx]);
  }).map(elm => elm.word);
}

const solve = [
  { word: "butter", startX: 3, startY: 6, endX: 3, endY: 1 },
  { word: "chicken", startX: 8, startY: 2, endX: 2, endY: 2 },
  { word: "coconut", startX: 9, startY: 10, endX: 3, endY: 4 },
  { word: "gremilins", startX: 1, startY: 0, endX: 9, endY: 8 },
  { word: "ham", startX: 7, startY: 2, endX: 5, endY: 0 },
  { word: "iceland", startX: 10, startY: 1, endX: 4, endY: 1 },
  { word: "italy", startX: 6, startY: 2, endX: 6, endY: 6 },
  { word: "korea", startX: 2, startY: 8, endX: 6, endY: 4 },
  { word: "portugal", startX: 9, startY: 9, endX: 2, endY: 9 },
  { word: "psycho", startX: 10, startY: 8, endX: 5, endY: 8 },
  { word: "rabbit", startX: 10, startY: 5, endX: 10, endY: 0 },
  { word: "sandwich", startX: 3, startY: 10, endX: 10, endY: 10</answer2>
<exanswer2><div class="answer" i="75406445" l="4.0" c="1675986204" a="VGhvbWFz" ai="6567275">
<p>You're overcomplicating things a bit. All you need is the start point and the direction, then horizontal, vertical, diagonal become all the same.</p>
<p><div>
<div>
<pre class="lang-js"><code>function findWords(words, matrix) {
  return words.filter(({ word, startX, startY, endX, endY }) => {
    const vx = Math.sign(endX - startX);
    const vy = Math.sign(endY - startY);

    return [...word].every((char, i) => char === matrix[startY + i * vy][startX + i * vx]);
  }).map(elm => elm.word);
}

const solve = [
  { word: "butter", startX: 3, startY: 6, endX: 3, endY: 1 },
  { word: "chicken", startX: 8, startY: 2, endX: 2, endY: 2 },
  { word: "coconut", startX: 9, startY: 10, endX: 3, endY: 4 },
  { word: "gremilins", startX: 1, startY: 0, endX: 9, endY: 8 },
  { word: "ham", startX: 7, startY: 2, endX: 5, endY: 0 },
  { word: "iceland", startX: 10, startY: 1, endX: 4, endY: 1 },
  { word: "italy", startX: 6, startY: 2, endX: 6, endY: 6 },
  { word: "korea", startX: 2, startY: 8, endX: 6, endY: 4 },
  { word: "portugal", startX: 9, startY: 9, endX: 2, endY: 9 },
  { word: "psycho", startX: 10, startY: 8, endX: 5, endY: 8 },
  { word: "rabbit", startX: 10, startY: 5, endX: 10, endY: 0 },
  { word: "sandwich", startX: 3, startY: 10, endX: 10, endY: 10 },
  { word: "serbia", startX: 9, startY: 8, endX: 9, endY: 3 },
  { word: "singapore", startX: 0, startY: 10, endX: 0, endY: 2 },
  { word: "tomato", startX: 3, startY: 0, endX: 8, endY: 0 },
];

const matrix = [
  ["r", "g", "j", "t", "o", "m", "a", "t", "o", "w", "t"],
  ["z", "a", "r", "r", "d", "n", "a", "l", "e", "c", "i"],
  ["e", "m", "n", "e", "k", "c", "i", "h", "c", "f", "b"],
  ["r", "c", "t", "t", "m", "a", "t", "v", "a", "a", "b"],
  ["o", "z", "q", "t", "t", "i", "a", "o", "u", "i", "a"],
  ["p", "j", "z", "u", "u", "e", "l", "u", "z", "b", "r"],
  ["a", "o", "e", "b", "r", "n", "y", "i", "z", "r", "g"],
  ["g", "n", "n", "o", "h", "w", "o", "h", "n", "e", "a"],
  ["n", "q", "k", "u", "w", "o", "h", "c", "y", "s", "p"],
  ["i", "j", "l", "a", "g", "u", "t", "r", "o", "p", "n"],
  ["s", "h", "y", "s", "a", "n", "d", "w", "i", "c", "h"],
];

console.log(findWords(solve, matrix));
.as-console-wrapper{top:0; max-height:100%!important}

Assuming that the data in solve is internally consistent, there might not be a need to scrutinize if factors like endX-startX align with the word length or if the points adhere to the 8 directional constraints, such as moving 2 right and 8 down with a 5-letter word.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to display notifications when the user is not actively browsing the website?

How can websites display notifications even when the user is not actively on the site? Take Facebook messenger, for instance. Even with the page closed, notifications still pop up. The same goes for Twitter, which also sends push notifications. I ...

Converting a JSON Array Without Member Names into a C# Object

I am trying to find a way to deserialize an array (without keys) into a C# object. I have seen some similar posts but haven't quite found what I need, so I am reaching out for help. Do I need to create a custom deserialization method or is there some ...

The ng-switch function is not generating the desired code output

In my Ionic app, I have the following code snippet that I am currently viewing with ionic serve. However, when the initial ng-switch statement triggers... <span ng-switch="post.enclosure"> <span ng-switch-when="[]"> <p>def&l ...

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

You can use HTML tags within a script tag for added flexibility and

I'm working on incorporating this into a dynamic script using data from an XML file (aiming for 50% to be dynamic). <div class="progress-bar progress-bar-danger" data-progress-animation="50%" data-appear-animation-delay="20"> It currently func ...

Unable to dynamically append items to Owl Carousel using JavaScript

I am currently working on adding items dynamically to an Owl carousel. This is how I am approaching it: HTML <div id="avatar-carousel" class="owl-carousel lesson-carousel"> <div class="item item-logo"& ...

Leveraging the power of LocalStorage in Ionic 2

Trying to collect data from two text fields and store it using LocalStorage has proven tricky. Below is the code I have set up, but unfortunately it's not functioning as expected. Can you provide guidance on how to resolve this issue? In page1.html ...

Looking for a way to prevent anonymous functions in jQuery using Greasemonkey?

Is there a way to prevent the execution of this particular jquery function? I've tried various scripts and even wrote my own, but nothing seems to work. $(document).ready(function () { $(window).on('beforeunload', function() { re ...

Oops! The Route.post() function is looking for a callback function, but instead, it received an [object Object

Looking to integrate a password reset feature in my web app, but encountering the error mentioned in the title. Here's a snippet of my code: main.js: const router = express.Router(); const AsyncNewPassword = require('./controller/asyncnewpasswor ...

Using a form tag within a table in HTML5

Can someone help me figure out how to integrate a form with the "Get" method into a table? The table includes a text field, and upon submitting the form, it should initiate validation. The validation process currently works correctly, however, when submi ...

What is the best place for organizing AngularJS model logic?

In my app, I work with Shape POCO objects that are retrieved from an AngularJS ShapeService. These shapes have properties like width and height, and can be configured to maintain their aspect ratio. When one dimension changes, the other needs to be automat ...

Customize the CSS for material-ui buttons or create a new style altogether

Looking to customize the background color of a material UI RaisedButton, I have encountered a challenge. This is what I currently have: const style = { backgroundColor: 'green' }; export default class CreateLinksave extends React.Component { ...

What is the best way to input an argument into my Javascript code using the command line?

Whenever I run my JavaScript file called "login.js" from the command line using "node login.js", I find it necessary to manually edit the URL inside the file if I want to change it. It would be more convenient for me if I could pass the URL as a command l ...

Ensure that jquery.load is executed before the HTML content is loaded

Recently, I encountered a situation where I had a bootstrap navbar stored in a separate file, specifically named navbar.html. I utilized Jquery.load() to load this navbar into my HTML page. At the bottom of my HTML page, I included the following code: &l ...

What steps do I need to take to retrieve the passed slug in my API (slug=${params.slug})?

Is there a way for me to retrieve the passed slug in my API (slug=${params.slug}) while using the vercel AI SDK? const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({ api: `/api/conversation?slug=${params.slug ...

What is the best way to change the date format from "yyyy-MM-dd" in a JavaScript file to "dd/MM/yyyy" and "MM/dd/yyyy" formats in an HTML file?

Is there a way to transform the date string "2020-08-02" from a JavaScript file into the formats "08/02/2020" and "02/08/2020" in an html file, without relying on the new Date() function in JavaScript? I would greatly appreciate any assistance with this t ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

Transforming jQuery into classic JavaScript traditions

I want to convert the code below into pure JavaScript. document.addEventListener('click', function(event) { if (event.target.classList.contains('savedPlayer')) { event.preventDefault(); let searchText = event.target.textCon ...

Update the span's content according to the user's input

Is it possible to update the value of a span to match that of an input field in HTML? HTML: <p style='font-size:150%'> Hey friend, I am <span id='name_display'>Anonymous</span>, I'd like to invite you to..... &l ...