Created
June 29, 2025 02:17
-
-
Save rokon12/173b75811ebf919c62d6bab53769f0e4 to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - snippet-10.java
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
record PeakValley(String type, double value, int index) {} | |
public static Gatherer<Double, ?, PeakValley> peakValleyDetection() { | |
return Gatherer.of( | |
() -> new Object() { | |
Double prev = null; // 1️⃣ Previous value | |
Double current = null; // 2️⃣ Current value | |
int index = 0; // 3️⃣ Track position | |
}, | |
(state, next, downstream) -> { | |
if (state.prev != null && state.current != null) { // 4️⃣ Have 3 points? | |
// Check for peak: current > both neighbors | |
if (state.current > state.prev && state.current > next) { | |
downstream.push(new PeakValley("PEAK", state.current, state.index)); | |
} | |
// Check for valley: current < both neighbors | |
else if (state.current < state.prev && state.current < next) { | |
downstream.push(new PeakValley("VALLEY", state.current, state.index)); | |
} | |
} | |
// 5️⃣ Slide the window forward | |
state.prev = state.current; | |
state.current = next; | |
state.index++; | |
return true; | |
} | |
); | |
} | |
// Visual example: | |
// Peak | |
// ↓ | |
// 103 | |
// / \ | |
// 101 99 ← Valley | |
// \ | |
// 102 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment