Adrian Neumann, Simple Programming Problems,
List and string problems
1
| #include "../lib/unity/src/unity.h" // throwtheswitch.org
|
1. Largest
Write a function that returns the largest element in a list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| int largest(int * arr, int arrlen) {
int max = arr[0];
for (int i = 1; i < arrlen; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
void test_largest() {
int arr[] = {1, 2, 3};
TEST_ASSERT_EQUAL(3, largest(arr, 3));
}
|
2. Reverse
Write a function that reverses a list, preferably in place.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| void reverse(int * arr, int arrlen) {
int temp;
int last = arrlen - 1;
for (int i = 0; i < arrlen / 2; i++) {
temp = arr[i];
arr[i] = arr[last - i];
arr[last - i] = temp;
}
}
void test_reverse() {
int arr1[] = {1, 2, 3, 4};
reverse(arr1, 4);
for (int i = 4, j = 0; i > 0; i--, j++) {
TEST_ASSERT_EQUAL(i, arr1[j]);
}
int arr2[] = {1, 2, 3};
reverse(arr2, 3);
for (int i = 3, j = 0; i > 0; i--, j++) {
TEST_ASSERT_EQUAL(i, arr2[j]);
}
}
|
3. Contains
Write a function that checks whether an element occurs in a list.
1
2
3
4
5
6
7
8
9
10
11
12
13
| int contains(int val, int * arr, int arrlen) {
int ret = 0;
for (int i = 0; i < arrlen; i++) {
if (arr[i] == val) ret = 1;
}
return ret;
}
void test_contains() {
int arr[] = {1, 2, 3};
TEST_ASSERT_EQUAL(1, contains(1, arr, 3));
TEST_ASSERT_EQUAL(0, contains(4, arr, 3));
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| int run_tests(void) {
UNITY_BEGIN();
RUN_TEST(test_largest);
RUN_TEST(test_reverse);
RUN_TEST(test_contains);
return UNITY_END();
}
int main(void) {
run_tests();
return 0;
}
|