2022 day 4: C, parts 1 & 2 (lazy way: same algo as Bash)

This commit is contained in:
2022-12-08 12:21:12 +01:00
parent d116b98ae9
commit ab73311d6b
3 changed files with 57 additions and 6 deletions

View File

@@ -70,10 +70,18 @@ aoc-c: res=2760
+++++++++++++++++ part 1
aoc.bash: res=444
time: 0:00.04 real, 0.04 user, 0.00 sys
context-switch: 5+1, page-faults: 0+338
time: 0:00.02 real, 0.01 user, 0.00 sys
context-switch: 0+1, page-faults: 0+258
aoc-c: res=444
time: 0:00.00 real, 0.00 user, 0.00 sys
context-switch: 0+1, page-faults: 0+87
+++++++++++++++++ part 2
aoc.bash: res=801
time: 0:00.04 real, 0.03 user, 0.00 sys
context-switch: 0+1, page-faults: 0+336
time: 0:00.02 real, 0.01 user, 0.00 sys
context-switch: 1+1, page-faults: 0+261
aoc-c: res=801
time: 0:00.00 real, 0.00 user, 0.00 sys
context-switch: 0+1, page-faults: 0+87

43
2022/day04/aoc-c.c Normal file
View File

@@ -0,0 +1,43 @@
/* aoc-c.c: Advent of Code 2022, day 3
*
* Copyright (C) 2022 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aoc.h"
static int parse(int part)
{
int res = 0, val[4];
while (scanf("%d-%d,%d-%d", val, val+1, val+2, val+3) == 4) {
if (part == 1) {
if ( (val[0] >= val[2] && val[1] <= val[3] ) ||
(val[0] <= val[2] && val[1] >= val[3] ) ) {
res++;
}
} else {
if ( (val[0] >= val[2] && val[0] <= val[3] ) ||
(val[0] <= val[2] && val[1] >= val[2] ) ) {
res++;
}
}
}
return res;
}
int main(int ac, char **av)
{
printf("%s: res=%d\n", *av, parse(parseargs(ac, av)));
exit(0);
}

View File

@@ -18,7 +18,7 @@ export LANG=C
parse() {
local -i _part="$1"
local -a _arr
global -ig res=0
declare -ig res=0
while IFS=-, read -ra _arr; do
# shellcheck disable=2068
@@ -26,7 +26,7 @@ parse() {
if (( _part == 1 )); then
(( ( ($1 >= $3 && $2 <= $4) || ($1 <= $3 && $2 >= $4) ) && res++ ))
else
(( ( ($1 >= $3 && $1 <= $4) || ($3 >= $1 && $3 <= $2) ) && res++ ))
(( ( ($1 >= $3 && $1 <= $4) || ($1 <= $3 && $2 >= $3) ) && res++ ))
fi
done
}