Javascript Recursive function. Wrong results while storing data in array

Jacob Goh

While trying to get all permutations using Heap's algorithm, I met trouble storing the results in array.

The result generated is (from console.log(arr);)
["1", "2", "3"]
["2", "1", "3"]
["3", "1", "2"]
["1", "3", "2"]
["2", "3", "1"]
["3", "2", "1"]

but only the last value is stored in the arr, and the array stored somehow is this (from console.log(JSON.stringify(allPermutations)); )
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]

var allPermutations = [];

function swap(arr,index1,index2){
    var dummy = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = dummy;
    return arr;
}

function generate(n,arr){
    if(n==1){
        console.log(arr);
            //result:
            //["1", "2", "3"]
            //["2", "1", "3"]
            //["3", "1", "2"]
            //["1", "3", "2"]
            //["2", "3", "1"]
            //["3", "2", "1"]
        allPermutations.push(arr);
    }else{
        for(var i=0;i<n-1;i++){
            generate(n-1,arr);
            if( n%2 ==0){
                arr = swap(arr,i,n-1);
            }else{
                arr = swap(arr,0,n-1);
            }
        }
        generate(n - 1, arr);
    }
}

generate(3,['1','2','3']);

console.log(JSON.stringify(allPermutations));
/*result:
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]*/

What's wrong with this? Would love to understand. Thanks

Amadan

Replace allPermutations.push(arr) with allPermutations.push(arr.slice()).

The problem is, you keep pushing the same array, then changing that array. When you push an array, you don't push a copy of it: you push a reference. There is only one array, and six references to it; when you read them out, they all read the same, because they are all the same array.

.slice() will give you a new array with the same elements; this way, you get six new arrays into your result, instead of six mentions of the same array.

From one of my earlier answers that is almost-but-not-quite a duplicate, a metaphor I like for this:

As a metaphor, imagine a theatre director in casting. He turns to an actor, says "You... you'll be Romeo.". Then he looks at the same actor, says "You... you'll be Mercutio. Here, Mercutio, take this sword. Romeo... who told you to get a sword?!?" completely failing to realise that, if Romeo and Mercutio are the same person, if one of them picks up a sword, the other does it too.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Storing recursive results backwards

From Dev

Storing objects in an array in javascript is storing the function

From Dev

Recursive function in php storing results without using static

From Dev

Javascript Storing Multiple Data Objects In An Array

From Dev

Javascript Storing Multiple Data Objects In An Array

From Dev

JavaScript recursive function for nested objects in array

From Dev

Recursive function Javascript concat array result - ImageJ

From Dev

Intermediate results in a recursive function

From Dev

Recursive function results in StackOverflowError

From Dev

Storing data from the keyboard to an array while ignoring duplicates

From Dev

Array.prototype.reduce in recursive function is producing unexpected results

From Dev

Array.prototype.reduce in recursive function is producing unexpected results

From Dev

Stack overflow while processing large array in recursive function

From Dev

Pass Array to Recursive Function While Modifying It C++

From Dev

Storing data in an array of char*

From Dev

Recursive function in lisp goes wrong

From Dev

Javascript array storing process

From Dev

In what situation would storing in an array different data types be useful in Javascript?

From Dev

Wrong results while String comparison

From Dev

Recursive tree search return wrong results

From Dev

data corrupt while storing in char ***

From Dev

Accumulating results of a recursive function in python

From Dev

Python Recursive function missing results

From Dev

storing a php array in a javascript array

From Dev

How can I create a two column or (six) array for storing the results of loop function estimates (n, R^2)?

From Dev

Function which takes an int pointer * as an argument and returns a struct. Storing data in struct struct* and printing results

From Dev

Recursive function for array integers

From Dev

Can while be replaced with if if the function is not recursive?

From Dev

Strange behavior storing function results in OCaml

Related Related

  1. 1

    Storing recursive results backwards

  2. 2

    Storing objects in an array in javascript is storing the function

  3. 3

    Recursive function in php storing results without using static

  4. 4

    Javascript Storing Multiple Data Objects In An Array

  5. 5

    Javascript Storing Multiple Data Objects In An Array

  6. 6

    JavaScript recursive function for nested objects in array

  7. 7

    Recursive function Javascript concat array result - ImageJ

  8. 8

    Intermediate results in a recursive function

  9. 9

    Recursive function results in StackOverflowError

  10. 10

    Storing data from the keyboard to an array while ignoring duplicates

  11. 11

    Array.prototype.reduce in recursive function is producing unexpected results

  12. 12

    Array.prototype.reduce in recursive function is producing unexpected results

  13. 13

    Stack overflow while processing large array in recursive function

  14. 14

    Pass Array to Recursive Function While Modifying It C++

  15. 15

    Storing data in an array of char*

  16. 16

    Recursive function in lisp goes wrong

  17. 17

    Javascript array storing process

  18. 18

    In what situation would storing in an array different data types be useful in Javascript?

  19. 19

    Wrong results while String comparison

  20. 20

    Recursive tree search return wrong results

  21. 21

    data corrupt while storing in char ***

  22. 22

    Accumulating results of a recursive function in python

  23. 23

    Python Recursive function missing results

  24. 24

    storing a php array in a javascript array

  25. 25

    How can I create a two column or (six) array for storing the results of loop function estimates (n, R^2)?

  26. 26

    Function which takes an int pointer * as an argument and returns a struct. Storing data in struct struct* and printing results

  27. 27

    Recursive function for array integers

  28. 28

    Can while be replaced with if if the function is not recursive?

  29. 29

    Strange behavior storing function results in OCaml

HotTag

Archive