javascript - swapping pairs in arrays recursively -
trying swap pairs in array recursively, managed iteratively. how implement swap part recursively? think have of correct! if there odd number, last 1 stays same. don't want have helper swap function if possible.
pairswap = function(arr) { var newarray = [] (var = 0; < arr.length; += 2) { var current = arr[i]; var next = arr[i + 1] if (next !== undefined) { newarray.push(next) } if (current !== undefined) { newarray.push(current) }; }; return newarray; } console.log(pairswap([1, 2, 3, 4, 5])) pairswaprecursive = function(arr) { if (arr.length < 2) { return arr; } else { //swap first , second: return (swap ? ) + pairswaprecursive(arr.slice(2)) } } console.log(pairswaprecursive([1, 2, 3, 4, 5])) //should return [2, 1, 4, 3, 5] //something similar in java: // public string swappairs(string s) { // if (s.length() < 2) // return s; // else // return swap(s.charat(0), s.charat(1)) + swappairs(s.substring(2)); // }
i don't want have helper swap function if possible.
and don't need - return second , first element , you're done:
var pairswaprecursive = function(arr) { if (arr.length < 2) { return arr; } return [arr[1], arr[0]].concat(pairswaprecursive(arr.slice(2))); };
so other recursive algorithm it:
- does little chunk of work. in case - return array 2 first elements swapped.
- invokes rest
jsfiddle: http://jsfiddle.net/am8rz1jx/
Comments
Post a Comment