Created
July 21, 2019 20:24
-
-
Save kylejeske/aa964f54821ed4c6d2086b99adb36372 to your computer and use it in GitHub Desktop.
Flipping bits - RunTime: o(n), Space: o(n)
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
// Start with: ['a', 'b', 'c', 'd', 'e'] | |
// End with: ['a', 'b', 'c', 'd', 'e'] | |
// without using any additional variables, and within o(n) runtime. | |
// swapArr (reference Array, pointer 1, pointer 2) | |
// will take the reference to the position within the array | |
// and swap them without using a third variable | |
const swapArr = (arr, x,y) => { | |
// replace ASCII values with the character decimals | |
arr[x] = arr[x].charCodeAt(0); | |
arr[y] = arr[y].charCodeAt(0); | |
// do a XOR bitwise comparison & swap | |
arr[x] = arr[x]^arr[y]; | |
arr[y] = arr[x]^arr[y]; | |
arr[x] = arr[x]^arr[y]; | |
// switch the characters back to the ASCII values | |
arr[x] = String.fromCharCode(arr[x]); | |
arr[y] = String.fromCharCode(arr[y]); | |
return arr; | |
} | |
const main = () => { | |
let _arr = ['a','b','c','d','e']; | |
console.log(`Before: ${_arr}`); | |
// start pointers at beginning and end of array | |
// then loop until we meet in the middle | |
let n = _arr.length; | |
let s = 0; | |
let e = n - 1; | |
while (s < e) { | |
// swap the letters | |
_arr = swapArr(_arr, s, e); | |
s++; | |
e--; | |
} | |
console.log(`After: ${_arr}`); | |
} | |
// runner function | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment