diff options
| author | Abigail <abigail@abigail.be> | 2021-01-27 00:29:48 +0100 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2021-01-27 00:29:48 +0100 |
| commit | 45121a3b1ac26d9806cc672d7dcbef8e162d1e18 (patch) | |
| tree | a7706847ed3ab66e7cfe820d0991cf1f440a4d5d /challenge-097 | |
| parent | c045cac9f990ed22afe8c2630a014c74baea3b46 (diff) | |
| download | perlweeklychallenge-club-45121a3b1ac26d9806cc672d7dcbef8e162d1e18.tar.gz perlweeklychallenge-club-45121a3b1ac26d9806cc672d7dcbef8e162d1e18.tar.bz2 perlweeklychallenge-club-45121a3b1ac26d9806cc672d7dcbef8e162d1e18.zip | |
C solution for week 97. part 2
Diffstat (limited to 'challenge-097')
| -rw-r--r-- | challenge-097/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-097/abigail/c/ch-2.c | 52 |
2 files changed, 53 insertions, 0 deletions
diff --git a/challenge-097/abigail/README.md b/challenge-097/abigail/README.md index e5b520217a..10240df509 100644 --- a/challenge-097/abigail/README.md +++ b/challenge-097/abigail/README.md @@ -67,6 +67,7 @@ Binary Substrings: ### Solutions * [AWK](awk/ch-2.awk) +* [C](c/ch-2.c) * [Perl](perl/ch-2.pl) ### Blog diff --git a/challenge-097/abigail/c/ch-2.c b/challenge-097/abigail/c/ch-2.c new file mode 100644 index 0000000000..dd1441f6a4 --- /dev/null +++ b/challenge-097/abigail/c/ch-2.c @@ -0,0 +1,52 @@ +# include <stdlib.h> +# include <stdio.h> +# include <string.h> +# include <unistd.h> +# include <ctype.h> + +/* + * See ../README.md + */ + +/* + * Run as: cc -o ch-2.o ch-2.c; ./ch-2.o -s SECTIONS < input-file + */ + +int main (int argc, char ** argv) { + char * line = NULL; + size_t len = 0; + size_t strlen; + int ch; + int sections = -1; + + while ((ch = getopt (argc, argv, "s:")) != -1) { + switch (ch) { + case 's': + sections = atoi (optarg); + break; + } + } + if (sections < 0) { + fprintf (stderr, "Requires an -s SECTIONS parameter\n"); + exit (1); + } + + while ((strlen = getline (&line, &len, stdin)) != -1) { + strlen --; /* We don't care about the newline */ + int len = strlen / sections; /* Section length */ + int sum = 0; + for (int i = 0; i < len; i ++) { + int zeros = 0; + for (int j = 0; j < sections; j ++) { + if (line [j * len + i] == '0') { + zeros ++; + } + } + int ones = sections - zeros; + sum += zeros < ones ? zeros : ones; + } + printf ("%d\n", sum); + } + free (line); + return (0); +} |
