When an array is pushed into another array in JavaScript, it reverts back to its original values

My implementation of recursion involves trying different pieces in a matrix:

function solve(matrix, pieces) {
    // Get next -1
    let nextEmpty = getNextEmtpy(matrix);
    if (!nextEmpty) {
        console.log(matrix)
        solutions.push(matrix);
    }
    let row = nextEmpty.row;
    let col = nextEmpty.col;
    // Try all pieces that are not in the matrix
    for (let i = 1; i < pieces.length; i++) {
        if (matrix.flat().includes(i)) continue;
        for (let r = 0; r < 4; r++) {
            let fit = rotatePiece(pieces[i]);
            if (col == 0) {
                if (fit[0] != 0) continue;
            }
            if (row == 0) {
                if (fit[1] != 0) continue;
            }
            if (col == matrix[0].length - 1) {
                if (fit[2] != 0) continue;
            }
            if (row == matrix.length - 1) {
                if (fit[3] != 0) continue;
            }
            // If the piece is not in a border
            if (col > 0) {
                if (fit[0] != pieces[matrix[row][col - 1]][2]) continue;
            }
            if (row > 0) {
                if (fit[1] != pieces[matrix[row - 1][col]][3]) continue;
            }
            // Add the piece to the matrix
            matrix[row][col] = i;
            // Update pieces
            pieces[i] = fit;
            // Recurse
            let solution = solve(matrix, pieces);
            // Reset the value 
            matrix[row][col] = -1;
        }
    }
    return false;
}

The expected output and variable values seem correct except when adding the matrix to solutions array which starts as an empty array []:

[
  [ 25, 1, 17, 24, 7 ],
  [ 19, 16, 23, 8, 15 ],
  [ 12, 14, 4, 2, 21 ],
  [ 5, 9, 11, 6, 18 ],
  [ 10, 13, 22, 20, 3 ]
]

However, instead of this result, it adds the starting value of matrix:

  [
    [ -1, -1, -1, -1, -1 ],
    [ -1, -1, -1, -1, -1 ],
    [ -1, -1, -1, -1, -1 ],
    [ -1, -1, -1, -1, -1 ],
    [ -1, -1, -1, -1, -1 ]
  ]

This behavior seems unexpected. Why could this be happening?

Answer №1

As mentioned in the comments, the resolution was to duplicate the matrix content into solutions instead of pointing directly to it.

    if (!nextEmpty) {
    let copy = matrix.map((row) => row.slice());
    solutions.push(copy);
}

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

Execution of Ajax call fails to occur synchronously

I have created a unique weather website that utilizes the flickr API as well as the yahoo API to gather weather data. However, I am facing an issue where the ajax call from the yahoo API does not retrieve the necessary data in time for the content of the p ...

How can I extract data from [Object object] in Node.js?

Can someone help me figure out how to extract data from [Object object]? Let's consider the following scenario for clarity. // Fetching data using dirty method var info = database.get('/htmltest') // Contents of test.db file {"key":"foo", ...

What steps should I take to troubleshoot and resolve a 500 internal server error in a Node.js/Express.js application?

Whenever I try to post data from an HTML form to my Express.js server, all I get is an Internal Server Error 500. It just displays POST /routeitisreaching 500 without any further explanation. I'm struggling to identify the root cause of this issue. E ...

Artwork expanding incorrectly on HTML canvas

I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected. My assumption is that the elements are being ...

JavaScript timekeepers and Ajax polling/scheduling

After looking into various methods like Comet and Long-Polling, I'm searching for a simpler way to push basic ajax updates to the browser. I've come across the idea of using Javascript timers to make Ajax calls at specific intervals. Is this app ...

Executing a callback in AngularJS after multiple HTTP requests have been completed using a forEach loop

I am trying to update multiple items within a foreach loop by sending HTTP requests, and I need a callback once all the requests are complete. Despite searching on Stack Overflow, I haven't found a solution that works for me. Here is the snippet of m ...

Navigating through Sails.js: A comprehensive guide on executing test cases

Being a beginner in sails, node, and js, I may be missing out on some obvious steps. My environment includes sails 0.10.5 and node 0.10.33. Although the sails.js documentation covers tests in , it does not provide instructions on how to actually execute ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

How to transfer parameters from an array to a constructor in PHP

Typically, when passing arguments from $myarray to $somefunction in PHP, I would use the following approach: call_user_func_array($somefunction, $myarray); However, this method does not function as intended when trying to call a constructor for an object ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Compatibility Issue between Jquery UI CheckBox Button and Click Function in IE8

Situation: After calling addButton() function in jQuery, the checkbox element is successfully turning into a button. However, the click event that should trigger an alert message is not functioning. This issue seems to be specific to IE-8 compatibility. ...

Using JQuery, you can easily add a new row right after the row that you have

I need to insert a new row after the selected row, but my current code inserts the row at the end if no row is selected. Is there a way to fix this issue? strGridId = update_GridID(strGridId); var grid = jQuery('#' + strGridId); var columnModel ...

Having Trouble Concealing an Element with jQuery UI

I am attempting to implement a jQuery slide effect where pressing a button causes the first paragraph tag to slide out of view and the second paragraph tag to slide into the viewport. Despite utilizing jQuery UI for the slide effects, I am encountering dif ...

A guide to saving a 2D dynamic array in C to a file

int row,col,i,j; int **matrix; printf("Enter number of columns:"); scanf("%d",&col); printf("Enter number of rows:"); scanf("%d",&row); matrix= (int**) malloc(row* sizeof(int)); if(NULL == matrix) { free(matrix); print ...

CSS3 Word Wrapping Tutorial

Are there alternative methods to word-wrap text within a div element? I am limited to using only CSS1 and some CSS2, so I cannot utilize word-wrap in CSS. *Consider using javascript or CSS Thank you! .test_wordWrap { position: absolute; top: 45px; ...

Reorganize the 2D array to switch the column values to row values while keeping the initial keys intact (transpose while maintaining the top-level

In this scenario, there is a parent array structured like so: $parent = [ 1 => ['test1', 'test2'], 2 => ['test1_1', 'test2_2'], ]; The goal here is to group the data by column. Intended output: [ ...

Pass an array of Javascript classes from PHP to Javascript

Currently, I am facing a challenge with sending an array from PHP to Javascript using Ajax. While I have experience sending regular arrays, this time I need to send an array that includes Javascript constructors. Specifically, I aim to send something lik ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Are there any issues with integrating the Bootstrap 4 Datepicker script?

I'm having trouble getting a simple bootstrap datepicker to work on a large page despite including all the necessary scripts and stylesheets. Here is my code: <html> <body> <div id="datepicker" class="input-group d ...

Issues with v-on:change not triggering method in nuxt.js

Despite my efforts, I can't seem to get this seemingly simple task to work. I came across a question on Stack Overflow that seemed to address the issue - how to fire an event when v-model changes Here is the component that I am working with: <tem ...