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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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/26] 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;