What is the best method for verifying a specific condition in every element of a 2D array?

:) I'm in the process of developing a maze using JS and P5, which involves utilizing a two-dimensional array filled with numbers 0-8. Specifically, 0 represents empty spaces, 1 denotes walls, 2 signifies the character you control, 3 marks the exit point, and 4-8 represent items that appear randomly. To successfully navigate through the maze and reach the exit (positioned at 3), all items must be collected. This is achieved by changing the value of locations containing items back to 0 upon interaction. Therefore, for the player to exit the maze, every value within the array should be less than 4. At this stage, I am seeking assistance on how to check if this condition is met.

I initially attempted to use the "every()" method, but it seems this only functions correctly with standard arrays. My assumption now is that I require a for loop to accomplish this task; however, I lack clarity on how to execute it properly. This is where I could benefit from some guidance!

The configuration of my maze comprises 18 rows and columns, exemplified by the following layout:

let maze = [
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,2,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,1,0,0,0,3],
    [1,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,0,1]
]

As for the random spawning of items, this functionality has already been successfully implemented. However, I encountered difficulties when attempting to verify if each value is less than or equal to 3. The implementation using "every()" looked like this:

function checkBoard(mazenumbers){
  return mazenumbers <= 3;
}

function alertMazenumbers() {
   alert(maze.every(checkBoard));
}

This code snippet should trigger an alert once the player reaches the exit location, as illustrated below:

else if(direction === 'right') {
        if(maze[playerPos.y][playerPos.x + 1] == 3) {
            alertMazenumbers();
        }

The desired outcome is to receive a true alert if all values are less than or equal to 3, and a false alert otherwise. Presently, despite receiving the alert message, the result always appears as false even when all items have been cleared, suggesting true should be displayed instead.

Answer №1

You're heading in the right direction by utilizing the every method!

As mentioned by Denys in a previous comment, the maze is essentially an array of arrays, so it requires using the every method twice in your implementation:

function canExitMaze(maze) {
  return maze.every(row => row.every(cell => cell <= 3))
}

If you're unfamiliar with the arrow function syntax (=>), check out this article for a detailed explanation.

I trust this information proves helpful to you!

Answer №2

To determine if each point within the maze is less than or equal to 3, you can use the following method:

const isTrue = num => num <= 3; // checks if a single cell is true

const isRowTrue = row => row.every(isTrue); // checks if all cells in a row are true
const isMazeTrue = rows => rows.every(isTrue); // checks if all cells in all rows are true

const maze = [
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 2, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 3],
  [1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
];

console.log(isMazeTrue(maze));

Answer №3

Revised Method: Verify that each element in the arrays is less than or equal to 3

let matrix = [
  [1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 2, 0, 0, 0, 0, 1, 3, 4],
  [1, 1, 1, 1, 0, 1, 0, 1, 1]
];

function testMatrix(matrix) {
  return matrix.every(row => row.every(validItem));
}

function validItem(item) {
  return item <= 3;
}

console.log(testMatrix(matrix));
matrix[2][7] = 5;
console.log(testMatrix(matrix));

Inventive Strategy: Merge arrays and search for numeric values

var grid = [
  [1, 1, 1, 1, 1, 1, 1, 1],
  [1, 2, 0, 0, 0, 0, 1, 3],
  [1, 1, 1, 1, 0, 1, 0, 1]
];

function testGrid(grid) {
  return [].concat(...grid).every(validEntry);
}

function validEntry(entry) {
  return entry <= 3;
}

console.log(testGrid(grid));
grid[2][7] = 4;
console.log(testGrid(grid));

New Technique: Convert the grid into a string and apply regex for validation

var grid = [
  [1, 1, 1, 1, 1, 1, 1, 1],
  [1, 2, 0, 0, 0, 0, 1, 3],
  [1, 1, 1, 1, 0, 1, 0, 1]
];

function testGrid(grid) {

  //or grid.toString().match(/\d+/g).every(x => validEntry(+x));
  return !/[4-9]/g.test(`${grid}`);
}

function validEntry(entry) {
  return entry <= 3;
}

console.log(testGrid(grid));
grid[2][7] = 4;
console.log(testGrid(grid));

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

Using PHP within Drupal, how can I show or hide a link as needed in PHP and Drupal?

Let me simplify my question - In the code snippet provided, how can I display the "Change" link only when the status value is "A"? I am currently struggling with the combination of Drupal module structure and PHP as I am still in the learning phase of mod ...

What is the most effective method for sharing features while maintaining unique aesthetics?

In the process of developing a Next.js website, I've encountered a challenge: I have 3 forms that function in similar ways but have different styles. Instead of duplicating code for each form, I'm looking for a way to build the form structure on ...

Steps for implementing a datepicker in a dynamically generated element

Snippet of jQuery code that adds an element to a container $(container).append( '<label class="control-label col-md-3">Join Duration</label>' + '<div class="col-md-4">' + '<input type="text" name="join_dura ...

Attempting to modify text using the header parameter has proven to be ineffective

pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent); const propName = 'x-rewrite'; enum Device { desktop = 'no& ...

Is there a way to calculate the total of all values within a nested hash?

I am working with a nested hash structure that looks like this: Aranea={ "Aranéomorphes"=>{ "Agelenidae"=>[80,1327], "Amaurobiidae"=>[49,270], "Ammoxenidae"=>[4,18], "Anapidae"=>[58,23 ...

Create a v-on:click command within a v-for loop

I have a list of images displayed with some information. I am trying to make these images clickable so that when clicked, a div will show up saying "HI!!". I attempted to set a variable as show:true in Vue data and create logic to change it to false upon c ...

What can be done to address columns overlapping when sidebar is activated?

Excellent https://i.sstatic.net/gwOI8.png Terrible https://i.sstatic.net/4f637.png The first image labeled as 'Excellent' shows that the card divs do not overlap, but in the second image when the sidebar is active they do. I attempted to cha ...

Angular: A guide to binding to the required/ngRequired attribute

There is a directive that may or may not be required, and it can be used in two different ways. <my-foo required></my-foo> or <my-foo ng-required="data.value > 10"></my-foo> Even though require and ngRequire are essentially t ...

Ways to identify when a user goes offline following an $http request

I'm trying to determine the network connectivity status (online/offline) following an unsuccessful request using the $http service in AngularJs. Despite examining all response parameters in the error handler, I couldn't find any information that ...

Showing content from a JavaScript variable once a button has been clicked

Imagine you are using express.js and have a JavaScript variable embedded in an ejs file like this: <%= someVariable %> How can you display the value from this variable on the same page, for instance within a bootstrap modal element (check out https: ...

Implementing siteSpeedSampleRate in Google Analytics with AngularJS - a step-by-step guide

I utilized the following link https://github.com/revolunet/angular-google-analytics to incorporate Google Analytics into my AngularJS 1.5 project. However, I'm having trouble setting the siteSpeedSampleRate. I injected the AnalyticsProvider and attemp ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Difficulty in presenting data retrieved from a getter function

New Question: I need assistance with calculating the win percentage for different teams based on the wins and losses entered by the user. In my program, when displaying the team information, the win percentage always shows up as "0.000000". How can I updat ...

What is the process for adding elements to an array, then sorting it in JavaScript and returning the sorted array

Having an issue with my code snippet below, My goal is to insert a new record at the beginning of the array and then sort it based on the label. However, I'm encountering an unexpected outcome where the array turns out empty. const array = [{id: &apos ...

What methods exist for combining a set of numpy array images into a single large image?

Currently, I'm facing a challenge in converting a 4D numpy array into a 2D numpy array. The current format of the numpy array is (35280L, 1L, 32L, 32L), representing the number of images, channels, width, and height respectively. Essentially, I have 3 ...

Easy task tracker in Vue.js

I’m currently delving into the world of VueJS and working on a simple to-do list application. The issue I’m facing is that I can't seem to successfully pass an array to the child component responsible for displaying the list: Parent Component < ...

Encountering a problem during the creation of a fresh Angular 2 project

After installing AngularJs with the command npm install -g angular-cli, I encountered an error when trying to create a new project: Cannot find module 'reflect-metadata' How can I resolve this error? ...

Navigate through the array in reverse order, starting and stopping at random positions

Seeking troubleshooting help for my function that traverses an array in reverse from a given tail index to head index. However, it seems like some values are being skipped along the way. This is my current approach: currentRec = tail; while (currentRec ...

Why does node.js struggle to find other TypeScript React components?

Currently, I am in the process of converting some react server-side rendering files to typescript. However, I have encountered an issue with locating my custom components. The file path structure is as follows: node_modules/ src/ page/Homepage.tsx ...

Retrieving data from an array of resolved Promises

I'm using axios.all to iterate through an array of items and send a GET request for each one in order to store their data correctly. Currently, I have an array of Promises that are all resolving with the right data, and the callback function triggers ...