From f20371e94fe411d75dbff4d4e2dbbc274f34f227 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 13 Sep 2021 20:31:56 +0200 Subject: Bash and C solutions for week 130, part 1 --- challenge-130/abigail/bash/ch-1.sh | 25 ++++++++++++++++ challenge-130/abigail/c/ch-1.c | 59 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 challenge-130/abigail/bash/ch-1.sh create mode 100644 challenge-130/abigail/c/ch-1.c diff --git a/challenge-130/abigail/bash/ch-1.sh b/challenge-130/abigail/bash/ch-1.sh new file mode 100644 index 0000000000..64be01526e --- /dev/null +++ b/challenge-130/abigail/bash/ch-1.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +# +# See ../README.md +# + +# +# Run as: bash ch-1.sh < input-file +# + +set -f + +declare -A numbers + +while read -a input +do numbers=() + for i in "${input[@]}" + do ((numbers[$i] ++)) + done + for i in "${!numbers[@]}" + do if ((numbers[$i] % 2)) + then echo $i + fi + done +done diff --git a/challenge-130/abigail/c/ch-1.c b/challenge-130/abigail/c/ch-1.c new file mode 100644 index 0000000000..6d1fcfa038 --- /dev/null +++ b/challenge-130/abigail/c/ch-1.c @@ -0,0 +1,59 @@ +# include +# include +# include + +/* + * See ../README.md + */ + +/* + * Run as: cc -o ch-1.o ch-1.c; ./ch-1.o < input-file + */ + +int cmp (const void * a, const void * b) { + return (* (int *) a - * (int *) b); +} + +int main (void) { + char * line = NULL; + size_t len = 0; + size_t str_len; + + while ((str_len = getline (&line, &len, stdin)) != -1) { + char * line_ptr = line; + int offset = 0; + int count = 0; + int number; + while (sscanf (line_ptr, "%d%n", &number, &offset) == 1) { + count ++; + line_ptr += offset; + } + int * numbers; + if ((numbers = (int *) malloc (count * sizeof (int))) == NULL) { + perror ("Malloc failed"); + exit (1); + } + line_ptr = line; + count = 0; + while (sscanf (line_ptr, "%d%n", &numbers [count], &offset) == 1) { + count ++; + line_ptr += offset; + } + + qsort (numbers, count, sizeof (int), cmp); + + int found = 0; + for (int i = 0; i < count - 1; i += 2) { + if (numbers [i] != numbers [i + 1]) { + printf ("%d\n", numbers [i]); + found ++; + } + } + if (!found) { /* Must be last element */ + printf ("%d\n", numbers [count - 1]); + } + } + free (line); + + return (0); +} -- cgit