How can we determine if a 2D array contains a specific string using javascript?

I am currently working on a script to locate the horizontalWord string within a two-dimensional array. While my function for finding verticalWord strings is running smoothly, I am encountering some difficulties with the horizontalWord string. If you have any suggestions or solutions, please do not hesitate to share them.

 let matrix = [
    [0, 'r', 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    ['a', 'p', 'p', 'l', 'e'],
    [0, 0, 0, 0, 0]
]

function isInMatrix(matrix, word) {

  for (let j = 0; j < matrix[0].length; j++) {

    let verticalWord = ''
    let horizontalWord = ''

    for (let i = 0; i < matrix.length; i++) {
      verticalWord += matrix[i][j]
    }

    for (let k = 0; k < matrix[0].length; k++) {
              horizontalWord += matrix[j][k]
    }

    if ((verticalWord.includes(word)) ||
      (verticalWord.split('').reverse().join('').includes(word)) ||
      (horizontalWord.includes(word)) ||
      (horizontalWord.split('').reverse().join('').includes(word))) return true
  }
  return false
}

console.log(isInMatrix(matrix, 'apple'))

Answer №1

It seems like your loop is not iterating through the entire matrix, you are only checking the first 5 rows.

for (let i = 0; i < matrix.length; i++) {

Instead of

(let j = 0; j < matrix[0].length; j++)
, try using
(let j = 0; j < matrix.length; j++)
.

Answer №2

To find the transpose of a matrix, you can utilize nested map functions for efficient computation.

After obtaining the transpose, verify if any of the inner arrays contain a specific word by utilizing some, join, and includes. This comparison should be performed horizontally and vertically on both the original matrix and its transpose.

let input = [
  [0, 'r', 0, 0, 0, 0, 0],
  [0, 'e', 0, 0, 0, 0, 0],
  [0, 'd', 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 'a', 'p', 'p', 'l', 'e', 0]
]

function isInArray(matrix, word) {
  let transpose = matrix[0].map((a, i) => matrix.map(b => b[i]));

  return matrix.some(a => a.join('').includes(word)) 
        || transpose.some(a => a.join('').includes(word))
}

console.log(isInArray(input, "apple"))
console.log(isInArray(input, "red"))
console.log(isInArray(input, "orange"))

Answer №3

function checkBoard(board, term) {
    if (term === '') return false;
    if (board.length < 1 || board[0].length < 1) return false;

    const startingPoints = getStartingPoints(board, term[0]);
    if (startingPoints.length < 1) return false;
    for (let point of startingPoints) {
        if (explorePath(board, term.slice(1), point, [])) return true;
    }
    return false;
}

function explorePath(B, T, P, L) {
    L.push(P.join(':'));
    if (!T) return true;
    let row = P[0], col = P[1], rows = B.length, cols = B[0].length;
    const nextPoints = [];
    if (row-1 >= 0 && B[row-1][col] === T[0] && !L.includes((row-1)+':'+col)) nextPoints.push([row-1, col]);

    if (row+1 < rows && B[row+1][col] === T[0] && !L.includes((row+1)+':'+col)) nextPoints.push([row+1, col]);

    if (col-1 >= 0 && B[row][col-1] === T[0] && !L.includes(row+':'+(col-1))) nextPoints.push([row, col-1]);

    if (col+1 < cols && B[row][col+1] === T[0] && !L.includes(row+':'+(col+1))) nextPoints.push([row, col+1]);

    for (let nextPoint of nextPoints) {
        const found = explorePath(B, T.slice(1), nextPoint, [...L]);
        if (found) {
            return true;
        }
    }
    return false;
}

function getStartingPoints(board, char) {
    const points = [];
    for (let r = 0; r < board.length; r++) {
        let index = -1;
        while(true) {
            index = board[r].indexOf(char, index+1);
            if (index >= 0) points.push([r, index]);
            else break;
        }
    }
    return points;
}

board = [ ['A','B','C','E'],['S','F','C','S'],['A','D','E','E'] ];
words = ["ABCCED", "SEE", "ABCB"];
// true, true, false
for (let word of words) console.log(checkBoard(board, word));
board = [ ["A","B","C","E"],["S","F","E","S"],["A","D","E","E"] ];
word = "ABCESEEEFS";
console.log(checkBoard(board, word));   // true

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

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

Is there a way to keep a JS script running even after navigating away in the Google Chrome console?

Assume there is a basic script available var x = 0; run(); function run() { console.log(x++); setTimeout(run, 1000); } If I input it into the Google Chrome console. How can I keep it running even after navigating to another page (continuously d ...

Design a function that accepts a string parameter and outputs an encoded (h4ck3r 5p34k) rendition of the input string

function convertToHacker(str){ for (var i=0; i <str.length;i++) { if (str[i]==="a") {str=str.replace("a","4")} else if (str[i]==="e") {str=str.replace("e","3")} else if (str[i]==="i") {str=str.replace("i","1") ...

Is There a Lack of 'Contains' Support in JavaScript's ScriptEngine?

Below is some code that I am working with. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("[1, 2, 3].contains(1)"); However, when I run the code, it throws the following e ...

Exploring Vue.js: Navigating Through an Array of Images Nested Within Another Array

I am looking to showcase images stored in an array called "image" within another array named product. Essentially, if a product has an array of 3 images, I want to display all 3 images, and so on. Here is the code snippet: <template> <div c ...

Attempting to transmit a value from an ASP.NET JavaScript script to my C# Code Behind function by utilizing a Hidden Field

I am encountering an issue with my ASP.NET Web site where I cannot retrieve a value from a JavaScript function in my C# Code Behind. The value is passed as an argument from an ASP.NET Hidden Field. In my ASP.NET and JavaScript code, I have defined a Hidde ...

Scanner for a two-dimensional array of size n by n

import java.util.Scanner; class Test1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[][] num = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < 0; j+ ...

What is the solution for handling undefined errors that occur when employing d3.select(this) within a Vue methods hook?

Currently, I am in the process of transferring d3 graphs from another project to my personal Vue-based project. Most aspects are functioning as expected, except for aligning labels in the arcs of a pie chart using the arc.centroid(d) method. Two errors kee ...

Tips for arranging, categorizing, and separating the array in alphabetical order using Angular 2+

I am looking to organize the buttons' content alphabetically into groups A-H, I-Q, and R-Z. The code I'm using is in Angular2+. https://i.sstatic.net/pPCBO.png My array: this.dropdownList = [ { item_text: 'Organisation' }, ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Steps for transforming Dec 2 1991 12:00AM into 12/02/1991

const dobString = "Dec 02 1991 12:00"; const newDate = dobString.substring(0, dobString.length - 6); const birthDate = $filter('date')(new Date(newDate), 'mm/dd/yyyy'); ...

Having trouble with babel-loader, encountering an issue with UglifyJS (ES6) causing errors

Recently, I integrated the FlipClockJs vue component into my project and it was functioning properly during development when I executed yarn encore dev However, upon running yarn encore production An error cropped up as follows: ERROR Failed to ...

The most recent axios request yielded a null response

I needed to retrieve the current weather conditions of a specific location, so I decided to utilize two different APIs. The first one being Mapbox, which helped me convert the place name to geo-coordinates. The second API I used was Accuweather. Additional ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

Discovering the method to retrieve a previous month's date within a VueJs application using Javascript

Can someone guide me on how to retrieve the date of the past month using Vue? This is the code I currently have: import SomeTable from "./table/SomeTable"; export default { name: "Cabinets", components: {SomeTable}, data() { return { ...

The function `map` cannot be applied to `this.state.[object]`

It seems like I might be overlooking a simple mistake, but I keep encountering this.state.iata.map is not a function , even though I have bound the context to all functions where I need to access that state. Additionally, the iata state is an array, s ...

When processing a series of input values, a C function executes successfully, but unexpectedly encounters a Segmentation Fault error with a value of

I am struggling to find a unique non-zero intersection between two sets. While my program works for some arrays, it encounters a segmentation fault for others. I have been attempting to identify the issue without success. Any assistance would be greatly ap ...

Adding child arrays to a parent array in Angular 8 using push method

Upon filtering the data, the response obtained inside the findChildrens function is as follows: My expectation now is that if the object length of this.newRegion is greater than 1, then merge the children of the second object into the parent object's ...

Simple guide on how to use AJAX (without jQuery) and PHP to count the number of records

As a novice programmer, I am attempting to tally the number of records in a table. Despite perusing various code snippets, I am unable to seamlessly integrate them to pass the PHP result to my javascript code. Here is the current state of my code: showsca ...

AngularJS - Executing code after the entire application has finished loading

Being new to AngularJs (1.6), I am just starting out and may not have all the right questions yet. I have recently begun working on a project built with AngularJS 1.6. My current task involves running a script on specific routes. For now, let's cons ...