Skip to content

Instantly share code, notes, and snippets.

@kbastani
Created June 12, 2023 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbastani/3cf68f54871b83206f15ac7122c6151e to your computer and use it in GitHub Desktop.
Save kbastani/3cf68f54871b83206f15ac7122c6151e to your computer and use it in GitHub Desktop.
Partition by inflection point segments in a double stream
import java.util.ArrayList;
import java.util.List;
public class PartitionExample {
public static void main(String[] args) {
List<Double> values = List.of(1.0, 2.0, 3.0, 2.5, 4.0, 3.0, 2.0, 1.0, 2.0, 3.0, 4.0);
List<List<Double>> partitions = partitionBetweenInflections(values);
// Print the partitions
for (List<Double> partition : partitions) {
System.out.println(partition);
}
}
public static List<List<Double>> partitionBetweenInflections(List<Double> values) {
List<List<Double>> partitions = new ArrayList<>();
int startIndex = 0;
int endIndex = 1;
while (endIndex < values.size() - 1) {
double prevValue = values.get(endIndex - 1);
double currValue = values.get(endIndex);
double nextValue = values.get(endIndex + 1);
if (prevValue < currValue && currValue > nextValue) {
partitions.add(values.subList(startIndex, endIndex + 1));
startIndex = endIndex + 1;
}
endIndex++;
}
// Add the remaining values as the last partition
partitions.add(values.subList(startIndex, values.size()));
return partitions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment