aoc-2022/07.sh

60 lines
1.2 KiB
Bash
Executable File

#!/bin/sh
set -euf
# I highly recommend you run this in a ramfs like /tmp
mkdir 07_sol && cd 07_sol
ROOT="$PWD"
while read -r line; do
set -- $line
if [ "$1" = "$" ]; then
[ "$2" = "cd" ] && shift && $@
continue
fi
if [ "$1" = "dir" ]; then
shift
mkdir -p "$*"
continue
fi
dd if=/dev/zero of="$2" bs=1 count="$1"
done <<-EOF
$(sed "s|cd /|cd $ROOT|g" ../07_input)
EOF
cd "$ROOT"
# used for part 2 later
used_space=0
while read -r file; do
size="$(wc -c "$file")"
used_space=$((used_space + ${size%% *}))
done <<-EOF
$(find -type f)
EOF
needed_space=$((used_space - 40000000))
# I had to do the wc -c thing because the 4kb size inherent to directories got in the way
total_under=0
minsize=$used_space # minimum size dir > needed space but < prev min dir
while read -r path; do
dirsize=0
while read -r file; do
size="$(wc -c "$file")"
dirsize=$((dirsize + ${size%% *}))
done <<-EOF
$(find "$path" -type f)
EOF
if [ $dirsize -le 100000 ]; then
total_under=$((total_under + dirsize))
fi
if [ $dirsize -le $minsize ] && [ $dirsize -ge $needed_space ]; then
minsize=$dirsize
fi
done <<-EOF
$(find -type d)
EOF
printf "PART 1: %s\n" "$total_under"
printf "PART 2: %s\n" "$minsize"