Skip to content

Instantly share code, notes, and snippets.

@DomNomNom
Last active July 9, 2017 03:02
Show Gist options
  • Save DomNomNom/060156de8472d9276e34262bfaef031f to your computer and use it in GitHub Desktop.
Save DomNomNom/060156de8472d9276e34262bfaef031f to your computer and use it in GitHub Desktop.
Count the number of zig zags in an array (switches from increasing to decreasing or from decreasing to increasing)
// Counts how often a sequence zig zags.
// ie. switches from increasing to decreasing or from decreasing to increasing
// countZigZags([]) --> 0
// countZigZags([5,5,5,5]) --> 0
// countZigZags([1,2,3]) --> 0
// countZigZags([1,2,3,2,1]) --> 1
// countZigZags([5,6,5,6,5]) --> 3
// countZigZags([2,2,2,6,6,5,5]) --> 1
function countZigZags(numbers) {
// sweep through the numbers finding points where it switches from increasing to decreasing or from decreasing to increasing
let i;
let isIncreasing;
let count = 0;
// figure out the initial slope
for (i=1; i<numbers.length; ++i) {
if (numbers[i-1] == numbers[i]) continue;
isIncreasing = numbers[i-1] < numbers[i];
break;
}
++i;
// count how oftern isIncreasing changes.
for (; i<numbers.length; ++i) {
if (numbers[i-1] == numbers[i]) continue;
const newIsIncreaing = numbers[i-1] < numbers[i];
if (newIsIncreaing == isIncreasing) continue;
isIncreasing = newIsIncreaing;
++count;
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment