Skip to content

Instantly share code, notes, and snippets.

@pete-murphy
Last active January 20, 2019 03:13
Show Gist options
  • Save pete-murphy/0f60b6d1c9ed4eca685e7661a93b32cb to your computer and use it in GitHub Desktop.
Save pete-murphy/0f60b6d1c9ed4eca685e7661a93b32cb to your computer and use it in GitHub Desktop.
Zig Zag
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
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