diff options
| -rw-r--r-- | challenge-111/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-111/abigail/c/ch-1.c | 49 |
2 files changed, 50 insertions, 0 deletions
diff --git a/challenge-111/abigail/README.md b/challenge-111/abigail/README.md index e78fafe291..92fe052262 100644 --- a/challenge-111/abigail/README.md +++ b/challenge-111/abigail/README.md @@ -33,6 +33,7 @@ languages, the fact input is sorted does not offer additional benefits. ### Solutions * [AWK](awk/ch-1.awk) * [Bash](bash/ch-1.sh) +* [C](c/ch-1.c) * [Perl](perl/ch-1.pl) ### Blog diff --git a/challenge-111/abigail/c/ch-1.c b/challenge-111/abigail/c/ch-1.c new file mode 100644 index 0000000000..a8804c7390 --- /dev/null +++ b/challenge-111/abigail/c/ch-1.c @@ -0,0 +1,49 @@ +# include <stdlib.h> +# include <stdio.h> +# include <string.h> + +/* + * See ../README.md + */ + +/* + * Run as: cc -o ch-1.o ch-1.c; ./ch-1.o < input-file + */ + +# define MATRIX_SIZE 5 +# define NR_OF_ELEMENTS (MATRIX_SIZE * MATRIX_SIZE) + +static int compare (const void *a, const void *b) { + return * (int *) a - * (int *) b; +} + +int main (void) { + int * matrix; + int target; + + if ((matrix = (int *) malloc (NR_OF_ELEMENTS * sizeof (int))) == NULL) { + perror ("Malloc failed"); + exit (1); + } + + /* + * Read in the matrix + */ + for (int i = 0; i < NR_OF_ELEMENTS; i ++) { + if (scanf ("%d", &matrix [i]) != 1) { + perror ("Scanf failed"); + exit (1); + } + } + + /* + * Read in the search data, and print 1/0 depending on whether + * the read number is in the matrix or not. + */ + while (scanf ("%d", &target) == 1) { + printf ("%d\n", bsearch (&target, matrix, NR_OF_ELEMENTS, + sizeof (int), compare) == NULL ? 0 : 1); + } + + return (0); +} |
