Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Exercise - Reverse 2 dimensional array

Reverse the values of a 2 dimensional array that could extend n times.

[1, [2, [3, ... [n, null]]]]

Given:

  1. All arrays always have a length of 2
  2. Last array in the list will contain an index 1 of null

Example:

  • [1, [2, [3, null]]] will output [3, [2, [1, null]]]
  • [1, [2, [3, [4, null]]]] would output [4, [3, [2, [1, null]]]]

I'm not sure if I'm describing it right but I came across this exercise today and came up with a fairly obvious solution.

var ars = [1, [2, [3, null]]], rev = null;

function r(x) {
    rev = (rev == null) ? [x[0]] : [x[0], rev];
    if( x[1] !== null )
        r(x[1]);
}
r(ars);
console.log( rev );

http://jsfiddle.net/5b4xntwg/

I am by no means a javascript expert, so I was wondering if there was a better way to do it?

like image 552
rgin Avatar asked Aug 27 '14 17:08

rgin


1 Answers

Here's a more concise approach that doesn't have side-effects:

function r(arr, acc) {
    acc = acc || null;
    return arr ? r(arr[1], [arr[0], acc]) : acc;
}

http://jsfiddle.net/5b4xntwg/1/

It goes through the following recursive calls for the input [1, [2, [3, null]]]:

r([1, [2, [3, null]]]                     )
r([2, [3, null]]     , [1, null]          )
r([3, null]          , [2, [1, null]]     )
r(null               , [3, [2, [1, null]]])

On the last call, arr is null (this is the base case), so it just returns acc, which has the value [3, [2, [1, null]]].

One thing worth mentioning is that this nested array structure is basically a cons list, which is used extensively in functional programming and is very conducive to recursive operations.

Lastly, here's an iterative version:

function r(arr) {
    var acc = null;
    while (arr) { 
        acc = [arr[0], acc]; 
        arr = arr[1]; 
    }
    return acc;
}
like image 185
JLRishe Avatar answered Oct 31 '22 16:10

JLRishe