AdventOfCode2022/07/README.md

37 lines
1.7 KiB
Markdown
Raw Permalink Normal View History

2022-12-08 01:46:51 +01:00
# [Day 7](https://adventofcode.com/2022/day/7)
:gift::gift::gift::gift::gift::gift::gift:
2023-12-09 13:46:15 +01:00
Today's language: **Bash + Awk**
2022-12-08 01:46:51 +01:00
2023-12-09 13:46:15 +01:00
Lines of code: **53**
Execution time: **0,039 s**
## The protagonist is stupid
2022-12-08 01:50:49 +01:00
The way the challenge is laid out is absolutely ridiculus; both tasks could be done in one-liners on a Linux machine *(which the device from the challenge probably is)*
in any POSIX shell,
2023-12-09 13:46:15 +01:00
*if* the user wasn't as stupid as our protagonist...
2022-12-08 01:46:51 +01:00
That's why I wrote a bash script that actually creates the whole filesystem from the input-file.
2022-12-08 01:52:59 +01:00
It does so (by default) in `/tmp`. The sizes for the files are only allocated, so that `du` shows the filesize.
No actual write operations are taking place, which makes recreating the file structure pretty fast.
2022-12-08 01:46:51 +01:00
2023-12-09 13:46:15 +01:00
### And so am I?
2022-12-08 01:46:51 +01:00
The problem is, that (even empty) directories have a size, which also increases with every file and subdirectory in it.
That's why I needed to calculate the sizes of the directories *without* the actual file sizes and subtract that from the output of `du`.
This new output can then be piped into an `awk` one-liner. In reality, this problem wouldn't exist since you would want the total size of a directory anyway.
If the size of the directories themselves would not matter, the commands would be:
```shell
# Task 1
du -b / | awk 'BEGIN{sum=0} {if ($1 <= 100000) {sum+=($1)}} END{print "Total size of all dirs<100000: "sum-0}'
# Task 2: min_size = (Update size) - (file system size) - (used size)
du -b / | awk 'BEGIN{file=""; size=99999999} {if ($1 >= min_size && $1 < size) {size=$1; file=$2}} END{print "You should delete "file" size("size")"}'
```
2022-12-08 01:50:49 +01:00
## Run today's code
2022-12-08 01:46:51 +01:00
```shell
./day7.sh output.txt
```
2023-12-09 13:46:15 +01:00
<!-- creates the filesystem -->