0

I have array const arr = [1,2,3,4] I want to get 4 different arrays by swapping a number pairs in this array. I. e. the outcome of this array would be:

1st: [2,1,3,4]

2nd: [1,3,2,4]

3rd: [1,2,4,3]

4rd: [4,2,3,1] (swapping first and last elements)

I know Object.assign help's to avoid mutations but not sure how to implement it.

more explanation:

  1. taking an original arr
  2. swapping the first pair of numbers
  3. returning [2,1,3,4]

repeating

  1. taking an original arr
  2. swapping the second pair of numbers
  3. returning [1,3,2,4]

etc.

karolis2017
  • 1,395
  • 2
  • 18
  • 36
  • is this array always of three elements ?. If it is more than three elements will how will the output be (will it it produce all order of permutations) ? – user93 Nov 24 '17 at 04:42
  • there could be more than 3 elements. Not sure about your second question. – karolis2017 Nov 24 '17 at 04:44
  • 1
    In other words what would expected results be for 4 elements in array, or 5? The swapping shown isn't intuitive and doesn't produce all possible permutations – charlietfl Nov 24 '17 at 04:47
  • You should not assign to `arr` indices in a `map` callback. – Bergi Nov 24 '17 at 04:48
  • 1
    "*`return arr => [3,2,1], [3,1,2], [3,1,undefined,2]`*" - what? – Bergi Nov 24 '17 at 04:48
  • 1
    To [copy an array](https://stackoverflow.com/q/7486085/1048572) to get individually mutable objects, use `.slice()`. But what do you mean by "*create arrays by swapping a number of pairs*"? Of course [there are many ways to generate all possible permutations](https://stackoverflow.com/q/9960908/1048572) of an array, but it has not much to do with swapping. – Bergi Nov 24 '17 at 04:49
  • "*I have array `const arr = [1,2,3,4]` I want to get 4 different arrays*" - but which 4? There are 24 permutations, and 6 of them that are reachable from the input through a single swap. It seems like you have missed `[3,2,1,4]` and `[1,4,3,2]`. – Bergi Nov 24 '17 at 04:57
  • as @Bergi if you need to produce all permutations without mutation you could do https://stackoverflow.com/a/22063440/2445295 – user93 Nov 24 '17 at 05:04
  • I didn't miss any array in my outcome example. I'm swapping one pair of numbers from left to right and returning new arr. Then taking the original array and doing the same with next pair of numbers in the array. – karolis2017 Nov 24 '17 at 05:32

1 Answers1

0

Looks like for any given array, you are going to produce an array of arrays characterized by single swaps. What's important to note is that this array of arrays has the same length (n) as the original array and that the ith array swaps elements i and (i+1)%n. Knowing that, here's a solution using map, Object.assign, and slice:

[ 1, 2, 3, 4 ].map( ( element, index, arr ) =>
    Object.assign( arr.slice(), {
        [ index ]: arr[ ( index + 1 ) % arr.length ],
        [ ( index + 1 ) % arr.length ]: arr[ index ]
    } ) );

Note element is unused.

vox
  • 767
  • 8
  • 15