From efe02dadbf6fa9dd562c044e046786376dc18111 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 26 Oct 2024 18:29:19 -0700 Subject: [PATCH 01/44] Add binary search in C --- archive/c/c/binary-search.c | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 archive/c/c/binary-search.c diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c new file mode 100644 index 000000000..e69de29bb From 7251534300b92cdc3545e1c0d19a913fd06d77ff Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 27 Oct 2024 10:57:09 -0700 Subject: [PATCH 02/44] Add code --- archive/c/c/binary-search.c | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index e69de29bb..22629d0e9 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -0,0 +1,41 @@ +#include + +// Function to perform binary search +int binarySearch(int arr[], int size, int target) { + int left = 0; + int right = size - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; // To prevent overflow + + // Check if target is present at mid + if (arr[mid] == target) { + return mid; // Target found + } + + // If target is greater, ignore the left half + if (arr[mid] < target) { + left = mid + 1; + } else { + // If target is smaller, ignore the right half + right = mid - 1; + } + } + + return -1; // Target not found +} + +int main() { + int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int size = sizeof(arr) / sizeof(arr[0]); + int target = 5; + + int result = binarySearch(arr, size, target); + if (result != -1) { + printf("Element found at index: %d\n", result); + } else { + printf("Element not found.\n"); + } + + return 0; +} From ea9c9ff8c28e033cdbac309c027e04800bd0dc16 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 27 Oct 2024 11:38:39 -0700 Subject: [PATCH 03/44] Handle errors and potential edge cases --- archive/c/c/binary-search.c | 108 ++++++++++++++++++++++++++++++------ 1 file changed, 91 insertions(+), 17 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index 22629d0e9..a5b06b00f 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -1,41 +1,115 @@ #include +#include + +// Function prototypes +int binarySearch(const int arr[], int size, int target); +int compare(const void *a, const void *b); +void getInputArray(int **arr, int *size); +void freeMemory(int *arr); +int isSorted(const int arr[], int size); + +int main() { + int *arr = NULL; + int size = 0; + + getInputArray(&arr, &size); + if (arr == NULL) { + return 1; // Memory allocation failure handled in getInputArray + } + + // Check if the array is sorted + if (!isSorted(arr, size)) { + printf("The array is not sorted. Sorting the array now...\n"); + qsort(arr, size, sizeof(int), compare); + } + + // Get target value to search for + int target; + printf("Enter the target value to search: "); + if (scanf("%d", &target) != 1) { + printf("Invalid input. Exiting.\n"); + freeMemory(arr); + return 1; + } + + // Perform binary search + int result = binarySearch(arr, size, target); + if (result != -1) { + printf("Element found at index: %d\n", result); + } else { + printf("Element not found.\n"); + } + + // Free allocated memory + freeMemory(arr); + return 0; +} // Function to perform binary search -int binarySearch(int arr[], int size, int target) { +int binarySearch(const int arr[], int size, int target) { int left = 0; int right = size - 1; while (left <= right) { - int mid = left + (right - left) / 2; // To prevent overflow + int mid = left + (right - left) / 2; - // Check if target is present at mid if (arr[mid] == target) { return mid; // Target found } - // If target is greater, ignore the left half if (arr[mid] < target) { - left = mid + 1; + left = mid + 1; // Move right } else { - // If target is smaller, ignore the right half - right = mid - 1; + right = mid - 1; // Move left } } return -1; // Target not found } -int main() { - int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - int size = sizeof(arr) / sizeof(arr[0]); - int target = 5; +// Comparison function for qsort +int compare(const void *a, const void *b) { + return (*(int *)a - *(int *)b); +} - int result = binarySearch(arr, size, target); - if (result != -1) { - printf("Element found at index: %d\n", result); - } else { - printf("Element not found.\n"); +// Function to get user input for the array +void getInputArray(int **arr, int *size) { + printf("Enter the number of elements in the array: "); + if (scanf("%d", size) != 1 || *size <= 0) { + printf("Invalid size. Exiting.\n"); + return; } - return 0; + *arr = (int *)malloc(*size * sizeof(int)); + if (*arr == NULL) { + printf("Memory allocation failed. Exiting.\n"); + return; + } + + printf("Enter %d elements (unsorted): ", *size); + for (int i = 0; i < *size; i++) { + if (scanf("%d", &(*arr)[i]) != 1) { + printf("Invalid input. Exiting.\n"); + freeMemory(*arr); + *arr = NULL; // Set to NULL to avoid double free + return; + } + } +} + +// Function to free allocated memory +void freeMemory(int *arr) { + if (arr != NULL) { + free(arr); + } +} + +// Function to check if the array is sorted +int isSorted(const int arr[], int size) { + for (int i = 1; i < size; i++) { + if (arr[i] < arr[i - 1]) { + return 0; // Array is not sorted + } + } + return 1; // Array is sorted } From b4281385aaf45a7c80ac03475789c36441479454 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 27 Oct 2024 11:56:17 -0700 Subject: [PATCH 04/44] Clean Up + Refactor + Request Input from Command Line --- archive/c/c/binary-search.c | 79 +++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index a5b06b00f..c29941762 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -1,36 +1,46 @@ #include #include +#include // Function prototypes int binarySearch(const int arr[], int size, int target); int compare(const void *a, const void *b); -void getInputArray(int **arr, int *size); +int parseInput(const char *input, int **arr); void freeMemory(int *arr); int isSorted(const int arr[], int size); +int isValidNumber(const char *str); + +int main(int argc, char *argv[]) { + if (argc != 3) { + printf("Usage: %s \n", argv[0]); + return 1; + } -int main() { int *arr = NULL; int size = 0; - getInputArray(&arr, &size); - if (arr == NULL) { - return 1; // Memory allocation failure handled in getInputArray + // Parse the input array from the first argument + if (parseInput(argv[1], &arr) != 0) { + return 1; // Exit if parsing fails } + // Update size + size = sizeof(arr) / sizeof(arr[0]); + // Check if the array is sorted if (!isSorted(arr, size)) { printf("The array is not sorted. Sorting the array now...\n"); qsort(arr, size, sizeof(int), compare); } - // Get target value to search for + // Get target value from the second argument int target; - printf("Enter the target value to search: "); - if (scanf("%d", &target) != 1) { - printf("Invalid input. Exiting.\n"); + if (!isValidNumber(argv[2])) { + printf("Invalid target input. Exiting.\n"); freeMemory(arr); return 1; } + target = atoi(argv[2]); // Perform binary search int result = binarySearch(arr, size, target); @@ -72,29 +82,41 @@ int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); } -// Function to get user input for the array -void getInputArray(int **arr, int *size) { - printf("Enter the number of elements in the array: "); - if (scanf("%d", size) != 1 || *size <= 0) { - printf("Invalid size. Exiting.\n"); - return; - } - - *arr = (int *)malloc(*size * sizeof(int)); +// Function to parse input string and populate the array +int parseInput(const char *input, int **arr) { + char *token; + int size = 0; + int capacity = 10; // Initial capacity + *arr = malloc(capacity * sizeof(int)); if (*arr == NULL) { printf("Memory allocation failed. Exiting.\n"); - return; + return 1; } - printf("Enter %d elements (unsorted): ", *size); - for (int i = 0; i < *size; i++) { - if (scanf("%d", &(*arr)[i]) != 1) { - printf("Invalid input. Exiting.\n"); + // Tokenize the input string based on commas + token = strtok((char *)input, ","); + while (token) { + if (!isValidNumber(token)) { + printf("Invalid number detected: '%s'. Exiting.\n", token); freeMemory(*arr); - *arr = NULL; // Set to NULL to avoid double free - return; + return 1; // Exit if a number is invalid + } + + if (size >= capacity) { + capacity *= 2; + *arr = realloc(*arr, capacity * sizeof(int)); + if (*arr == NULL) { + printf("Memory reallocation failed. Exiting.\n"); + return 1; + } } + (*arr)[size++] = atoi(token); + token = strtok(NULL, ","); } + + // Resize the array to the actual size + *arr = realloc(*arr, size * sizeof(int)); + return 0; // Successful parsing } // Function to free allocated memory @@ -113,3 +135,10 @@ int isSorted(const int arr[], int size) { } return 1; // Array is sorted } + +// Function to check if a string is a valid number +int isValidNumber(const char *str) { + char *end; + strtol(str, &end, 10); // Convert string to long + return (*end == '\0' || *end == '\n'); // Check if the entire string was valid +} From bca6b207cf47b7569d3b13a42f0c335c393193f2 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 27 Oct 2024 13:01:36 -0700 Subject: [PATCH 05/44] Follow documentation to the letter --- archive/c/c/binary-search.c | 50 ++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index c29941762..6c845866c 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -1,18 +1,20 @@ #include #include #include +#include // Function prototypes int binarySearch(const int arr[], int size, int target); int compare(const void *a, const void *b); -int parseInput(const char *input, int **arr); +int parseInput(const char *input, int **arr, int *size); void freeMemory(int *arr); int isSorted(const int arr[], int size); int isValidNumber(const char *str); +char* trimWhitespace(char *str); int main(int argc, char *argv[]) { if (argc != 3) { - printf("Usage: %s \n", argv[0]); + printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); return 1; } @@ -20,23 +22,21 @@ int main(int argc, char *argv[]) { int size = 0; // Parse the input array from the first argument - if (parseInput(argv[1], &arr) != 0) { + if (parseInput(argv[1], &arr, &size) != 0) { return 1; // Exit if parsing fails } - // Update size - size = sizeof(arr) / sizeof(arr[0]); - // Check if the array is sorted if (!isSorted(arr, size)) { - printf("The array is not sorted. Sorting the array now...\n"); - qsort(arr, size, sizeof(int), compare); + printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); + freeMemory(arr); + return 1; } // Get target value from the second argument int target; if (!isValidNumber(argv[2])) { - printf("Invalid target input. Exiting.\n"); + printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); freeMemory(arr); return 1; } @@ -45,9 +45,9 @@ int main(int argc, char *argv[]) { // Perform binary search int result = binarySearch(arr, size, target); if (result != -1) { - printf("Element found at index: %d\n", result); + printf("true\n"); } else { - printf("Element not found.\n"); + printf("false\n"); } // Free allocated memory @@ -83,9 +83,8 @@ int compare(const void *a, const void *b) { } // Function to parse input string and populate the array -int parseInput(const char *input, int **arr) { +int parseInput(const char *input, int **arr, int *size) { char *token; - int size = 0; int capacity = 10; // Initial capacity *arr = malloc(capacity * sizeof(int)); if (*arr == NULL) { @@ -94,28 +93,34 @@ int parseInput(const char *input, int **arr) { } // Tokenize the input string based on commas - token = strtok((char *)input, ","); + char *inputCopy = strdup(input); + token = strtok(inputCopy, ","); + *size = 0; while (token) { + trimWhitespace(token); // Trim whitespace around token if (!isValidNumber(token)) { printf("Invalid number detected: '%s'. Exiting.\n", token); freeMemory(*arr); + free(inputCopy); return 1; // Exit if a number is invalid } - if (size >= capacity) { + if (*size >= capacity) { capacity *= 2; *arr = realloc(*arr, capacity * sizeof(int)); if (*arr == NULL) { printf("Memory reallocation failed. Exiting.\n"); + free(inputCopy); return 1; } } - (*arr)[size++] = atoi(token); + (*arr)[(*size)++] = atoi(token); token = strtok(NULL, ","); } // Resize the array to the actual size - *arr = realloc(*arr, size * sizeof(int)); + *arr = realloc(*arr, *size * sizeof(int)); + free(inputCopy); // Free the input copy return 0; // Successful parsing } @@ -142,3 +147,14 @@ int isValidNumber(const char *str) { strtol(str, &end, 10); // Convert string to long return (*end == '\0' || *end == '\n'); // Check if the entire string was valid } + +// Function to trim whitespace from a string +char* trimWhitespace(char *str) { + // Trim leading whitespace + while (isspace((unsigned char)*str)) str++; + // Trim trailing whitespace + char *end = str + strlen(str) - 1; + while (end > str && isspace((unsigned char)*end)) end--; + *(end + 1) = '\0'; // Null terminate after the last non-space character + return str; +} From 6a1105c7d652bb18b5484d0a345a70c7cbc6397c Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 09:14:19 -0700 Subject: [PATCH 06/44] for the win? (e.g. check that array is not empty) --- archive/c/c/binary-search.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index 6c845866c..e43bd1a02 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -26,6 +26,13 @@ int main(int argc, char *argv[]) { return 1; // Exit if parsing fails } + // Check if the size of the array is at least 1 + if (size < 1) { + printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); + freeMemory(arr); + return 1; + } + // Check if the array is sorted if (!isSorted(arr, size)) { printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); From 7e838d0a3eec3bac98291f0a2aa4439297416922 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 14:22:30 -0700 Subject: [PATCH 07/44] Clean Up & Refactor --- archive/c/c/binary-search.c | 95 ++++++++++--------------------------- 1 file changed, 24 insertions(+), 71 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index e43bd1a02..b4f9c73e8 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -5,57 +5,34 @@ // Function prototypes int binarySearch(const int arr[], int size, int target); -int compare(const void *a, const void *b); int parseInput(const char *input, int **arr, int *size); void freeMemory(int *arr); int isSorted(const int arr[], int size); int isValidNumber(const char *str); char* trimWhitespace(char *str); +void handleError(const char *message); int main(int argc, char *argv[]) { if (argc != 3) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - return 1; + handleError("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); } int *arr = NULL; int size = 0; // Parse the input array from the first argument - if (parseInput(argv[1], &arr, &size) != 0) { - return 1; // Exit if parsing fails - } - - // Check if the size of the array is at least 1 - if (size < 1) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - freeMemory(arr); - return 1; - } - - // Check if the array is sorted - if (!isSorted(arr, size)) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - freeMemory(arr); - return 1; + if (parseInput(argv[1], &arr, &size) != 0 || size < 1 || !isSorted(arr, size)) { + handleError("Invalid input: Please provide a valid list of sorted integers."); } // Get target value from the second argument - int target; if (!isValidNumber(argv[2])) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - freeMemory(arr); - return 1; + handleError("Invalid number: Please provide a valid integer to find."); } - target = atoi(argv[2]); + int target = atoi(argv[2]); // Perform binary search - int result = binarySearch(arr, size, target); - if (result != -1) { - printf("true\n"); - } else { - printf("false\n"); - } + printf(binarySearch(arr, size, target) != -1 ? "true\n" : "false\n"); // Free allocated memory freeMemory(arr); @@ -64,86 +41,56 @@ int main(int argc, char *argv[]) { // Function to perform binary search int binarySearch(const int arr[], int size, int target) { - int left = 0; - int right = size - 1; + int left = 0, right = size - 1; while (left <= right) { int mid = left + (right - left) / 2; - - if (arr[mid] == target) { - return mid; // Target found - } - - if (arr[mid] < target) { - left = mid + 1; // Move right - } else { - right = mid - 1; // Move left - } + if (arr[mid] == target) return mid; // Target found + (arr[mid] < target) ? (left = mid + 1) : (right = mid - 1); // Move left or right } - return -1; // Target not found } -// Comparison function for qsort -int compare(const void *a, const void *b) { - return (*(int *)a - *(int *)b); -} - // Function to parse input string and populate the array int parseInput(const char *input, int **arr, int *size) { char *token; int capacity = 10; // Initial capacity *arr = malloc(capacity * sizeof(int)); - if (*arr == NULL) { - printf("Memory allocation failed. Exiting.\n"); - return 1; - } + if (!*arr) handleError("Memory allocation failed."); - // Tokenize the input string based on commas char *inputCopy = strdup(input); token = strtok(inputCopy, ","); *size = 0; + while (token) { - trimWhitespace(token); // Trim whitespace around token + trimWhitespace(token); if (!isValidNumber(token)) { - printf("Invalid number detected: '%s'. Exiting.\n", token); - freeMemory(*arr); free(inputCopy); - return 1; // Exit if a number is invalid + handleError("Invalid number detected."); } if (*size >= capacity) { capacity *= 2; *arr = realloc(*arr, capacity * sizeof(int)); - if (*arr == NULL) { - printf("Memory reallocation failed. Exiting.\n"); - free(inputCopy); - return 1; - } + if (!*arr) handleError("Memory reallocation failed."); } (*arr)[(*size)++] = atoi(token); token = strtok(NULL, ","); } - // Resize the array to the actual size - *arr = realloc(*arr, *size * sizeof(int)); - free(inputCopy); // Free the input copy + free(inputCopy); return 0; // Successful parsing } // Function to free allocated memory void freeMemory(int *arr) { - if (arr != NULL) { - free(arr); - } + free(arr); } // Function to check if the array is sorted int isSorted(const int arr[], int size) { for (int i = 1; i < size; i++) { - if (arr[i] < arr[i - 1]) { - return 0; // Array is not sorted - } + if (arr[i] < arr[i - 1]) return 0; // Array is not sorted } return 1; // Array is sorted } @@ -165,3 +112,9 @@ char* trimWhitespace(char *str) { *(end + 1) = '\0'; // Null terminate after the last non-space character return str; } + +// Function to handle errors +void handleError(const char *message) { + fprintf(stderr, "%s\n", message); + exit(1); +} From e6816cbd0f66e646d34306dc74087f22ea07610f Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 14:29:51 -0700 Subject: [PATCH 08/44] Clean Up & Refactor --- archive/c/c/binary-search.c | 95 ++++++++++--------------------------- 1 file changed, 24 insertions(+), 71 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index e43bd1a02..b4f9c73e8 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -5,57 +5,34 @@ // Function prototypes int binarySearch(const int arr[], int size, int target); -int compare(const void *a, const void *b); int parseInput(const char *input, int **arr, int *size); void freeMemory(int *arr); int isSorted(const int arr[], int size); int isValidNumber(const char *str); char* trimWhitespace(char *str); +void handleError(const char *message); int main(int argc, char *argv[]) { if (argc != 3) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - return 1; + handleError("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); } int *arr = NULL; int size = 0; // Parse the input array from the first argument - if (parseInput(argv[1], &arr, &size) != 0) { - return 1; // Exit if parsing fails - } - - // Check if the size of the array is at least 1 - if (size < 1) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - freeMemory(arr); - return 1; - } - - // Check if the array is sorted - if (!isSorted(arr, size)) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - freeMemory(arr); - return 1; + if (parseInput(argv[1], &arr, &size) != 0 || size < 1 || !isSorted(arr, size)) { + handleError("Invalid input: Please provide a valid list of sorted integers."); } // Get target value from the second argument - int target; if (!isValidNumber(argv[2])) { - printf("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - freeMemory(arr); - return 1; + handleError("Invalid number: Please provide a valid integer to find."); } - target = atoi(argv[2]); + int target = atoi(argv[2]); // Perform binary search - int result = binarySearch(arr, size, target); - if (result != -1) { - printf("true\n"); - } else { - printf("false\n"); - } + printf(binarySearch(arr, size, target) != -1 ? "true\n" : "false\n"); // Free allocated memory freeMemory(arr); @@ -64,86 +41,56 @@ int main(int argc, char *argv[]) { // Function to perform binary search int binarySearch(const int arr[], int size, int target) { - int left = 0; - int right = size - 1; + int left = 0, right = size - 1; while (left <= right) { int mid = left + (right - left) / 2; - - if (arr[mid] == target) { - return mid; // Target found - } - - if (arr[mid] < target) { - left = mid + 1; // Move right - } else { - right = mid - 1; // Move left - } + if (arr[mid] == target) return mid; // Target found + (arr[mid] < target) ? (left = mid + 1) : (right = mid - 1); // Move left or right } - return -1; // Target not found } -// Comparison function for qsort -int compare(const void *a, const void *b) { - return (*(int *)a - *(int *)b); -} - // Function to parse input string and populate the array int parseInput(const char *input, int **arr, int *size) { char *token; int capacity = 10; // Initial capacity *arr = malloc(capacity * sizeof(int)); - if (*arr == NULL) { - printf("Memory allocation failed. Exiting.\n"); - return 1; - } + if (!*arr) handleError("Memory allocation failed."); - // Tokenize the input string based on commas char *inputCopy = strdup(input); token = strtok(inputCopy, ","); *size = 0; + while (token) { - trimWhitespace(token); // Trim whitespace around token + trimWhitespace(token); if (!isValidNumber(token)) { - printf("Invalid number detected: '%s'. Exiting.\n", token); - freeMemory(*arr); free(inputCopy); - return 1; // Exit if a number is invalid + handleError("Invalid number detected."); } if (*size >= capacity) { capacity *= 2; *arr = realloc(*arr, capacity * sizeof(int)); - if (*arr == NULL) { - printf("Memory reallocation failed. Exiting.\n"); - free(inputCopy); - return 1; - } + if (!*arr) handleError("Memory reallocation failed."); } (*arr)[(*size)++] = atoi(token); token = strtok(NULL, ","); } - // Resize the array to the actual size - *arr = realloc(*arr, *size * sizeof(int)); - free(inputCopy); // Free the input copy + free(inputCopy); return 0; // Successful parsing } // Function to free allocated memory void freeMemory(int *arr) { - if (arr != NULL) { - free(arr); - } + free(arr); } // Function to check if the array is sorted int isSorted(const int arr[], int size) { for (int i = 1; i < size; i++) { - if (arr[i] < arr[i - 1]) { - return 0; // Array is not sorted - } + if (arr[i] < arr[i - 1]) return 0; // Array is not sorted } return 1; // Array is sorted } @@ -165,3 +112,9 @@ char* trimWhitespace(char *str) { *(end + 1) = '\0'; // Null terminate after the last non-space character return str; } + +// Function to handle errors +void handleError(const char *message) { + fprintf(stderr, "%s\n", message); + exit(1); +} From 702809789f4949bbc1564fb8951e8e5fd6ac23df Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 15:27:47 -0700 Subject: [PATCH 09/44] Fix error message --- archive/c/c/binary-search.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index b4f9c73e8..2ad044c03 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -10,11 +10,11 @@ void freeMemory(int *arr); int isSorted(const int arr[], int size); int isValidNumber(const char *str); char* trimWhitespace(char *str); -void handleError(const char *message); +void handleError(const char *message, int usageMessage); int main(int argc, char *argv[]) { if (argc != 3) { - handleError("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); + handleError("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")", 1); } int *arr = NULL; @@ -22,12 +22,12 @@ int main(int argc, char *argv[]) { // Parse the input array from the first argument if (parseInput(argv[1], &arr, &size) != 0 || size < 1 || !isSorted(arr, size)) { - handleError("Invalid input: Please provide a valid list of sorted integers."); + handleError("Invalid input: Please provide a valid list of sorted integers.", 1); } // Get target value from the second argument if (!isValidNumber(argv[2])) { - handleError("Invalid number: Please provide a valid integer to find."); + handleError("Invalid number: Please provide a valid integer to find.", 1); } int target = atoi(argv[2]); @@ -56,7 +56,7 @@ int parseInput(const char *input, int **arr, int *size) { char *token; int capacity = 10; // Initial capacity *arr = malloc(capacity * sizeof(int)); - if (!*arr) handleError("Memory allocation failed."); + if (!*arr) handleError("Memory allocation failed.", 0); char *inputCopy = strdup(input); token = strtok(inputCopy, ","); @@ -66,13 +66,13 @@ int parseInput(const char *input, int **arr, int *size) { trimWhitespace(token); if (!isValidNumber(token)) { free(inputCopy); - handleError("Invalid number detected."); + handleError("Invalid number detected.", 1); } if (*size >= capacity) { capacity *= 2; *arr = realloc(*arr, capacity * sizeof(int)); - if (!*arr) handleError("Memory reallocation failed."); + if (!*arr) handleError("Memory reallocation failed.", 0); } (*arr)[(*size)++] = atoi(token); token = strtok(NULL, ","); @@ -114,7 +114,10 @@ char* trimWhitespace(char *str) { } // Function to handle errors -void handleError(const char *message) { +void handleError(const char *message, int usageMessage) { fprintf(stderr, "%s\n", message); + if (usageMessage) { + fprintf(stderr, "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); + } exit(1); } From de08b320f259961e4ae5ad99268a895c4d125f37 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 16:00:55 -0700 Subject: [PATCH 10/44] Update error message handling --- archive/c/c/binary-search.c | 77 ++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 26 deletions(-) diff --git a/archive/c/c/binary-search.c b/archive/c/c/binary-search.c index 2ad044c03..c555db76c 100644 --- a/archive/c/c/binary-search.c +++ b/archive/c/c/binary-search.c @@ -5,16 +5,16 @@ // Function prototypes int binarySearch(const int arr[], int size, int target); -int parseInput(const char *input, int **arr, int *size); -void freeMemory(int *arr); int isSorted(const int arr[], int size); int isValidNumber(const char *str); char* trimWhitespace(char *str); -void handleError(const char *message, int usageMessage); +int parseInput(const char *input, int **arr, int *size); +void freeMemory(int *arr); +void printErrorAndExit(const char *message, int *arr); int main(int argc, char *argv[]) { if (argc != 3) { - handleError("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")", 1); + printErrorAndExit("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n", NULL); } int *arr = NULL; @@ -22,17 +22,19 @@ int main(int argc, char *argv[]) { // Parse the input array from the first argument if (parseInput(argv[1], &arr, &size) != 0 || size < 1 || !isSorted(arr, size)) { - handleError("Invalid input: Please provide a valid list of sorted integers.", 1); + printErrorAndExit("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n", arr); } // Get target value from the second argument if (!isValidNumber(argv[2])) { - handleError("Invalid number: Please provide a valid integer to find.", 1); + printErrorAndExit("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n", arr); } + int target = atoi(argv[2]); // Perform binary search - printf(binarySearch(arr, size, target) != -1 ? "true\n" : "false\n"); + int result = binarySearch(arr, size, target); + printf(result != -1 ? "true\n" : "false\n"); // Free allocated memory freeMemory(arr); @@ -41,13 +43,23 @@ int main(int argc, char *argv[]) { // Function to perform binary search int binarySearch(const int arr[], int size, int target) { - int left = 0, right = size - 1; + int left = 0; + int right = size - 1; while (left <= right) { int mid = left + (right - left) / 2; - if (arr[mid] == target) return mid; // Target found - (arr[mid] < target) ? (left = mid + 1) : (right = mid - 1); // Move left or right + + if (arr[mid] == target) { + return mid; // Target found + } + + if (arr[mid] < target) { + left = mid + 1; // Move right + } else { + right = mid - 1; // Move left + } } + return -1; // Target not found } @@ -56,29 +68,40 @@ int parseInput(const char *input, int **arr, int *size) { char *token; int capacity = 10; // Initial capacity *arr = malloc(capacity * sizeof(int)); - if (!*arr) handleError("Memory allocation failed.", 0); + if (*arr == NULL) { + printf("Memory allocation failed. Exiting.\n"); + return 1; + } + // Tokenize the input string based on commas char *inputCopy = strdup(input); token = strtok(inputCopy, ","); *size = 0; - while (token) { - trimWhitespace(token); + trimWhitespace(token); // Trim whitespace around token if (!isValidNumber(token)) { + printf("Invalid number detected: '%s'. Exiting.\n", token); + freeMemory(*arr); free(inputCopy); - handleError("Invalid number detected.", 1); + return 1; // Exit if a number is invalid } if (*size >= capacity) { capacity *= 2; *arr = realloc(*arr, capacity * sizeof(int)); - if (!*arr) handleError("Memory reallocation failed.", 0); + if (*arr == NULL) { + printf("Memory reallocation failed. Exiting.\n"); + free(inputCopy); + return 1; + } } (*arr)[(*size)++] = atoi(token); token = strtok(NULL, ","); } - free(inputCopy); + // Resize the array to the actual size + *arr = realloc(*arr, *size * sizeof(int)); + free(inputCopy); // Free the input copy return 0; // Successful parsing } @@ -87,10 +110,21 @@ void freeMemory(int *arr) { free(arr); } +// Function to print error message and exit +void printErrorAndExit(const char *message, int *arr) { + if (arr != NULL) { + freeMemory(arr); + } + printf("%s", message); + exit(1); +} + // Function to check if the array is sorted int isSorted(const int arr[], int size) { for (int i = 1; i < size; i++) { - if (arr[i] < arr[i - 1]) return 0; // Array is not sorted + if (arr[i] < arr[i - 1]) { + return 0; // Array is not sorted + } } return 1; // Array is sorted } @@ -112,12 +146,3 @@ char* trimWhitespace(char *str) { *(end + 1) = '\0'; // Null terminate after the last non-space character return str; } - -// Function to handle errors -void handleError(const char *message, int usageMessage) { - fprintf(stderr, "%s\n", message); - if (usageMessage) { - fprintf(stderr, "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n"); - } - exit(1); -} From 29511a4380c970fe9679db7dec1197604b67804c Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 16:52:00 -0700 Subject: [PATCH 11/44] Add Convex Hull --- archive/c/c/convex-hull.c | 106 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 archive/c/c/convex-hull.c diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c new file mode 100644 index 000000000..07682e22c --- /dev/null +++ b/archive/c/c/convex-hull.c @@ -0,0 +1,106 @@ +#include +#include +#include +#include + +typedef struct { + int x, y; +} Point; + +int orientation(Point p, Point q, Point r) { + int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + if (val == 0) return 0; // Collinear + return (val > 0) ? 1 : 2; // Clock or counterclock wise +} + +void convexHull(Point points[], int n) { + if (n < 3) { + printf("Convex hull not possible with less than 3 points.\n"); + return; + } + + int leftmost = 0; + for (int i = 1; i < n; i++) { + if (points[i].x < points[leftmost].x) { + leftmost = i; + } + } + + int p = leftmost, q; + do { + printf("(%d, %d) ", points[p].x, points[p].y); + q = (p + 1) % n; + for (int i = 0; i < n; i++) { + if (orientation(points[p], points[i], points[q]) == 2) { + q = i; + } + } + p = q; + } while (p != leftmost); + + printf("\n"); +} + +int isInteger(const char *s) { + while (*s) { + if (!isdigit(*s) && *s != '-') return 0; + s++; + } + return 1; +} + +void parseCoordinates(char *xStr, char *yStr, Point **points, int *n) { + char *xToken = strtok(xStr, ","); + char *yToken = strtok(yStr, ","); + int count = 0; + + while (xToken && yToken) { + if (!isInteger(xToken) || !isInteger(yToken)) { + printf("Invalid Integers\n"); + exit(1); + } + (*points)[count].x = atoi(xToken); + (*points)[count].y = atoi(yToken); + count++; + xToken = strtok(NULL, ","); + yToken = strtok(NULL, ","); + } + + if (xToken || yToken) { + printf("Different Cardinality\n"); + exit(1); + } + + *n = count; +} + +int main(int argc, char *argv[]) { + if (argc != 3) { + printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); + return 1; + } + + char *xStr = argv[1]; + char *yStr = argv[2]; + + Point *points = malloc(100 * sizeof(Point)); // Assume a maximum of 100 points for simplicity + if (!points) { + printf("Memory allocation failed\n"); + return 1; + } + + int n = 0; + parseCoordinates(xStr, yStr, &points, &n); + + if (n < 3) { + printf("Convex hull not possible with less than 3 points.\n"); + free(points); + return 1; + } + + printf("The points in the convex hull are: "); + convexHull(points, n); + + free(points); + return 0; +} From 643eb70fd25fb559c910c65cfbdb9f506b546b1d Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 17:28:22 -0700 Subject: [PATCH 12/44] Update test handling --- archive/c/c/convex-hull.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index 07682e22c..b337ee6fb 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -28,7 +28,7 @@ void convexHull(Point points[], int n) { int p = leftmost, q; do { - printf("(%d, %d) ", points[p].x, points[p].y); + printf("(%d, %d)\n", points[p].x, points[p].y); q = (p + 1) % n; for (int i = 0; i < n; i++) { if (orientation(points[p], points[i], points[q]) == 2) { @@ -37,8 +37,6 @@ void convexHull(Point points[], int n) { } p = q; } while (p != leftmost); - - printf("\n"); } int isInteger(const char *s) { @@ -98,7 +96,7 @@ int main(int argc, char *argv[]) { return 1; } - printf("The points in the convex hull are: "); + printf("The points in the convex hull are:\n"); convexHull(points, n); free(points); From d0f82131f382d62e60550bd676f2133ed90dab8c Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Mon, 28 Oct 2024 17:48:34 -0700 Subject: [PATCH 13/44] Clean Up & Refactor --- archive/c/c/convex-hull.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index b337ee6fb..3327c18a1 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -47,6 +47,13 @@ int isInteger(const char *s) { return 1; } +void checkInputValidity(char *xStr, char *yStr) { + if (strlen(xStr) == 0 || strlen(yStr) == 0) { + printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); + exit(1); + } +} + void parseCoordinates(char *xStr, char *yStr, Point **points, int *n) { char *xToken = strtok(xStr, ","); char *yToken = strtok(yStr, ","); @@ -81,6 +88,9 @@ int main(int argc, char *argv[]) { char *xStr = argv[1]; char *yStr = argv[2]; + // Check input validity for empty strings + checkInputValidity(xStr, yStr); + Point *points = malloc(100 * sizeof(Point)); // Assume a maximum of 100 points for simplicity if (!points) { printf("Memory allocation failed\n"); From 51f982eaf7ef924d70f2c2576818ebafa2fda0c9 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 11:38:27 -0700 Subject: [PATCH 14/44] for the win? --- archive/c/c/convex-hull.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index 3327c18a1..ebfa41553 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -10,7 +10,7 @@ typedef struct { int orientation(Point p, Point q, Point r) { int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // Collinear - return (val > 0) ? 1 : 2; // Clock or counterclock wise + return (val > 0) ? 1 : 2; // Clockwise or counterclockwise } void convexHull(Point points[], int n) { @@ -47,7 +47,7 @@ int isInteger(const char *s) { return 1; } -void checkInputValidity(char *xStr, char *yStr) { +void validateInputs(char *xStr, char *yStr) { if (strlen(xStr) == 0 || strlen(yStr) == 0) { printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); exit(1); @@ -88,8 +88,8 @@ int main(int argc, char *argv[]) { char *xStr = argv[1]; char *yStr = argv[2]; - // Check input validity for empty strings - checkInputValidity(xStr, yStr); + // Validate input for empty strings + validateInputs(xStr, yStr); Point *points = malloc(100 * sizeof(Point)); // Assume a maximum of 100 points for simplicity if (!points) { From fe4f138a0b75b9a07d670cddb8b94361b3b3ac53 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 12:29:16 -0700 Subject: [PATCH 15/44] Fix input validation and output format for convex hull calculation + Add checks for empty inputs, matching cardinality, and valid integers + Adjust output format to ensure correct line breaks for points --- archive/c/c/convex-hull.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index ebfa41553..b26b084e2 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -7,12 +7,14 @@ typedef struct { int x, y; } Point; +// Function to determine the orientation of the triplet (p, q, r) int orientation(Point p, Point q, Point r) { int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // Collinear return (val > 0) ? 1 : 2; // Clockwise or counterclockwise } +// Function to compute the convex hull using the Gift Wrapping algorithm void convexHull(Point points[], int n) { if (n < 3) { printf("Convex hull not possible with less than 3 points.\n"); @@ -39,6 +41,7 @@ void convexHull(Point points[], int n) { } while (p != leftmost); } +// Function to check if a string is a valid integer int isInteger(const char *s) { while (*s) { if (!isdigit(*s) && *s != '-') return 0; @@ -47,6 +50,7 @@ int isInteger(const char *s) { return 1; } +// Function to validate inputs void validateInputs(char *xStr, char *yStr) { if (strlen(xStr) == 0 || strlen(yStr) == 0) { printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); @@ -54,6 +58,7 @@ void validateInputs(char *xStr, char *yStr) { } } +// Function to parse coordinates from input strings void parseCoordinates(char *xStr, char *yStr, Point **points, int *n) { char *xToken = strtok(xStr, ","); char *yToken = strtok(yStr, ","); @@ -77,6 +82,11 @@ void parseCoordinates(char *xStr, char *yStr, Point **points, int *n) { } *n = count; + + if (count < 3) { + printf("Convex hull not possible with less than 3 points.\n"); + exit(1); + } } int main(int argc, char *argv[]) { @@ -91,7 +101,7 @@ int main(int argc, char *argv[]) { // Validate input for empty strings validateInputs(xStr, yStr); - Point *points = malloc(100 * sizeof(Point)); // Assume a maximum of 100 points for simplicity + Point *points = malloc(100 * sizeof(Point)); // Assume a maximum of 100 points if (!points) { printf("Memory allocation failed\n"); return 1; @@ -100,12 +110,6 @@ int main(int argc, char *argv[]) { int n = 0; parseCoordinates(xStr, yStr, &points, &n); - if (n < 3) { - printf("Convex hull not possible with less than 3 points.\n"); - free(points); - return 1; - } - printf("The points in the convex hull are:\n"); convexHull(points, n); From 793dc0a147ec0117029e6b55121d9c64b57bb774 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:03:21 -0700 Subject: [PATCH 16/44] Add command line argument handling for x and y coordinates + Implement input validation for cases: no input, missing y, invalid shape, different cardinality, and invalid integers + Developed the Gift Wrapping algorithm to compute the convex hull + Ensure output format matches requirements for unit testing --- archive/c/c/convex-hull.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index b26b084e2..4ac3c18ed 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -43,8 +43,11 @@ void convexHull(Point points[], int n) { // Function to check if a string is a valid integer int isInteger(const char *s) { + if (*s == '-') s++; // Allow negative integers + if (*s == '\0') return 0; // Empty after optional '-' + while (*s) { - if (!isdigit(*s) && *s != '-') return 0; + if (!isdigit(*s)) return 0; s++; } return 1; From aa58d244e7f6f20e05b923a1aa63ee6ef4d8a39d Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:35:22 -0700 Subject: [PATCH 17/44] brand new implementation --- archive/c/c/convex-hull.c | 145 +++++++++++++++++++++----------------- 1 file changed, 79 insertions(+), 66 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index 4ac3c18ed..f82af058c 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -1,121 +1,134 @@ #include #include #include -#include +#include typedef struct { - int x, y; + int x; + int y; } Point; -// Function to determine the orientation of the triplet (p, q, r) +int compare(const void *p1, const void *p2) { + Point *point1 = (Point *)p1; + Point *point2 = (Point *)p2; + + if (point1->x != point2->x) { + return point1->x - point2->x; + } + return point1->y - point2->y; +} + int orientation(Point p, Point q, Point r) { int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - if (val == 0) return 0; // Collinear - return (val > 0) ? 1 : 2; // Clockwise or counterclockwise + return (val == 0) ? 0 : (val > 0) ? 1 : 2; } -// Function to compute the convex hull using the Gift Wrapping algorithm void convexHull(Point points[], int n) { - if (n < 3) { - printf("Convex hull not possible with less than 3 points.\n"); - return; - } + if (n < 3) return; - int leftmost = 0; - for (int i = 1; i < n; i++) { - if (points[i].x < points[leftmost].x) { - leftmost = i; - } - } + Point hull[n]; + + qsort(points, n, sizeof(Point), compare); - int p = leftmost, q; + int l = 0; + for (int i = 1; i < n; i++) + if (points[i].x < points[l].x) + l = i; + + int p = l, q; do { - printf("(%d, %d)\n", points[p].x, points[p].y); + hull[0] = points[p]; q = (p + 1) % n; + for (int i = 0; i < n; i++) { if (orientation(points[p], points[i], points[q]) == 2) { q = i; } } + p = q; - } while (p != leftmost); -} + } while (p != l); + + for (int i = 0; i < n; i++) { + bool found = false; + for (int j = 0; j < n; j++) { + if (hull[j].x == points[i].x && hull[j].y == points[i].y) { + found = true; + break; + } + } + if (!found) { + hull[n++] = points[i]; + } + } -// Function to check if a string is a valid integer -int isInteger(const char *s) { - if (*s == '-') s++; // Allow negative integers - if (*s == '\0') return 0; // Empty after optional '-' + for (int i = 0; i < n; i++) { + printf("(%d, %d)\n", hull[i].x, hull[i].y); + } +} +bool isInteger(const char *s) { while (*s) { - if (!isdigit(*s)) return 0; + if (*s < '0' || *s > '9') { + return false; + } s++; } - return 1; + return true; } -// Function to validate inputs -void validateInputs(char *xStr, char *yStr) { - if (strlen(xStr) == 0 || strlen(yStr) == 0) { - printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); - exit(1); - } -} +void parseCoordinates(char *inputX, char *inputY) { + char *tokenX = strtok(inputX, ","); + char *tokenY = strtok(inputY, ","); -// Function to parse coordinates from input strings -void parseCoordinates(char *xStr, char *yStr, Point **points, int *n) { - char *xToken = strtok(xStr, ","); - char *yToken = strtok(yStr, ","); + Point *points = NULL; int count = 0; - while (xToken && yToken) { - if (!isInteger(xToken) || !isInteger(yToken)) { + while (tokenX && tokenY) { + if (!isInteger(tokenX) || !isInteger(tokenY)) { printf("Invalid Integers\n"); - exit(1); + return; } - (*points)[count].x = atoi(xToken); - (*points)[count].y = atoi(yToken); + + points = realloc(points, sizeof(Point) * (count + 1)); + points[count].x = atoi(tokenX); + points[count].y = atoi(tokenY); count++; - xToken = strtok(NULL, ","); - yToken = strtok(NULL, ","); + + tokenX = strtok(NULL, ","); + tokenY = strtok(NULL, ","); } - if (xToken || yToken) { + if (tokenX || tokenY) { printf("Different Cardinality\n"); - exit(1); + free(points); + return; } - *n = count; - if (count < 3) { - printf("Convex hull not possible with less than 3 points.\n"); - exit(1); + printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); + free(points); + return; } + + convexHull(points, count); + free(points); } int main(int argc, char *argv[]) { if (argc != 3) { - printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); + printf("Usage: please provide two coordinate lists (x, y)\n"); return 1; } - char *xStr = argv[1]; - char *yStr = argv[2]; + char *inputX = argv[1]; + char *inputY = argv[2]; - // Validate input for empty strings - validateInputs(xStr, yStr); - - Point *points = malloc(100 * sizeof(Point)); // Assume a maximum of 100 points - if (!points) { - printf("Memory allocation failed\n"); + if (strlen(inputY) == 0) { + printf("Missing Y\n"); return 1; } - int n = 0; - parseCoordinates(xStr, yStr, &points, &n); - - printf("The points in the convex hull are:\n"); - convexHull(points, n); - - free(points); + parseCoordinates(inputX, inputY); return 0; } From bd69cb4e5fe7970fed13d7757d1e114b8e2ea2eb Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:47:15 -0700 Subject: [PATCH 18/44] Refactor error handling to eliminate code repetition for usage messages --- archive/c/c/convex-hull.c | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index f82af058c..b14d7c284 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -8,6 +8,11 @@ typedef struct { int y; } Point; +void printUsageAndExit() { + printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); + exit(1); +} + int compare(const void *p1, const void *p2) { Point *point1 = (Point *)p1; Point *point2 = (Point *)p2; @@ -86,8 +91,7 @@ void parseCoordinates(char *inputX, char *inputY) { while (tokenX && tokenY) { if (!isInteger(tokenX) || !isInteger(tokenY)) { - printf("Invalid Integers\n"); - return; + printUsageAndExit(); } points = realloc(points, sizeof(Point) * (count + 1)); @@ -100,15 +104,11 @@ void parseCoordinates(char *inputX, char *inputY) { } if (tokenX || tokenY) { - printf("Different Cardinality\n"); - free(points); - return; + printUsageAndExit(); } if (count < 3) { - printf("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n"); - free(points); - return; + printUsageAndExit(); } convexHull(points, count); @@ -117,8 +117,7 @@ void parseCoordinates(char *inputX, char *inputY) { int main(int argc, char *argv[]) { if (argc != 3) { - printf("Usage: please provide two coordinate lists (x, y)\n"); - return 1; + printUsageAndExit(); } char *inputX = argv[1]; From 54d6812e5da4a10937716d13b764f71eda33bb25 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:57:25 -0700 Subject: [PATCH 19/44] Use same error message everywhere --- archive/c/c/convex-hull.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index b14d7c284..3e5e0ce19 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -29,8 +29,6 @@ int orientation(Point p, Point q, Point r) { } void convexHull(Point points[], int n) { - if (n < 3) return; - Point hull[n]; qsort(points, n, sizeof(Point), compare); @@ -124,8 +122,7 @@ int main(int argc, char *argv[]) { char *inputY = argv[2]; if (strlen(inputY) == 0) { - printf("Missing Y\n"); - return 1; + printUsageAndExit(); } parseCoordinates(inputX, inputY); From db2fd2e07ad3f9d6d056735816af0c2086116283 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Tue, 29 Oct 2024 13:59:39 -0700 Subject: [PATCH 20/44] Handle negative numbers --- archive/c/c/convex-hull.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index 3e5e0ce19..dee326aab 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -71,6 +71,21 @@ void convexHull(Point points[], int n) { } bool isInteger(const char *s) { + // Check for an empty string + if (*s == '\0') { + return false; + } + + // Allow a leading negative sign + if (*s == '-') { + s++; // Move to the next character + // If there's no digit after the negative sign, it's not a valid integer + if (*s == '\0') { + return false; + } + } + + // Check that all remaining characters are digits while (*s) { if (*s < '0' || *s > '9') { return false; From 63147653a5b3abbefaeb38862344053d1eece1f9 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Wed, 30 Oct 2024 17:29:04 -0700 Subject: [PATCH 21/44] Fix convex hull logic to correctly output hull points --- archive/c/c/convex-hull.c | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index dee326aab..b8d014065 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -30,6 +30,7 @@ int orientation(Point p, Point q, Point r) { void convexHull(Point points[], int n) { Point hull[n]; + int hullCount = 0; qsort(points, n, sizeof(Point), compare); @@ -40,7 +41,7 @@ void convexHull(Point points[], int n) { int p = l, q; do { - hull[0] = points[p]; + hull[hullCount++] = points[p]; q = (p + 1) % n; for (int i = 0; i < n; i++) { @@ -52,20 +53,7 @@ void convexHull(Point points[], int n) { p = q; } while (p != l); - for (int i = 0; i < n; i++) { - bool found = false; - for (int j = 0; j < n; j++) { - if (hull[j].x == points[i].x && hull[j].y == points[i].y) { - found = true; - break; - } - } - if (!found) { - hull[n++] = points[i]; - } - } - - for (int i = 0; i < n; i++) { + for (int i = 0; i < hullCount; i++) { printf("(%d, %d)\n", hull[i].x, hull[i].y); } } From 9f03c2bb172ec943045d86ea98b8a5e1403f1621 Mon Sep 17 00:00:00 2001 From: rzuckerm Date: Sat, 16 Nov 2024 08:09:23 -0600 Subject: [PATCH 22/44] Fix Convex Hull in C --- archive/c/c/convex-hull.c | 119 +++++++++++++++++++++++++++----------- 1 file changed, 85 insertions(+), 34 deletions(-) diff --git a/archive/c/c/convex-hull.c b/archive/c/c/convex-hull.c index b8d014065..153651cfc 100644 --- a/archive/c/c/convex-hull.c +++ b/archive/c/c/convex-hull.c @@ -2,6 +2,7 @@ #include #include #include +#include typedef struct { int x; @@ -58,60 +59,110 @@ void convexHull(Point points[], int n) { } } +// Function to check if a string is a valid number bool isInteger(const char *s) { - // Check for an empty string - if (*s == '\0') { + char *end; + strtol(s, &end, 10); // Convert string to long + return (*end == '\0' || *end == '\n'); // Check if the entire string was valid +} + +// Function to trim whitespace from a string +char* trimWhitespace(char *str) { + // Trim leading whitespace + while (isspace((unsigned char)*str)) str++; + // Trim trailing whitespace + char *end = str + strlen(str) - 1; + while (end > str && isspace((unsigned char)*end)) end--; + *(end + 1) = '\0'; // Null terminate after the last non-space character + return str; +} + +// Function to parse input string and populate the array +int parseInput(const char *input, int **arr, int *size) { + char *token; + int capacity = 10; // Initial capacity + *arr = malloc(capacity * sizeof(int)); + if (*arr == NULL) { return false; } - // Allow a leading negative sign - if (*s == '-') { - s++; // Move to the next character - // If there's no digit after the negative sign, it's not a valid integer - if (*s == '\0') { - return false; - } + // Tokenize the input string based on commas + char *inputCopy = strdup(input); + if (inputCopy == NULL) { + free(*arr); + *arr = NULL; + return false; } - // Check that all remaining characters are digits - while (*s) { - if (*s < '0' || *s > '9') { - return false; + token = strtok(inputCopy, ","); + *size = 0; + while (token) { + trimWhitespace(token); // Trim whitespace around token + if (!isInteger(token)) { + free(*arr); + free(inputCopy); + *arr = NULL; + return false; // Exit if a number is invalid } - s++; + + if (*size >= capacity) { + capacity *= 2; + *arr = realloc(*arr, capacity * sizeof(int)); + if (*arr == NULL) { + free(inputCopy); + return false; + } + } + (*arr)[(*size)++] = atoi(token); + token = strtok(NULL, ","); } - return true; -} -void parseCoordinates(char *inputX, char *inputY) { - char *tokenX = strtok(inputX, ","); - char *tokenY = strtok(inputY, ","); + // Resize the array to the actual size + *arr = realloc(*arr, *size * sizeof(int)); + free(inputCopy); // Free the input copy + if (*arr == NULL) { + return false; + } - Point *points = NULL; - int count = 0; + return true; // Successful parsing +} - while (tokenX && tokenY) { - if (!isInteger(tokenX) || !isInteger(tokenY)) { - printUsageAndExit(); +void parseCoordinates(char *inputX, char *inputY) { + int *xCoords = NULL; + int *yCoords = NULL; + int xSize = 0; + int ySize = 0; + if (!parseInput(inputX, &xCoords, &xSize) || + !parseInput(inputY, &yCoords, &ySize) || + xSize != ySize || + xSize < 3) { + if (xCoords != NULL) { + free(xCoords); } - points = realloc(points, sizeof(Point) * (count + 1)); - points[count].x = atoi(tokenX); - points[count].y = atoi(tokenY); - count++; + if (yCoords != NULL) { + free(yCoords); + } - tokenX = strtok(NULL, ","); - tokenY = strtok(NULL, ","); + printUsageAndExit(); } - if (tokenX || tokenY) { + int count = xSize; + Point *points = malloc(sizeof(Point) * count); + if (points == NULL) { + free(xCoords); + free(yCoords); printUsageAndExit(); } - if (count < 3) { - printUsageAndExit(); + for (int i = 0; i < count; i++) { + points[i].x = xCoords[i]; + points[i].y = yCoords[i]; } + free(xCoords); + free(yCoords); + convexHull(points, count); free(points); } @@ -124,7 +175,7 @@ int main(int argc, char *argv[]) { char *inputX = argv[1]; char *inputY = argv[2]; - if (strlen(inputY) == 0) { + if (strlen(inputX) == 0 || strlen(inputY) == 0) { printUsageAndExit(); } From 13b1aab9b86cb7bb89246d74cf80759755198c5e Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Fri, 17 Jan 2025 19:48:56 -0500 Subject: [PATCH 23/44] Add job-sequencing.c --- archive/c/c/job-sequencing.c | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 archive/c/c/job-sequencing.c diff --git a/archive/c/c/job-sequencing.c b/archive/c/c/job-sequencing.c new file mode 100644 index 000000000..6e51aa7c5 --- /dev/null +++ b/archive/c/c/job-sequencing.c @@ -0,0 +1,64 @@ +#include +#include + +typedef struct { + int id; // Job ID + int profit; // Profit of the job + int deadline; // Deadline of the job +} Job; + +// Function to compare two jobs based on profit +int compareJobs(const void* a, const void* b) { + Job* jobA = (Job*)a; + Job* jobB = (Job*)b; + return jobB->profit - jobA->profit; // Sort in descending order of profit +} + +// Function to perform job sequencing +void jobSequencing(Job jobs[], int n) { + // Sort jobs based on profit + qsort(jobs, n, sizeof(Job), compareJobs); + + // To keep track of free time slots + int result[n]; // Result array to store the sequence of jobs + int slot[n]; // To keep track of free time slots + for (int i = 0; i < n; i++) { + slot[i] = 0; // Initialize all slots as free + } + + // Iterate over the jobs + for (int i = 0; i < n; i++) { + // Find a free slot for this job (going backwards) + for (int j = (jobs[i].deadline < n ? jobs[i].deadline : n) - 1; j >= 0; j--) { + if (slot[j] == 0) { // If the slot is free + slot[j] = 1; // Mark this slot as occupied + result[j] = jobs[i].id; // Assign job to this slot + break; + } + } + } + + // Print the scheduled jobs + printf("Scheduled jobs: "); + for (int i = 0; i < n; i++) { + if (slot[i]) { // Print only occupied slots + printf("Job %d ", result[i]); + } + } + printf("\n"); +} + +int main() { + Job jobs[] = { + {1, 100, 2}, + {2, 19, 1}, + {3, 27, 2}, + {4, 25, 1}, + {5, 15, 3} + }; + int n = sizeof(jobs) / sizeof(jobs[0]); + + jobSequencing(jobs, n); // Perform job sequencing + + return 0; +} From fe0426a3981c9f0cafeb23c981935b68eb9e42dd Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Fri, 17 Jan 2025 19:58:29 -0500 Subject: [PATCH 24/44] Update solution --- archive/c/c/job-sequencing.c | 102 +++++++++++++++++++++-------------- 1 file changed, 63 insertions(+), 39 deletions(-) diff --git a/archive/c/c/job-sequencing.c b/archive/c/c/job-sequencing.c index 6e51aa7c5..848f4f305 100644 --- a/archive/c/c/job-sequencing.c +++ b/archive/c/c/job-sequencing.c @@ -1,64 +1,88 @@ #include #include +#include + +#define MAX_JOBS 100 typedef struct { - int id; // Job ID - int profit; // Profit of the job - int deadline; // Deadline of the job + int profit; + int deadline; } Job; -// Function to compare two jobs based on profit -int compareJobs(const void* a, const void* b) { - Job* jobA = (Job*)a; - Job* jobB = (Job*)b; - return jobB->profit - jobA->profit; // Sort in descending order of profit +int compare(const void* a, const void* b) { + return ((Job*)b)->profit - ((Job*)a)->profit; +} + +int min(int a, int b) { + return (a < b) ? a : b; +} + +int max(int a, int b) { + return (a > b) ? a : b; } -// Function to perform job sequencing -void jobSequencing(Job jobs[], int n) { - // Sort jobs based on profit - qsort(jobs, n, sizeof(Job), compareJobs); +int jobSequencing(Job jobs[], int n) { + qsort(jobs, n, sizeof(Job), compare); - // To keep track of free time slots - int result[n]; // Result array to store the sequence of jobs - int slot[n]; // To keep track of free time slots + int maxDeadline = 0; for (int i = 0; i < n; i++) { - slot[i] = 0; // Initialize all slots as free + maxDeadline = max(maxDeadline, jobs[i].deadline); } - // Iterate over the jobs + int slot[MAX_JOBS] = {0}; + int totalProfit = 0; + for (int i = 0; i < n; i++) { - // Find a free slot for this job (going backwards) - for (int j = (jobs[i].deadline < n ? jobs[i].deadline : n) - 1; j >= 0; j--) { - if (slot[j] == 0) { // If the slot is free - slot[j] = 1; // Mark this slot as occupied - result[j] = jobs[i].id; // Assign job to this slot + for (int j = min(n, jobs[i].deadline) - 1; j >= 0; j--) { + if (slot[j] == 0) { + slot[j] = 1; + totalProfit += jobs[i].profit; break; } } } - // Print the scheduled jobs - printf("Scheduled jobs: "); - for (int i = 0; i < n; i++) { - if (slot[i]) { // Print only occupied slots - printf("Job %d ", result[i]); - } + return totalProfit; +} + +int* parseInput(char* input, int* size) { + int* arr = malloc(MAX_JOBS * sizeof(int)); + char* token = strtok(input, ", "); + *size = 0; + while (token != NULL) { + arr[(*size)++] = atoi(token); + token = strtok(NULL, ", "); } - printf("\n"); + return arr; } -int main() { - Job jobs[] = { - {1, 100, 2}, - {2, 19, 1}, - {3, 27, 2}, - {4, 25, 1}, - {5, 15, 3} - }; - int n = sizeof(jobs) / sizeof(jobs[0]); +int main(int argc, char* argv[]) { + if (argc != 3) { + printf("Usage: please provide a list of profits and a list of deadlines\n"); + return 1; + } + + int profitSize, deadlineSize; + int* profits = parseInput(argv[1], &profitSize); + int* deadlines = parseInput(argv[2], &deadlineSize); + + if (profitSize != deadlineSize) { + printf("Usage: please provide a list of profits and a list of deadlines\n"); + free(profits); + free(deadlines); + return 1; + } + + Job jobs[MAX_JOBS]; + for (int i = 0; i < profitSize; i++) { + jobs[i].profit = profits[i]; + jobs[i].deadline = deadlines[i]; + } - jobSequencing(jobs, n); // Perform job sequencing + int result = jobSequencing(jobs, profitSize); + printf("%d\n", result); + free(profits); + free(deadlines); return 0; } From 1d17029abcef1c7e03a928905a953d226ff5bd51 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 10:32:50 -0500 Subject: [PATCH 25/44] Add fraction-math.c --- archive/c/c/fraction-math.c | 95 +++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 archive/c/c/fraction-math.c diff --git a/archive/c/c/fraction-math.c b/archive/c/c/fraction-math.c new file mode 100644 index 000000000..737dd3e40 --- /dev/null +++ b/archive/c/c/fraction-math.c @@ -0,0 +1,95 @@ +#include + +// Structure to represent a fraction +typedef struct { + int numerator; + int denominator; +} Fraction; + +// Function to simplify a fraction +Fraction simplify(Fraction frac) { + int gcd = 1; + for (int i = 1; i <= frac.numerator && i <= frac.denominator; i++) { + if (frac.numerator % i == 0 && frac.denominator % i == 0) { + gcd = i; + } + } + frac.numerator /= gcd; + frac.denominator /= gcd; + return frac; +} + +// Function to add two fractions +Fraction add(Fraction a, Fraction b) { + Fraction result; + result.numerator = a.numerator * b.denominator + b.numerator * a.denominator; + result.denominator = a.denominator * b.denominator; + return simplify(result); +} + +// Function to subtract two fractions +Fraction subtract(Fraction a, Fraction b) { + Fraction result; + result.numerator = a.numerator * b.denominator - b.numerator * a.denominator; + result.denominator = a.denominator * b.denominator; + return simplify(result); +} + +// Function to multiply two fractions +Fraction multiply(Fraction a, Fraction b) { + Fraction result; + result.numerator = a.numerator * b.numerator; + result.denominator = a.denominator * b.denominator; + return simplify(result); +} + +// Function to divide two fractions +Fraction divide(Fraction a, Fraction b) { + Fraction result; + result.numerator = a.numerator * b.denominator; + result.denominator = a.denominator * b.numerator; + return simplify(result); +} + +// Function to print a fraction +void printFraction(Fraction frac) { + printf("%d/%d\n", frac.numerator, frac.denominator); +} + +int main() { + Fraction frac1, frac2, result; + + // Input for first fraction + printf("Enter first fraction (numerator denominator): "); + scanf("%d %d", &frac1.numerator, &frac1.denominator); + + // Input for second fraction + printf("Enter second fraction (numerator denominator): "); + scanf("%d %d", &frac2.numerator, &frac2.denominator); + + // Add fractions + result = add(frac1, frac2); + printf("Sum: "); + printFraction(result); + + // Subtract fractions + result = subtract(frac1, frac2); + printf("Difference: "); + printFraction(result); + + // Multiply fractions + result = multiply(frac1, frac2); + printf("Product: "); + printFraction(result); + + // Divide fractions + if (frac2.numerator != 0) { + result = divide(frac1, frac2); + printf("Quotient: "); + printFraction(result); + } else { + printf("Error: Division by zero.\n"); + } + + return 0; +} From bca9bd664bb7e2cae2cf0ceaaf11d891bdf48a41 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 10:37:24 -0500 Subject: [PATCH 26/44] Update solution --- archive/c/c/fraction-math.c | 146 ++++++++++++++++++++++-------------- 1 file changed, 88 insertions(+), 58 deletions(-) diff --git a/archive/c/c/fraction-math.c b/archive/c/c/fraction-math.c index 737dd3e40..58457595d 100644 --- a/archive/c/c/fraction-math.c +++ b/archive/c/c/fraction-math.c @@ -1,94 +1,124 @@ #include +#include +#include -// Structure to represent a fraction typedef struct { int numerator; int denominator; } Fraction; -// Function to simplify a fraction -Fraction simplify(Fraction frac) { - int gcd = 1; - for (int i = 1; i <= frac.numerator && i <= frac.denominator; i++) { - if (frac.numerator % i == 0 && frac.denominator % i == 0) { - gcd = i; - } +int gcd(int a, int b) { + if (b == 0) return a; + return gcd(b, a % b); +} + +Fraction simplify(Fraction f) { + int g = gcd(abs(f.numerator), abs(f.denominator)); + f.numerator /= g; + f.denominator /= g; + if (f.denominator < 0) { + f.numerator = -f.numerator; + f.denominator = -f.denominator; } - frac.numerator /= gcd; - frac.denominator /= gcd; - return frac; + return f; +} + +Fraction parse_fraction(const char* str) { + Fraction f; + sscanf(str, "%d/%d", &f.numerator, &f.denominator); + return simplify(f); } -// Function to add two fractions Fraction add(Fraction a, Fraction b) { - Fraction result; - result.numerator = a.numerator * b.denominator + b.numerator * a.denominator; - result.denominator = a.denominator * b.denominator; + Fraction result = { + a.numerator * b.denominator + b.numerator * a.denominator, + a.denominator * b.denominator + }; return simplify(result); } -// Function to subtract two fractions Fraction subtract(Fraction a, Fraction b) { - Fraction result; - result.numerator = a.numerator * b.denominator - b.numerator * a.denominator; - result.denominator = a.denominator * b.denominator; + Fraction result = { + a.numerator * b.denominator - b.numerator * a.denominator, + a.denominator * b.denominator + }; return simplify(result); } -// Function to multiply two fractions Fraction multiply(Fraction a, Fraction b) { - Fraction result; - result.numerator = a.numerator * b.numerator; - result.denominator = a.denominator * b.denominator; + Fraction result = { + a.numerator * b.numerator, + a.denominator * b.denominator + }; return simplify(result); } -// Function to divide two fractions Fraction divide(Fraction a, Fraction b) { - Fraction result; - result.numerator = a.numerator * b.denominator; - result.denominator = a.denominator * b.numerator; + Fraction result = { + a.numerator * b.denominator, + a.denominator * b.numerator + }; return simplify(result); } -// Function to print a fraction -void printFraction(Fraction frac) { - printf("%d/%d\n", frac.numerator, frac.denominator); +int compare(Fraction a, Fraction b) { + int lhs = a.numerator * b.denominator; + int rhs = b.numerator * a.denominator; + if (lhs < rhs) return -1; + if (lhs > rhs) return 1; + return 0; } -int main() { - Fraction frac1, frac2, result; - - // Input for first fraction - printf("Enter first fraction (numerator denominator): "); - scanf("%d %d", &frac1.numerator, &frac1.denominator); - - // Input for second fraction - printf("Enter second fraction (numerator denominator): "); - scanf("%d %d", &frac2.numerator, &frac2.denominator); +void print_fraction(Fraction f) { + printf("%d/%d\n", f.numerator, f.denominator); +} - // Add fractions - result = add(frac1, frac2); - printf("Sum: "); - printFraction(result); +int main(int argc, char* argv[]) { + if (argc != 4) { + printf("Usage: ./fraction-math operand1 operator operand2\n"); + return 1; + } - // Subtract fractions - result = subtract(frac1, frac2); - printf("Difference: "); - printFraction(result); + Fraction a = parse_fraction(argv[1]); + Fraction b = parse_fraction(argv[3]); + char* op = argv[2]; - // Multiply fractions - result = multiply(frac1, frac2); - printf("Product: "); - printFraction(result); + Fraction result; + int cmp; - // Divide fractions - if (frac2.numerator != 0) { - result = divide(frac1, frac2); - printf("Quotient: "); - printFraction(result); + if (strcmp(op, "+") == 0) { + result = add(a, b); + print_fraction(result); + } else if (strcmp(op, "-") == 0) { + result = subtract(a, b); + print_fraction(result); + } else if (strcmp(op, "*") == 0) { + result = multiply(a, b); + print_fraction(result); + } else if (strcmp(op, "/") == 0) { + result = divide(a, b); + print_fraction(result); + } else if (strcmp(op, "==") == 0) { + cmp = compare(a, b); + printf("%d\n", cmp == 0); + } else if (strcmp(op, ">") == 0) { + cmp = compare(a, b); + printf("%d\n", cmp > 0); + } else if (strcmp(op, "<") == 0) { + cmp = compare(a, b); + printf("%d\n", cmp < 0); + } else if (strcmp(op, ">=") == 0) { + cmp = compare(a, b); + printf("%d\n", cmp >= 0); + } else if (strcmp(op, "<=") == 0) { + cmp = compare(a, b); + printf("%d\n", cmp <= 0); + } else if (strcmp(op, "!=") == 0) { + cmp = compare(a, b); + printf("%d\n", cmp != 0); } else { - printf("Error: Division by zero.\n"); + printf("Invalid operator\n"); + return 1; } return 0; From 8d08765c63c48b0a01289c81c05be95848066b79 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 17:59:56 -0500 Subject: [PATCH 27/44] Add depth-first-search.c --- archive/c/c/depth-first-search.c | 84 ++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 archive/c/c/depth-first-search.c diff --git a/archive/c/c/depth-first-search.c b/archive/c/c/depth-first-search.c new file mode 100644 index 000000000..835083a0a --- /dev/null +++ b/archive/c/c/depth-first-search.c @@ -0,0 +1,84 @@ +#include +#include + +#define MAX 100 + +// Structure for an adjacency list node +typedef struct Node { + int vertex; + struct Node* next; +} Node; + +// Structure for the graph +typedef struct Graph { + int numVertices; + Node* adjLists[MAX]; + int visited[MAX]; +} Graph; + +// Function to create a node +Node* createNode(int vertex) { + Node* newNode = (Node*)malloc(sizeof(Node)); + newNode->vertex = vertex; + newNode->next = NULL; + return newNode; +} + +// Function to create a graph +Graph* createGraph(int vertices) { + Graph* graph = (Graph*)malloc(sizeof(Graph)); + graph->numVertices = vertices; + + for (int i = 0; i < vertices; i++) { + graph->adjLists[i] = NULL; + graph->visited[i] = 0; + } + + return graph; +} + +// Function to add an edge to the graph +void addEdge(Graph* graph, int src, int dest) { + Node* newNode = createNode(dest); + newNode->next = graph->adjLists[src]; + graph->adjLists[src] = newNode; + + // For undirected graph, add an edge from dest to src as well + newNode = createNode(src); + newNode->next = graph->adjLists[dest]; + graph->adjLists[dest] = newNode; +} + +// Recursive DFS function +void DFS(Graph* graph, int vertex) { + graph->visited[vertex] = 1; // Mark the current node as visited + printf("%d ", vertex); // Print the visited node + + Node* adjList = graph->adjLists[vertex]; + Node* temp = adjList; + + // Visit all the adjacent vertices + while (temp != NULL) { + int connectedVertex = temp->vertex; + if (graph->visited[connectedVertex] == 0) { + DFS(graph, connectedVertex); + } + temp = temp->next; + } +} + +int main() { + Graph* graph = createGraph(5); // Create a graph with 5 vertices + + // Add edges to the graph + addEdge(graph, 0, 1); + addEdge(graph, 0, 2); + addEdge(graph, 1, 3); + addEdge(graph, 1, 4); + addEdge(graph, 2, 4); + + printf("Depth First Search starting from vertex 0:\n"); + DFS(graph, 0); // Perform DFS starting from vertex 0 + + return 0; +} From eb2648688b31b3ab54492d1394cccbc1cf2e52c7 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 18:04:51 -0500 Subject: [PATCH 28/44] Update solution --- archive/c/c/depth-first-search.c | 125 +++++++++++++++---------------- 1 file changed, 61 insertions(+), 64 deletions(-) diff --git a/archive/c/c/depth-first-search.c b/archive/c/c/depth-first-search.c index 835083a0a..71c145732 100644 --- a/archive/c/c/depth-first-search.c +++ b/archive/c/c/depth-first-search.c @@ -1,84 +1,81 @@ #include #include +#include +#include +#include -#define MAX 100 +#define MAX_NODES 100 -// Structure for an adjacency list node -typedef struct Node { - int vertex; - struct Node* next; -} Node; +int adjacency_matrix[MAX_NODES][MAX_NODES]; +int vertex_values[MAX_NODES]; +int num_nodes; +bool visited[MAX_NODES]; -// Structure for the graph -typedef struct Graph { - int numVertices; - Node* adjLists[MAX]; - int visited[MAX]; -} Graph; - -// Function to create a node -Node* createNode(int vertex) { - Node* newNode = (Node*)malloc(sizeof(Node)); - newNode->vertex = vertex; - newNode->next = NULL; - return newNode; +bool dfs(int node, int target) { + if (vertex_values[node] == target) { + return true; + } + visited[node] = true; + for (int i = 0; i < num_nodes; i++) { + if (adjacency_matrix[node][i] && !visited[i]) { + if (dfs(i, target)) { + return true; + } + } + } + return false; } -// Function to create a graph -Graph* createGraph(int vertices) { - Graph* graph = (Graph*)malloc(sizeof(Graph)); - graph->numVertices = vertices; - - for (int i = 0; i < vertices; i++) { - graph->adjLists[i] = NULL; - graph->visited[i] = 0; +bool depth_first_search(int target) { + memset(visited, 0, sizeof(visited)); + for (int i = 0; i < num_nodes; i++) { + if (!visited[i] && dfs(i, target)) { + return true; + } } - - return graph; + return false; } -// Function to add an edge to the graph -void addEdge(Graph* graph, int src, int dest) { - Node* newNode = createNode(dest); - newNode->next = graph->adjLists[src]; - graph->adjLists[src] = newNode; - - // For undirected graph, add an edge from dest to src as well - newNode = createNode(src); - newNode->next = graph->adjLists[dest]; - graph->adjLists[dest] = newNode; +void parse_matrix(char* input) { + char* token = strtok(input, ", "); + int i = 0, j = 0; + while (token != NULL) { + adjacency_matrix[i][j] = atoi(token); + j++; + if (j == num_nodes) { + i++; + j = 0; + } + token = strtok(NULL, ", "); + } } -// Recursive DFS function -void DFS(Graph* graph, int vertex) { - graph->visited[vertex] = 1; // Mark the current node as visited - printf("%d ", vertex); // Print the visited node - - Node* adjList = graph->adjLists[vertex]; - Node* temp = adjList; - - // Visit all the adjacent vertices - while (temp != NULL) { - int connectedVertex = temp->vertex; - if (graph->visited[connectedVertex] == 0) { - DFS(graph, connectedVertex); - } - temp = temp->next; +void parse_values(char* input) { + char* token = strtok(input, ", "); + int i = 0; + while (token != NULL) { + vertex_values[i++] = atoi(token); + token = strtok(NULL, ", "); } } -int main() { - Graph* graph = createGraph(5); // Create a graph with 5 vertices +int main(int argc, char* argv[]) { + if (argc != 4) { + printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\").\n"); + return 1; + } + + char* matrix_str = argv[1]; + char* values_str = argv[2]; + int target = atoi(argv[3]); + + num_nodes = (int)sqrt(strlen(matrix_str) / 2 + 1); - // Add edges to the graph - addEdge(graph, 0, 1); - addEdge(graph, 0, 2); - addEdge(graph, 1, 3); - addEdge(graph, 1, 4); - addEdge(graph, 2, 4); + parse_matrix(matrix_str); + parse_values(values_str); - printf("Depth First Search starting from vertex 0:\n"); - DFS(graph, 0); // Perform DFS starting from vertex 0 + bool result = depth_first_search(target); + printf(result ? "true\n" : "false\n"); return 0; } From 40cfc729fbddb22dd3b8b96a803178194223b11b Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 18:09:27 -0500 Subject: [PATCH 29/44] remove dependency on math library --- archive/c/c/depth-first-search.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/archive/c/c/depth-first-search.c b/archive/c/c/depth-first-search.c index 71c145732..cdf44d3b9 100644 --- a/archive/c/c/depth-first-search.c +++ b/archive/c/c/depth-first-search.c @@ -69,7 +69,17 @@ int main(int argc, char* argv[]) { char* values_str = argv[2]; int target = atoi(argv[3]); - num_nodes = (int)sqrt(strlen(matrix_str) / 2 + 1); + // Count the number of commas to determine the total elements + int total_elements = 1; + for (char* p = matrix_str; *p; p++) { + if (*p == ',') total_elements++; + } + + // Calculate num_nodes without using sqrt + num_nodes = 0; + while (num_nodes * num_nodes < total_elements) { + num_nodes++; + } parse_matrix(matrix_str); parse_values(values_str); @@ -79,3 +89,4 @@ int main(int argc, char* argv[]) { return 0; } + From dfff90977860e5b49dde4a182a91d29b1be50540 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 18:13:09 -0500 Subject: [PATCH 30/44] improve input validation and error handling --- archive/c/c/depth-first-search.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/archive/c/c/depth-first-search.c b/archive/c/c/depth-first-search.c index cdf44d3b9..2d17f2326 100644 --- a/archive/c/c/depth-first-search.c +++ b/archive/c/c/depth-first-search.c @@ -60,8 +60,8 @@ void parse_values(char* input) { } int main(int argc, char* argv[]) { - if (argc != 4) { - printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\").\n"); + if (argc != 4 || !*argv[1] || !*argv[2] || !*argv[3]) { + printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\")"); return 1; } From 47167d8f6de75ddb993b530f8d62abc711c0346e Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:18:36 -0500 Subject: [PATCH 31/44] bring back sqrt solution --- archive/c/c/depth-first-search.c | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/archive/c/c/depth-first-search.c b/archive/c/c/depth-first-search.c index 2d17f2326..71c145732 100644 --- a/archive/c/c/depth-first-search.c +++ b/archive/c/c/depth-first-search.c @@ -60,8 +60,8 @@ void parse_values(char* input) { } int main(int argc, char* argv[]) { - if (argc != 4 || !*argv[1] || !*argv[2] || !*argv[3]) { - printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\")"); + if (argc != 4) { + printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\").\n"); return 1; } @@ -69,17 +69,7 @@ int main(int argc, char* argv[]) { char* values_str = argv[2]; int target = atoi(argv[3]); - // Count the number of commas to determine the total elements - int total_elements = 1; - for (char* p = matrix_str; *p; p++) { - if (*p == ',') total_elements++; - } - - // Calculate num_nodes without using sqrt - num_nodes = 0; - while (num_nodes * num_nodes < total_elements) { - num_nodes++; - } + num_nodes = (int)sqrt(strlen(matrix_str) / 2 + 1); parse_matrix(matrix_str); parse_values(values_str); @@ -89,4 +79,3 @@ int main(int argc, char* argv[]) { return 0; } - From a48676d834909bf9673464559a612ec30f677c94 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:21:49 -0500 Subject: [PATCH 32/44] add math library linking flag for sqrt support --- archive/c/c/testinfo.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/archive/c/c/testinfo.yml b/archive/c/c/testinfo.yml index 61c6e8b87..098d27ba0 100644 --- a/archive/c/c/testinfo.yml +++ b/archive/c/c/testinfo.yml @@ -5,5 +5,5 @@ folder: container: image: "gcc" tag: "8.3" - build: "gcc -o {{ source.name }} {{ source.name }}{{ source.extension }}" + build: "gcc -o {{ source.name }} {{ source.name }}{{ source.extension }} -lm" cmd: "./{{ source.name }}" From cc5ba65fd4bc0bfc03733e9185bdec8a6c58d208 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:26:17 -0500 Subject: [PATCH 33/44] adjust error handling & output format --- archive/c/c/depth-first-search.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/archive/c/c/depth-first-search.c b/archive/c/c/depth-first-search.c index 71c145732..6ec43771e 100644 --- a/archive/c/c/depth-first-search.c +++ b/archive/c/c/depth-first-search.c @@ -60,8 +60,8 @@ void parse_values(char* input) { } int main(int argc, char* argv[]) { - if (argc != 4) { - printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\").\n"); + if (argc != 4 || !*argv[1] || !*argv[2] || !*argv[3]) { + printf("Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\")"); return 1; } @@ -69,7 +69,12 @@ int main(int argc, char* argv[]) { char* values_str = argv[2]; int target = atoi(argv[3]); - num_nodes = (int)sqrt(strlen(matrix_str) / 2 + 1); + int total_elements = 1; + for (char* p = matrix_str; *p; p++) { + if (*p == ',') total_elements++; + } + + num_nodes = (int)sqrt(total_elements); parse_matrix(matrix_str); parse_values(values_str); @@ -79,3 +84,4 @@ int main(int argc, char* argv[]) { return 0; } + From a29234e0d6e7910d5a53f7ee252e70eaf7bd1d23 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:45:32 -0500 Subject: [PATCH 34/44] add dijkstra.c --- archive/c/c/dijkstra.c | 161 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 archive/c/c/dijkstra.c diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c new file mode 100644 index 000000000..9ca1dfa95 --- /dev/null +++ b/archive/c/c/dijkstra.c @@ -0,0 +1,161 @@ +#include +#include +#include + +#define MAX 100 + +// Structure for a min-heap node +typedef struct { + int vertex; + int distance; +} MinHeapNode; + +// Structure for the min-heap +typedef struct { + int size; + int capacity; + int* pos; // To store the position of each vertex in the heap + MinHeapNode* array; +} MinHeap; + +// Function to create a new min-heap node +MinHeapNode* newMinHeapNode(int v, int dist) { + MinHeapNode* minHeapNode = (MinHeapNode*)malloc(sizeof(MinHeapNode)); + minHeapNode->vertex = v; + minHeapNode->distance = dist; + return minHeapNode; +} + +// Function to create a min-heap +MinHeap* createMinHeap(int capacity) { + MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap)); + minHeap->pos = (int*)malloc(capacity * sizeof(int)); + minHeap->size = 0; + minHeap->capacity = capacity; + minHeap->array = (MinHeapNode**)malloc(capacity * sizeof(MinHeapNode*)); + return minHeap; +} + +// Function to swap two nodes of the min-heap +void swapMinHeapNode(MinHeapNode** a, MinHeapNode** b) { + MinHeapNode* t = *a; + *a = *b; + *b = t; +} + +// Function to heapify the min-heap +void minHeapify(MinHeap* minHeap, int idx) { + int smallest = idx; + int left = 2 * idx + 1; + int right = 2 * idx + 2; + + if (left < minHeap->size && minHeap->array[left]->distance < minHeap->array[smallest]->distance) + smallest = left; + + if (right < minHeap->size && minHeap->array[right]->distance < minHeap->array[smallest]->distance) + smallest = right; + + if (smallest != idx) { + // Swap positions + MinHeapNode* smallestNode = minHeap->array[smallest]; + MinHeapNode* idxNode = minHeap->array[idx]; + + minHeap->pos[smallestNode->vertex] = idx; + minHeap->pos[idxNode->vertex] = smallest; + + swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); + minHeapify(minHeap, smallest); + } +} + +// Function to check if the min-heap is empty +int isEmpty(MinHeap* minHeap) { + return minHeap->size == 0; +} + +// Function to extract the minimum node from the min-heap +MinHeapNode* extractMin(MinHeap* minHeap) { + if (isEmpty(minHeap)) + return NULL; + + MinHeapNode* root = minHeap->array[0]; + + MinHeapNode* lastNode = minHeap->array[minHeap->size - 1]; + minHeap->array[0] = lastNode; + + minHeap->pos[root->vertex] = minHeap->size - 1; + minHeap->pos[lastNode->vertex] = 0; + + --minHeap->size; + minHeapify(minHeap, 0); + + return root; +} + +// Function to decrease the distance value of a given vertex +void decreaseKey(MinHeap* minHeap, int v, int dist) { + int i = minHeap->pos[v]; + + minHeap->array[i]->distance = dist; + + while (i && minHeap->array[i]->distance < minHeap->array[(i - 1) / 2]->distance) { + minHeap->pos[minHeap->array[i]->vertex] = (i - 1) / 2; + minHeap->pos[minHeap->array[(i - 1) / 2]->vertex] = i; + swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]); + i = (i - 1) / 2; + } +} + +// Function to check if a vertex is in the min-heap +int isInMinHeap(MinHeap* minHeap, int v) { + return minHeap->pos[v] < minHeap->size; +} + +// Function to implement Dijkstra's algorithm +void dijkstra(int graph[MAX][MAX], int src, int vertices) { + int dist[MAX]; // The output array. dist[i] holds the shortest distance from src to j + MinHeap* minHeap = createMinHeap(vertices); + + for (int v = 0; v < vertices; v++) { + dist[v] = INT_MAX; // Initialize all distances as infinite + minHeap->array[v] = newMinHeapNode(v, dist[v]); + minHeap->pos[v] = v; + } + + dist[src] = 0; + decreaseKey(minHeap, src, dist[src]); + minHeap->size = vertices; + + while (!isEmpty(minHeap)) { + MinHeapNode* minHeapNode = extractMin(minHeap); + int u = minHeapNode->vertex; + + for (int v = 0; v < vertices; v++) { + if (graph[u][v] && isInMinHeap(minHeap, v) && dist[u] != INT_MAX && + dist[u] + graph[u][v] < dist[v]) { + dist[v] = dist[u] + graph[u][v]; + decreaseKey(minHeap, v, dist[v]); + } + } + } + + printf("Vertex Distance from Source (%d)\n", src); + for (int i = 0; i < vertices; i++) + printf("%d \t\t %d\n", i, dist[i]); +} + +int main() { + // Example graph represented as an adjacency matrix + int graph[MAX][MAX] = { + {0, 10, 0, 30, 100}, + {10, 0, 50, 0, 0}, + {0, 50, 0, 20, 10}, + {30, 0, 20, 0, 60}, + {100, 0, 10, 60, 0} + }; + int vertices = 5; + + dijkstra(graph, 0, vertices); // Run Dijkstra starting from vertex 0 + + return 0; +} From 2f725237fd81afcc44cb0a3ebbc261f9143efa8b Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:50:16 -0500 Subject: [PATCH 35/44] update solution --- archive/c/c/dijkstra.c | 193 +++++++++++++---------------------------- 1 file changed, 61 insertions(+), 132 deletions(-) diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c index 9ca1dfa95..2bba9c8d0 100644 --- a/archive/c/c/dijkstra.c +++ b/archive/c/c/dijkstra.c @@ -1,161 +1,90 @@ #include #include +#include #include +#include -#define MAX 100 - -// Structure for a min-heap node -typedef struct { - int vertex; - int distance; -} MinHeapNode; - -// Structure for the min-heap -typedef struct { - int size; - int capacity; - int* pos; // To store the position of each vertex in the heap - MinHeapNode* array; -} MinHeap; - -// Function to create a new min-heap node -MinHeapNode* newMinHeapNode(int v, int dist) { - MinHeapNode* minHeapNode = (MinHeapNode*)malloc(sizeof(MinHeapNode)); - minHeapNode->vertex = v; - minHeapNode->distance = dist; - return minHeapNode; -} - -// Function to create a min-heap -MinHeap* createMinHeap(int capacity) { - MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap)); - minHeap->pos = (int*)malloc(capacity * sizeof(int)); - minHeap->size = 0; - minHeap->capacity = capacity; - minHeap->array = (MinHeapNode**)malloc(capacity * sizeof(MinHeapNode*)); - return minHeap; -} - -// Function to swap two nodes of the min-heap -void swapMinHeapNode(MinHeapNode** a, MinHeapNode** b) { - MinHeapNode* t = *a; - *a = *b; - *b = t; -} - -// Function to heapify the min-heap -void minHeapify(MinHeap* minHeap, int idx) { - int smallest = idx; - int left = 2 * idx + 1; - int right = 2 * idx + 2; - - if (left < minHeap->size && minHeap->array[left]->distance < minHeap->array[smallest]->distance) - smallest = left; +#define MAX_NODES 100 - if (right < minHeap->size && minHeap->array[right]->distance < minHeap->array[smallest]->distance) - smallest = right; +int dijkstra(int graph[MAX_NODES][MAX_NODES], int src, int dest, int n) { + int dist[MAX_NODES]; + bool sptSet[MAX_NODES]; - if (smallest != idx) { - // Swap positions - MinHeapNode* smallestNode = minHeap->array[smallest]; - MinHeapNode* idxNode = minHeap->array[idx]; - - minHeap->pos[smallestNode->vertex] = idx; - minHeap->pos[idxNode->vertex] = smallest; - - swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); - minHeapify(minHeap, smallest); + for (int i = 0; i < n; i++) { + dist[i] = INT_MAX; + sptSet[i] = false; } -} -// Function to check if the min-heap is empty -int isEmpty(MinHeap* minHeap) { - return minHeap->size == 0; -} - -// Function to extract the minimum node from the min-heap -MinHeapNode* extractMin(MinHeap* minHeap) { - if (isEmpty(minHeap)) - return NULL; + dist[src] = 0; - MinHeapNode* root = minHeap->array[0]; + for (int count = 0; count < n - 1; count++) { + int min = INT_MAX, min_index; - MinHeapNode* lastNode = minHeap->array[minHeap->size - 1]; - minHeap->array[0] = lastNode; + for (int v = 0; v < n; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; - minHeap->pos[root->vertex] = minHeap->size - 1; - minHeap->pos[lastNode->vertex] = 0; + int u = min_index; + sptSet[u] = true; - --minHeap->size; - minHeapify(minHeap, 0); + for (int v = 0; v < n; v++) + if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } - return root; + return dist[dest] == INT_MAX ? -1 : dist[dest]; } -// Function to decrease the distance value of a given vertex -void decreaseKey(MinHeap* minHeap, int v, int dist) { - int i = minHeap->pos[v]; - - minHeap->array[i]->distance = dist; - - while (i && minHeap->array[i]->distance < minHeap->array[(i - 1) / 2]->distance) { - minHeap->pos[minHeap->array[i]->vertex] = (i - 1) / 2; - minHeap->pos[minHeap->array[(i - 1) / 2]->vertex] = i; - swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]); - i = (i - 1) / 2; +int main(int argc, char *argv[]) { + if (argc != 4) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 1; } -} -// Function to check if a vertex is in the min-heap -int isInMinHeap(MinHeap* minHeap, int v) { - return minHeap->pos[v] < minHeap->size; -} + char *matrix = argv[1]; + int src = atoi(argv[2]); + int dest = atoi(argv[3]); -// Function to implement Dijkstra's algorithm -void dijkstra(int graph[MAX][MAX], int src, int vertices) { - int dist[MAX]; // The output array. dist[i] holds the shortest distance from src to j - MinHeap* minHeap = createMinHeap(vertices); + int n = 0; + for (int i = 0; matrix[i]; i++) + if (matrix[i] == ',') n++; + n = (int)sqrt(n + 1); - for (int v = 0; v < vertices; v++) { - dist[v] = INT_MAX; // Initialize all distances as infinite - minHeap->array[v] = newMinHeapNode(v, dist[v]); - minHeap->pos[v] = v; + if (n * n != strlen(matrix) / 2 + 1) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 1; } - dist[src] = 0; - decreaseKey(minHeap, src, dist[src]); - minHeap->size = vertices; - - while (!isEmpty(minHeap)) { - MinHeapNode* minHeapNode = extractMin(minHeap); - int u = minHeapNode->vertex; + if (src < 0 || dest < 0 || src >= n || dest >= n) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 1; + } - for (int v = 0; v < vertices; v++) { - if (graph[u][v] && isInMinHeap(minHeap, v) && dist[u] != INT_MAX && - dist[u] + graph[u][v] < dist[v]) { - dist[v] = dist[u] + graph[u][v]; - decreaseKey(minHeap, v, dist[v]); + int graph[MAX_NODES][MAX_NODES] = {0}; + char *token = strtok(matrix, ","); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (!token) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 1; + } + int weight = atoi(token); + if (weight < 0) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 1; } + graph[i][j] = weight; + token = strtok(NULL, ","); } } - printf("Vertex Distance from Source (%d)\n", src); - for (int i = 0; i < vertices; i++) - printf("%d \t\t %d\n", i, dist[i]); -} - -int main() { - // Example graph represented as an adjacency matrix - int graph[MAX][MAX] = { - {0, 10, 0, 30, 100}, - {10, 0, 50, 0, 0}, - {0, 50, 0, 20, 10}, - {30, 0, 20, 0, 60}, - {100, 0, 10, 60, 0} - }; - int vertices = 5; - - dijkstra(graph, 0, vertices); // Run Dijkstra starting from vertex 0 + int result = dijkstra(graph, src, dest, n); + if (result == -1) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + } else { + printf("%d\n", result); + } return 0; } From 5ce295d277b6da0e22aa6faa360c4a30133eef08 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:54:37 -0500 Subject: [PATCH 36/44] fix input parsing --- archive/c/c/dijkstra.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c index 2bba9c8d0..3980630dc 100644 --- a/archive/c/c/dijkstra.c +++ b/archive/c/c/dijkstra.c @@ -51,7 +51,7 @@ int main(int argc, char *argv[]) { if (matrix[i] == ',') n++; n = (int)sqrt(n + 1); - if (n * n != strlen(matrix) / 2 + 1) { + if (n * n != (strlen(matrix) - n + 1) / 2 + 1) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); return 1; } @@ -62,7 +62,7 @@ int main(int argc, char *argv[]) { } int graph[MAX_NODES][MAX_NODES] = {0}; - char *token = strtok(matrix, ","); + char *token = strtok(matrix, ", "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (!token) { @@ -75,7 +75,7 @@ int main(int argc, char *argv[]) { return 1; } graph[i][j] = weight; - token = strtok(NULL, ","); + token = strtok(NULL, ", "); } } @@ -88,3 +88,4 @@ int main(int argc, char *argv[]) { return 0; } + From f13d940a527ea6f326e0350b9685d517e993a4c5 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:58:07 -0500 Subject: [PATCH 37/44] update input parsing --- archive/c/c/dijkstra.c | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c index 3980630dc..124ec1519 100644 --- a/archive/c/c/dijkstra.c +++ b/archive/c/c/dijkstra.c @@ -51,11 +51,6 @@ int main(int argc, char *argv[]) { if (matrix[i] == ',') n++; n = (int)sqrt(n + 1); - if (n * n != (strlen(matrix) - n + 1) / 2 + 1) { - printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); - return 1; - } - if (src < 0 || dest < 0 || src >= n || dest >= n) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); return 1; @@ -63,12 +58,8 @@ int main(int argc, char *argv[]) { int graph[MAX_NODES][MAX_NODES] = {0}; char *token = strtok(matrix, ", "); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - if (!token) { - printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); - return 1; - } + for (int i = 0; i < n && token; i++) { + for (int j = 0; j < n && token; j++) { int weight = atoi(token); if (weight < 0) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); From f919d9a8c2ff698d5d1eefe96628c1e25b6125db Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 21:02:59 -0500 Subject: [PATCH 38/44] fix algorithm implementation & input parsing --- archive/c/c/dijkstra.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c index 124ec1519..557a67a9c 100644 --- a/archive/c/c/dijkstra.c +++ b/archive/c/c/dijkstra.c @@ -3,6 +3,7 @@ #include #include #include +#include #define MAX_NODES 100 @@ -46,10 +47,11 @@ int main(int argc, char *argv[]) { int src = atoi(argv[2]); int dest = atoi(argv[3]); - int n = 0; - for (int i = 0; matrix[i]; i++) + long long n = 0; + for (size_t i = 0; matrix[i]; i++) { if (matrix[i] == ',') n++; - n = (int)sqrt(n + 1); + } + n = (long long)sqrt((double)n + 1); if (src < 0 || dest < 0 || src >= n || dest >= n) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); @@ -70,7 +72,7 @@ int main(int argc, char *argv[]) { } } - int result = dijkstra(graph, src, dest, n); + int result = dijkstra(graph, src, dest, (int)n); if (result == -1) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); } else { @@ -79,4 +81,3 @@ int main(int argc, char *argv[]) { return 0; } - From 29de0db9912911d240ab6c5db443035e6593d75f Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 21:06:06 -0500 Subject: [PATCH 39/44] fix edge case handling --- archive/c/c/dijkstra.c | 52 +++++++++--------------------------------- 1 file changed, 11 insertions(+), 41 deletions(-) diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c index 557a67a9c..ad75d361b 100644 --- a/archive/c/c/dijkstra.c +++ b/archive/c/c/dijkstra.c @@ -1,42 +1,3 @@ -#include -#include -#include -#include -#include -#include - -#define MAX_NODES 100 - -int dijkstra(int graph[MAX_NODES][MAX_NODES], int src, int dest, int n) { - int dist[MAX_NODES]; - bool sptSet[MAX_NODES]; - - for (int i = 0; i < n; i++) { - dist[i] = INT_MAX; - sptSet[i] = false; - } - - dist[src] = 0; - - for (int count = 0; count < n - 1; count++) { - int min = INT_MAX, min_index; - - for (int v = 0; v < n; v++) - if (sptSet[v] == false && dist[v] <= min) - min = dist[v], min_index = v; - - int u = min_index; - sptSet[u] = true; - - for (int v = 0; v < n; v++) - if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX - && dist[u] + graph[u][v] < dist[v]) - dist[v] = dist[u] + graph[u][v]; - } - - return dist[dest] == INT_MAX ? -1 : dist[dest]; -} - int main(int argc, char *argv[]) { if (argc != 4) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); @@ -44,8 +5,17 @@ int main(int argc, char *argv[]) { } char *matrix = argv[1]; - int src = atoi(argv[2]); - int dest = atoi(argv[3]); + char *src_str = argv[2]; + char *dest_str = argv[3]; + + // Check for empty inputs + if (strlen(matrix) == 0 || strlen(src_str) == 0 || strlen(dest_str) == 0) { + printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 1; + } + + int src = atoi(src_str); + int dest = atoi(dest_str); long long n = 0; for (size_t i = 0; matrix[i]; i++) { From 94cf360e39ea4a2c760e660afe23063b5dc72e7a Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sat, 18 Jan 2025 21:10:00 -0500 Subject: [PATCH 40/44] undo brain fart --- archive/c/c/dijkstra.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/archive/c/c/dijkstra.c b/archive/c/c/dijkstra.c index ad75d361b..030401aee 100644 --- a/archive/c/c/dijkstra.c +++ b/archive/c/c/dijkstra.c @@ -1,3 +1,42 @@ +#include +#include +#include +#include +#include +#include + +#define MAX_NODES 100 + +int dijkstra(int graph[MAX_NODES][MAX_NODES], int src, int dest, int n) { + int dist[MAX_NODES]; + bool sptSet[MAX_NODES]; + + for (int i = 0; i < n; i++) { + dist[i] = INT_MAX; + sptSet[i] = false; + } + + dist[src] = 0; + + for (int count = 0; count < n - 1; count++) { + int min = INT_MAX, min_index; + + for (int v = 0; v < n; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + + int u = min_index; + sptSet[u] = true; + + for (int v = 0; v < n; v++) + if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + return dist[dest] == INT_MAX ? -1 : dist[dest]; +} + int main(int argc, char *argv[]) { if (argc != 4) { printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); From 93e2559ec6dcd1df751b08b093f28d6a22a30f00 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 19 Jan 2025 09:46:33 -0500 Subject: [PATCH 41/44] add josephus-problem.c --- archive/c/c/josephus-problem.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 archive/c/c/josephus-problem.c diff --git a/archive/c/c/josephus-problem.c b/archive/c/c/josephus-problem.c new file mode 100644 index 000000000..6ec3cab05 --- /dev/null +++ b/archive/c/c/josephus-problem.c @@ -0,0 +1,26 @@ +#include + +// Function to find the position of the last person remaining +int josephus(int n, int k) { + if (n == 1) + return 0; // Base case: only one person remains + else + return (josephus(n - 1, k) + k) % n; // Recursive case +} + +int main() { + int n, k; + + // Input number of people and step count + printf("Enter the number of people: "); + scanf("%d", &n); + printf("Enter the step count (k): "); + scanf("%d", &k); + + // Get the position (0-based index) and convert to 1-based index + int result = josephus(n, k) + 1; + + printf("The position of the last person remaining is: %d\n", result); + + return 0; +} From 096b450264d57136c13f7e4456d75cb538acf0b9 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 19 Jan 2025 09:49:56 -0500 Subject: [PATCH 42/44] Update solution --- archive/c/c/josephus-problem.c | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/archive/c/c/josephus-problem.c b/archive/c/c/josephus-problem.c index 6ec3cab05..bf6eb39cd 100644 --- a/archive/c/c/josephus-problem.c +++ b/archive/c/c/josephus-problem.c @@ -1,26 +1,34 @@ #include +#include -// Function to find the position of the last person remaining int josephus(int n, int k) { if (n == 1) - return 0; // Base case: only one person remains + return 1; else - return (josephus(n - 1, k) + k) % n; // Recursive case + return (josephus(n - 1, k) + k - 1) % n + 1; } -int main() { - int n, k; +int main(int argc, char *argv[]) { + if (argc != 3) { + printf("Usage: please input the total number of people and number of people to skip.\n"); + return 1; + } - // Input number of people and step count - printf("Enter the number of people: "); - scanf("%d", &n); - printf("Enter the step count (k): "); - scanf("%d", &k); + char *endptr; + int n = strtol(argv[1], &endptr, 10); + if (*endptr != '\0' || n <= 0) { + printf("Usage: please input the total number of people and number of people to skip.\n"); + return 1; + } - // Get the position (0-based index) and convert to 1-based index - int result = josephus(n, k) + 1; + int k = strtol(argv[2], &endptr, 10); + if (*endptr != '\0' || k <= 0) { + printf("Usage: please input the total number of people and number of people to skip.\n"); + return 1; + } - printf("The position of the last person remaining is: %d\n", result); + int result = josephus(n, k); + printf("%d\n", result); return 0; } From e8ebb1ff18c7d60efd070983b4e9742d37d670b5 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 19 Jan 2025 10:23:57 -0500 Subject: [PATCH 43/44] add longest-palindromic.substring.c --- archive/c/c/longest-palindromic-substring.c | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 archive/c/c/longest-palindromic-substring.c diff --git a/archive/c/c/longest-palindromic-substring.c b/archive/c/c/longest-palindromic-substring.c new file mode 100644 index 000000000..41ab402af --- /dev/null +++ b/archive/c/c/longest-palindromic-substring.c @@ -0,0 +1,58 @@ +#include +#include + +#define MAX_LENGTH 1000 + +// Function to expand around center and find palindrome length +int expandAroundCenter(const char* s, int left, int right) { + while (left >= 0 && right < strlen(s) && s[left] == s[right]) { + left--; + right++; + } + return right - left - 1; +} + +// Function to find the longest palindromic substring +void longestPalindromicSubstring(const char* s, char* result) { + if (s == NULL || strlen(s) == 0) { + strcpy(result, ""); + return; + } + + int start = 0, maxLength = 1; + int len = strlen(s); + + for (int i = 0; i < len; i++) { + int len1 = expandAroundCenter(s, i, i); // Odd length palindrome + int len2 = expandAroundCenter(s, i, i + 1); // Even length palindrome + int len = (len1 > len2) ? len1 : len2; + + if (len > maxLength) { + start = i - (len - 1) / 2; + maxLength = len; + } + } + + strncpy(result, s + start, maxLength); + result[maxLength] = '\0'; +} + +int main(int argc, char* argv[]) { + if (argc != 2) { + printf("Usage: please provide a string that contains at least one palindrome\n"); + return 1; + } + + const char* input = argv[1]; + char result[MAX_LENGTH]; + + longestPalindromicSubstring(input, result); + + if (strlen(result) == 0) { + printf("Usage: please provide a string that contains at least one palindrome\n"); + } else { + printf("%s\n", result); + } + + return 0; +} From b67fb0c746f51985707ba7aa491e1f730ed71d23 Mon Sep 17 00:00:00 2001 From: 2Clutch <13703683+2Clutch@users.noreply.github.com> Date: Sun, 19 Jan 2025 10:30:39 -0500 Subject: [PATCH 44/44] handle case with no valid palindromes in input --- archive/c/c/longest-palindromic-substring.c | 31 +++++++++++---------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/archive/c/c/longest-palindromic-substring.c b/archive/c/c/longest-palindromic-substring.c index 41ab402af..2217898d9 100644 --- a/archive/c/c/longest-palindromic-substring.c +++ b/archive/c/c/longest-palindromic-substring.c @@ -1,9 +1,9 @@ #include #include +#include #define MAX_LENGTH 1000 -// Function to expand around center and find palindrome length int expandAroundCenter(const char* s, int left, int right) { while (left >= 0 && right < strlen(s) && s[left] == s[right]) { left--; @@ -12,19 +12,18 @@ int expandAroundCenter(const char* s, int left, int right) { return right - left - 1; } -// Function to find the longest palindromic substring -void longestPalindromicSubstring(const char* s, char* result) { +bool longestPalindromicSubstring(const char* s, char* result) { if (s == NULL || strlen(s) == 0) { strcpy(result, ""); - return; + return false; } - int start = 0, maxLength = 1; + int start = 0, maxLength = 0; int len = strlen(s); for (int i = 0; i < len; i++) { - int len1 = expandAroundCenter(s, i, i); // Odd length palindrome - int len2 = expandAroundCenter(s, i, i + 1); // Even length palindrome + int len1 = expandAroundCenter(s, i, i); + int len2 = expandAroundCenter(s, i, i + 1); int len = (len1 > len2) ? len1 : len2; if (len > maxLength) { @@ -33,8 +32,14 @@ void longestPalindromicSubstring(const char* s, char* result) { } } - strncpy(result, s + start, maxLength); - result[maxLength] = '\0'; + if (maxLength > 1) { + strncpy(result, s + start, maxLength); + result[maxLength] = '\0'; + return true; + } + + strcpy(result, ""); + return false; } int main(int argc, char* argv[]) { @@ -46,12 +51,10 @@ int main(int argc, char* argv[]) { const char* input = argv[1]; char result[MAX_LENGTH]; - longestPalindromicSubstring(input, result); - - if (strlen(result) == 0) { - printf("Usage: please provide a string that contains at least one palindrome\n"); - } else { + if (longestPalindromicSubstring(input, result) && strlen(result) > 0) { printf("%s\n", result); + } else { + printf("Usage: please provide a string that contains at least one palindrome\n"); } return 0;