Created
May 29, 2017 16:45
-
-
Save rousan/23ff1e81bd87b4d9cedfd2976186700a to your computer and use it in GitHub Desktop.
Solution in JS
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
function findSomePair(arr, sum) { | |
arr = arr || []; | |
sum = sum || 0; | |
let outs = {}, | |
map = new Map(); | |
if (arr.length <= 1) { | |
outs["pairElementIndex1"] = -1; | |
outs["pairElementIndex2"] = -1; | |
return outs; | |
} | |
for(let i = 0; i < arr.length; ++i) { | |
if (map.has(arr[i])) { | |
outs["pairElementIndex1"] = i; | |
outs["pairElementIndex2"] = map.get(arr[i]); | |
return outs; | |
} else { | |
map.set(sum - arr[i], i); | |
} | |
} | |
outs["pairElementIndex1"] = -1; | |
outs["pairElementIndex2"] = -1; | |
return outs; | |
} | |
function testFindSomePair() { | |
let arr = [1, 4, 5, -1, 4, 7, 8, 8, 9, 12], | |
outs; | |
outs = findSomePair(arr, 21); | |
console.log(`Element Pair at ${outs.pairElementIndex1} and ${outs.pairElementIndex2}`); | |
} | |
function reverse(arr, start, end) { | |
let temp; | |
while (start < end) { | |
temp = arr[start]; | |
arr[start] = arr[end]; | |
arr[end] = temp; | |
start++; | |
end--; | |
} | |
} | |
function reverseEachWord(arr) { | |
let startInd = 0, | |
i = 0; | |
while (true) { | |
if (arr[i] === ' ') { | |
reverse(arr, startInd, i - 1); | |
startInd = i + 1; | |
} else if(i === arr.length) { | |
reverse(arr, startInd, i - 1); | |
break; | |
} | |
i++; | |
} | |
} | |
function testReverseEachWord() { | |
let arr = "This is our country".split(""); | |
reverseEachWord(arr); | |
console.log(arr.join("")); | |
} | |
(function () { | |
testFindSomePair(); | |
testReverseEachWord(); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment