Created
April 11, 2022 22:27
-
-
Save leophys/4ad429f590cac5ce1f8c7e01f5794815 to your computer and use it in GitHub Desktop.
A ring in C
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
#include <stdio.h> | |
#include <stdlib.h> | |
struct ring_int { | |
struct ring_int *next; | |
int value; | |
} ring_int; | |
struct ring_int *new_ring(int capacity, int placeholder); | |
void advance(struct ring_int **ring); | |
void test_two_rounds(struct ring_int *ring, int *expected, int len); | |
int main() { | |
struct ring_int *ring = new_ring(3, 0); | |
int expected_0[3] = {0, 0, 0}; | |
test_two_rounds(ring, expected_0, 3); | |
int expected[3] = {1, 2, 3}; | |
for (int i = 0; i < 3; i++) { | |
ring->value = expected[i]; | |
advance(&ring); | |
} | |
test_two_rounds(ring, expected, 3); | |
} | |
struct ring_int *new_ring(int capacity, int placeholder) { | |
struct ring_int *cur = (struct ring_int *)malloc(sizeof(struct ring_int *)); | |
struct ring_int *start = cur; | |
for (int i = 1; i < capacity; i++) { | |
struct ring_int *next = | |
(struct ring_int *)malloc(sizeof(struct ring_int *)); | |
cur->next = next; | |
cur = next; | |
} | |
cur->next = start; | |
return start; | |
} | |
void advance(struct ring_int **ring) { *ring = (*ring)->next; } | |
void test_two_rounds(struct ring_int *ring, int *expected, int len) { | |
for (int i = 0; i < 2 * len; i++) { | |
if (ring->value != expected[i % len]) { | |
printf("val: %d\texpected[%d]: %d\n", ring->value, i % len, | |
expected[i % len]); | |
exit(i + 1); | |
} | |
advance(&ring); | |
} | |
printf("Test passed\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment