Skip to content

Instantly share code, notes, and snippets.

@waltervargas
Last active March 24, 2024 16:13
Show Gist options
  • Save waltervargas/b535b7f8bb8b4a207e5f7a5dd28e639a to your computer and use it in GitHub Desktop.
Save waltervargas/b535b7f8bb8b4a207e5f7a5dd28e639a to your computer and use it in GitHub Desktop.
range in C
int* range(int start, int end) {
int len;
if (start <= end) {
len = end - start + 1;
} else {
len = start - end + 1;
}
int* array = malloc(sizeof(int) * len);
if (start == end){
array[0] = start;
} else if (start < end) {
int i = 0;
while (i < len) {
array[i] = start;
start++;
i++;
}
} else {
int i = 0;
while (i < len) {
array[i] = start;
start--;
i++;
}
}
return array;
}
#include <check.h>
#include "utils.h"
// Function prototypes
Suite* swap_suite(void);
START_TEST(test_range) {
int* array = range(0, 10);
ck_assert_int_eq(array[0],0);
ck_assert_int_eq(array[1],1);
ck_assert_int_eq(array[9],9);
ck_assert_int_eq(array[10],10);
int* array2 = range(3, 7);
ck_assert_int_eq(array2[0],3);
ck_assert_int_eq(array2[4],7);
int* array3 = range(-3, 1);
ck_assert_int_eq(array3[0],-3);
ck_assert_int_eq(array3[1],-2);
ck_assert_int_eq(array3[2],-1);
ck_assert_int_eq(array3[3],0);
ck_assert_int_eq(array3[4],1);
int* array4 = range(1, 1);
ck_assert_int_eq(array4[0],1);
int* array5 = range(0, -3); // 0 -1 -2 -3
ck_assert_int_eq(array5[0], 0);
ck_assert_int_eq(array5[1], -1);
ck_assert_int_eq(array5[2], -2);
ck_assert_int_eq(array5[3], -3);
}
END_TEST
// Suite setup
Suite* swap_suite(void) {
Suite *s;
TCase *tc_core;
s = suite_create("utils");
/* Core test case */
tc_core = tcase_create("Core");
tcase_add_test(tc_core, test_is_num_in_stack);
tcase_add_test(tc_core, test_range);
suite_add_tcase(s, tc_core);
return s;
}
// Main function to run the test suite
int main(void) {
int number_failed;
Suite *s;
SRunner *sr;
s = swap_suite();
sr = srunner_create(s);
srunner_run_all(sr, CK_VERBOSE);
number_failed = srunner_ntests_failed(sr);
srunner_free(sr);
return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
@waltervargas
Copy link
Author

cc utils.c utils_test.c -I /opt/homebrew/include -lcheck -L/opt/homebrew/lib -o utils_test
./utils_test
Running suite(s): utils
100%: Checks: 2, Failures: 0, Errors: 0
utils_test.c:57:P:Core:test_range:0: Passed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment