2019-09-01 12:52:45 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
|
2019-09-01 15:50:45 +00:00
|
|
|
// Type for vector, change to the desired type to be used in the vector
|
2019-09-01 14:06:28 +00:00
|
|
|
#define VECTOR_TYPE int
|
2019-09-01 12:52:45 +00:00
|
|
|
|
2019-09-01 15:50:45 +00:00
|
|
|
typedef struct vector {
|
2019-09-01 12:52:45 +00:00
|
|
|
size_t length;
|
2019-09-01 14:06:28 +00:00
|
|
|
VECTOR_TYPE* arr;
|
2019-09-01 12:52:45 +00:00
|
|
|
size_t start;
|
|
|
|
size_t size;
|
2019-09-01 14:06:28 +00:00
|
|
|
} vector_t;
|
2019-09-01 12:52:45 +00:00
|
|
|
|
2019-09-01 14:07:21 +00:00
|
|
|
inline static size_t vector_end(vector_t* self) {
|
2019-09-01 14:06:28 +00:00
|
|
|
return (self->start + self->size) % self->length;
|
|
|
|
}
|
|
|
|
|
|
|
|
vector_t vector_init(size_t length) {
|
|
|
|
vector_t self;
|
2019-09-01 12:52:45 +00:00
|
|
|
self.length = length;
|
2019-09-01 14:06:28 +00:00
|
|
|
self.arr = malloc(length * sizeof(VECTOR_TYPE));
|
2019-09-01 12:52:45 +00:00
|
|
|
self.start = 0;
|
|
|
|
self.size = 0;
|
|
|
|
return self;
|
|
|
|
}
|
|
|
|
|
2019-09-01 14:06:28 +00:00
|
|
|
bool vector_add(vector_t* self, VECTOR_TYPE element, bool to_end) {
|
2019-09-01 12:52:45 +00:00
|
|
|
if (self->size == self->length) {
|
|
|
|
return false;
|
|
|
|
}
|
2019-09-01 14:06:28 +00:00
|
|
|
if (to_end) {
|
2019-09-01 14:07:21 +00:00
|
|
|
self->arr[vector_end(self)] = element;
|
2019-09-01 14:06:28 +00:00
|
|
|
} else {
|
|
|
|
if (self->size == 0) {
|
|
|
|
self->arr[self->start] = element;
|
|
|
|
} else {
|
|
|
|
self->arr[self->start - 1] = element;
|
|
|
|
self->start--;
|
|
|
|
}
|
|
|
|
}
|
2019-09-01 12:52:45 +00:00
|
|
|
self->size++;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-09-01 14:06:28 +00:00
|
|
|
bool vector_remove(vector_t* self, VECTOR_TYPE* destination, bool from_end) {
|
2019-09-01 12:52:45 +00:00
|
|
|
if (self->size == 0) {
|
|
|
|
return false;
|
|
|
|
}
|
2019-09-01 14:06:28 +00:00
|
|
|
|
2019-09-01 14:07:21 +00:00
|
|
|
*destination = self->arr[!from_end ? vector_end(self) : self->start];
|
2019-09-01 15:50:45 +00:00
|
|
|
self->start = from_end ? (self->start + 1) % self->length : self->start;
|
2019-09-01 12:52:45 +00:00
|
|
|
self->size--;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-09-01 14:06:28 +00:00
|
|
|
void vector_destroy(vector_t* self) {
|
2019-09-01 12:52:45 +00:00
|
|
|
if (self->arr != NULL) {
|
|
|
|
free(self->arr);
|
|
|
|
self->arr = NULL;
|
|
|
|
}
|
|
|
|
}
|