Last active
March 14, 2019 17:22
-
-
Save dbalduini/d63bec4bcd5e06bbb2bfb8b14fe6f9ac to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/woguran
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reverse inplace the two char arrays splitten by space. Examples: | |
// perfect makes practice -> practice makes perfect | |
// a b c -> c b a | |
function reverse(arr) { | |
reverseArray(arr, 0, arr.length-1); | |
} | |
// reverse array inplace | |
function reverseArray(arr, start, end) { | |
var i = start; | |
var j = end; | |
var firstSpace; | |
var secondSpace; | |
while (i < j) { | |
//console.log(i + ' ' + j + ' [' + arr + ']'); | |
// swap | |
swap(arr, i, j); | |
if (arr[i] === ' ') { | |
// reverse first word | |
reverseWord(arr, 0, i-1); | |
firstSpace = i; | |
} | |
if (arr[j] === ' ') { | |
// reverse second word | |
reverseWord(arr, j+1, end); | |
secondSpace = j; | |
} | |
i++; | |
j--; | |
} | |
// reverse the middle word | |
reverseWord(arr, firstSpace, secondSpace); | |
} | |
function reverseWord(arr, start, end) { | |
var i = start; | |
var j = end; | |
while (i < j) { | |
// swap | |
swap(arr, i, j); | |
i++; | |
j--; | |
} | |
} | |
function swap(arr, i, j) { | |
var tmp = arr[j]; | |
arr[j] = arr[i]; | |
arr[i] = tmp; | |
} | |
var inputTest = ['a', ' ', 'b', ' ', 'c']; | |
reverse(inputTest); | |
console.log(inputTest); | |
var input1 = 'perfect makes practice'.split(''); | |
reverse(input1); | |
console.log(input1.join('')); | |
var input2 = 'cat giraffe dog'.split(''); | |
reverse(input2); | |
console.log(input2.join('')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment