峰值查询算法
这是来源[https://zhuanlan.zhihu.com/p/549588865]
他用了 python, 于是我就用 ChatGPT 转换成了 C 语言, 试验了下, 还算好用
这么牛逼的代码, 我这辈子写不出来了
不求甚解, 会用就行
#include <stdio.h>
#include <stdlib.h>
int* AMPD(float* data, int count, int* peak_count) {
int* p_data = (int*)calloc(count, sizeof(int));
int* arr_rowsum = (int*)malloc(sizeof(int) * (count / 2));
int min_index;
int max_window_length;
if (p_data == NULL || arr_rowsum == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
// Calculate arr_rowsum
for (int k = 1; k <= count / 2; k++) {
int row_sum = 0;
for (int i = k; i < count - k; i++) {
if (data[i] > data[i - k] && data[i] > data[i + k]) {
row_sum -= 1;
}
}
arr_rowsum[k - 1] = row_sum;
}
// Find min_index
min_index = 0;
for (int i = 1; i < count / 2; i++) {
if (arr_rowsum[i] < arr_rowsum[min_index]) {
min_index = i;
}
}
max_window_length = min_index + 1;
// Mark peaks in p_data
for (int k = 1; k <= max_window_length; k++) {
for (int i = k; i < count - k; i++) {
if (data[i] > data[i - k] && data[i] > data[i + k]) {
p_data[i] += 1;
}
}
}
// Find indices of peaks
int* peaks = (int*)malloc(sizeof(int) * count);
*peak_count = 0;
for (int i = 0; i < count; i++) {
if (p_data[i] == max_window_length) {
peaks[*peak_count] = i;
(*peak_count)++;
}
}
// Resize peaks array
peaks = (int*)realloc(peaks, sizeof(int) * (*peak_count));
free(p_data);
free(arr_rowsum);
return peaks;
}
int main() {
float data[] = {1.0, 2.0, 3.0, 2.5, 2.0, 1.0, 0.5, 1.0, 2.0, 3.0, 4.0, 3.0, 2.0, 1.0};
int count = sizeof(data) / sizeof(data[0]);
int peak_count;
int* peak_indices = AMPD(data, count, &peak_count);
printf("Peak indices:\n");
for (int i = 0; i < peak_count; i++) {
printf("%d ", peak_indices[i]);
}
printf("\n");
free(peak_indices);
return 0;
}
License:
CC BY 4.0