Last active
January 20, 2019 03:13
-
-
Save pete-murphy/0f60b6d1c9ed4eca685e7661a93b32cb to your computer and use it in GitHub Desktop.
Zig Zag
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
const isZigZag = str => { | |
const nums = str.split(" ").map(Number) | |
return nums.every( | |
(num, i) => | |
num > Math.max(nums[i - 1] || -Infinity, nums[i + 1] || -Infinity) || | |
num < Math.min(nums[i - 1] || +Infinity, nums[i + 1] || +Infinity) | |
) | |
} | |
isZigZag("4 2 3 1 5 3") | |
// -> true | |
isZigZag("7 3 5 5 2") | |
// -> false | |
isZigZag("3 8 6 4 5") | |
// -> false | |
isZigZag("1") | |
// -> true |
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
const longestZigZag = str => { | |
const signs = str | |
.split(" ") | |
.map(Number) | |
.map((n, i, arr) => Math.sign(n - arr[i - 1])) | |
const lens = signs.reduce( | |
(acc, n, i) => | |
n !== signs[i - 1] && n !== 0 | |
? (([x, ...xs]) => [x + 1, ...xs])(acc) | |
: [1, ...acc], | |
[0] | |
) | |
return Math.max(...lens) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment