diff --git a/c_impl/.gitignore b/c_impl/.gitignore new file mode 100644 index 0000000..4d4c8fb --- /dev/null +++ b/c_impl/.gitignore @@ -0,0 +1,2 @@ +LocalMaxima +src/*.o diff --git a/c_impl/Makefile b/c_impl/Makefile new file mode 100644 index 0000000..c967c80 --- /dev/null +++ b/c_impl/Makefile @@ -0,0 +1,20 @@ +SOURCES = src/main.c +OBJECTS = $(subst .c,.o,$(SOURCES)) + +COMMON_FLAGS = -Wall -Wextra -Wpedantic +ifdef DEBUG + CFLAGS = $(COMMON_FLAGS) -O0 -g +else + CFLAGS = $(COMMON_FLAGS) -O3 -DNDEBUG +endif + +all: LocalMaxima + +LocalMaxima: $(OBJECTS) + $(CC) $(CFLAGS) -o LocalMaxima $^ + +.PHONY: + +clean: + rm -f LocalMaxima + rm -f src/*.o diff --git a/c_impl/src/main.c b/c_impl/src/main.c new file mode 100644 index 0000000..0a29fc7 --- /dev/null +++ b/c_impl/src/main.c @@ -0,0 +1,57 @@ +#include +#include +#include + +#define INPUT_INIT_SIZE 32 + +int parseInteger(int **input, size_t *input_size, size_t *input_capacity, char *argv) { + int value = atoi(argv); + if(value == 0 && argv[0] != '0') { + return 1; + } + + if(*input_size == *input_capacity) { + int *newBuf = malloc(sizeof(int)*(*input_capacity)*2); + memcpy(newBuf, *input, sizeof(int)*(*input_capacity)); + free(*input); + *input_capacity *= 2; + *input = newBuf; + } + (*input)[(*input_size)++] = value; + return 0; +} + +void findLocalMaxima(int *input, int size) { + int consecutive = 0; + for(size_t i = 1; i + 1 < size; ++i) { + if(input[i-1] <= input[i] && input[i] >= input[i+1]) { + if(consecutive == 0) { + printf("%d ", input[i]); + consecutive = 1; + } + } else { + consecutive = 0; + } + } + printf("\n"); +} + +int main(int argc, char **argv) { + int *input = (int*)malloc(sizeof(int) * INPUT_INIT_SIZE); + size_t input_size = 0; + size_t input_capacity = INPUT_INIT_SIZE; + + --argc; ++argv; + while(argc > 0) { + if(parseInteger(&input, &input_size, &input_capacity, argv[0]) != 0) { + free(input); + return 1; + } + --argc; ++argv; + } + + findLocalMaxima(input, input_size); + + free(input); + return 0; +} diff --git a/problem b/problem new file mode 100644 index 0000000..3a4bafe --- /dev/null +++ b/problem @@ -0,0 +1,4 @@ +Write a program that finds the local maxima of a list of integers. + +A local maxima in a list is a number that is greater than or equal to adjacent +numbers.