Last active
May 20, 2020 04:10
-
-
Save muhsalaa/dcb288fed0cd69451075a565b28582cc to your computer and use it in GitHub Desktop.
list of answer of hackerrank problem in javascript
This file contains 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
// 1. https://www.hackerrank.com/challenges/counting-valleys/problem | |
// count how many valleys has been passed by hiker | |
function countingValleys(n, s) { | |
let valleys = 0; | |
let count = 0; | |
s.split('').forEach(x => { | |
if (x === 'U') { | |
count += 1 | |
// check if count === 0 means it is the time when hiker go to sea level from valleys, valleys += 1 | |
if (count === 0) { | |
valleys += 1 | |
} | |
} else { | |
count -= 1 | |
} | |
}) | |
return valleys | |
} | |
// 2. https://www.hackerrank.com/challenges/sock-merchant/problem | |
// find the amount of scokpairs | |
function sockMerchant(n, ar) { | |
// create color hash | |
const colors = {}; | |
// count total matches (pairs) | |
let matches = 0; | |
ar.forEach(x => { | |
// if color with truthy value exist, increment pairs by 1 and set color to zero to make it falsy | |
if (colors[x]) { | |
matches++; | |
colors[x] = 0 | |
} | |
// if color value is falsy (0 or have no key inside hash), create or add 1 | |
else { | |
colors[x] = 1 | |
} | |
}) | |
// result of socks pair | |
return matches | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment