]> git.sommitrealweird.co.uk Git - advent-of-code-2019.git/blob - day07/part2.sh
Add percentage done ticker
[advent-of-code-2019.git] / day07 / part2.sh
1 #!/bin/bash
2
3 set -u
4 set -e
5
6 . "$(dirname $(readlink -f "$BASH_SOURCE"))/computer.sh"
7
8 exec 3<input-full.txt
9
10 OLDIFS=$IFS
11 IFS="," read -u 3 -a orig_data
12 IFS=$OLDIFS
13
14 echo "Part 2:"
15
16 run_amplifier() {
17     sequence=($@)
18     output=0
19     a=1
20     declare -a amps_stdin
21     declare -a amps_stdout
22     coproc amp1 (run_program orig_data)
23     coproc amp2 (run_program orig_data)
24     coproc amp3 (run_program orig_data)
25     coproc amp4 (run_program orig_data)
26     coproc amp5 (run_program orig_data)
27
28     for phase in ${sequence[@]}; do
29         amps_stdin[$a]="$(eval echo '${amp'${a}'[1]}')"
30         amps_stdout[$a]="$(eval echo '${amp'${a}'[0]}')"
31         echo -e "$phase\n$output" >&${amps_stdin[$a]}
32         read -u ${amps_stdout[$a]} output
33         a=$((a+1))
34     done
35
36     # that's all the amps started up, now we loop until amp1 stops, then we stop feeding amp5's
37     # data to it and read that's last output instead
38     while ( ps -p $amp1_PID >/dev/null 2>&1 ); do
39         for (( a=1; a<=5; a++ )); do
40             echo $output >&${amps_stdin[$a]}
41             read -u ${amps_stdout[$a]} output
42         done
43     done
44
45     echo "$output"
46 }
47
48 values="56789"
49 biggest_output=0
50 biggest_order="01234"
51 for (( a=0; a<${#values}; a++ )); do
52     values_2="${values:0:$a}${values:$((a+1))}"
53     value_1=${values:$a:1}
54     for (( b=0; b<${#values_2}; b++ )); do
55         values_3="${values_2:0:$b}${values_2:$((b+1))}"
56         value_2=${values_2:$b:1}
57         for (( c=0; c<${#values_3}; c++ )); do
58             values_4="${values_3:0:$c}${values_3:$((c+1))}"
59             value_3=${values_3:$c:1}
60             for (( d=0; d<${#values_4}; d++ )); do
61                 value_5="${values_4:0:$d}${values_4:$((d+1))}"
62                 value_4="${values_4:d:1}"
63                 output="$(run_amplifier $value_1 $value_2 $value_3 $value_4 $value_5 2>/dev/null)"
64                 if [ $output -gt $biggest_output ]; then
65                     biggest_output=$output
66                     biggest_order="${value_1}${value_2}${value_3}${value_4}${value_5}"
67                 fi
68             done
69         done
70     done
71 done
72
73 echo "Got biggest output $biggest_output with phases $biggest_order"
74
75 exit 0
76
77 output=0
78 for val in 4 3 2 1 0; do
79     output=$(echo -e "$val\n$output" | run_program orig_data)
80 done
81 echo $output
82