From f23df827572d55835353bd578ad9ee09d85d2669 Mon Sep 17 00:00:00 2001 From: Hammy Date: Sun, 2 Jan 2022 02:06:10 +0000 Subject: [PATCH] Add List_count() --- src/list.c | 17 +++++++++++++++++ src/test/test.c | 16 ++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/list.c b/src/list.c index 6a6cdd5..bbbf501 100644 --- a/src/list.c +++ b/src/list.c @@ -219,6 +219,23 @@ int List_extend(List *list_to_extend, List *input_list) { return 0; } +int List_count(List *list, int element) { + if (!list) { + return 1; + } + + int count = 0; + int listLength = List_length(list); + + for (int i = 0; i < listLength; i++) { + if (element == List_get(list, i)) { + count++; + } + } + + return count; +} + int List_length(List *list) { return list->_currentSize + 1; } diff --git a/src/test/test.c b/src/test/test.c index 5898af2..68f0b96 100644 --- a/src/test/test.c +++ b/src/test/test.c @@ -241,6 +241,21 @@ void shouldPopElementFromList() { printSuccess(__func__); } +void shouldCountElementsInList() { + // Arrange + List *list = List_new(); + List_append_all(list, 5, 0, 1, 1, 3, 4, 5); + + // Act + int count = List_count(list, 1); + + // Assert + assert(count == 2); + + List_destroy(&list); + printSuccess(__func__); +} + int main() { printf("============================================"); printf("\nSTART TESTING"); @@ -258,6 +273,7 @@ int main() { shouldExtendList(); shouldDeleteElementFromList(); shouldPopElementFromList(); + shouldCountElementsInList(); printf("\n\n============================================"); printf("\nFINISH TESTING"); printf("\n============================================");