]> git.sommitrealweird.co.uk Git - advent-of-code-2019.git/blob - day08/parse_image.sh
And lo, we have completed day13 (it took a while for blockbuster to run - it did...
[advent-of-code-2019.git] / day08 / parse_image.sh
1 #!/bin/bash
2
3 exec 3<input.txt
4
5 declare -a layers
6
7 image_width=25
8 image_height=6
9
10 layer_number=1
11 while read -u 3 -N $((image_width*$image_height)) layer; do
12     layers[$layer_number]=$layer
13     layer_number=$((layer_number+1))
14 done
15
16 echo "Got $layer_number layers"
17
18 get_count() {
19     digit=$1
20     data=$2
21
22     countstring="$(echo -n "$data" | sed -e 's#[^'$digit']##g;')"
23     count=${#countstring}
24
25     echo $count
26 }
27
28 zero_count_layer=0
29 lowest_zero_count=-1
30 for layer_number in ${!layers[@]}; do
31     count=$(get_count 0 ${layers[$layer_number]})
32     if [ $count -lt $lowest_zero_count ] || [ $lowest_zero_count -eq -1 ]; then
33         lowest_zero_count=$count
34         zero_count_layer=$layer_number
35     fi
36 done
37
38 one_count=$(get_count 1 ${layers[$zero_count_layer]})
39 two_count=$(get_count 2 ${layers[$zero_count_layer]})
40
41 echo "Layer $zero_count_layer has the fewest zeros ($lowest_zero_count)"
42 echo "Answer of number of 1s * number of 2s: $one_count * $two_count = $((one_count * two_count))"
43
44 draw_image() {
45     image=""
46     for (( y=0; y<$image_height; y++ )); do
47         offset=$(($image_width*$y))
48         for (( x=0; x<$image_width; x++ )); do
49             for (( layer=1; layer<=$layer_number; layer++ )); do
50                 data=${layers[$layer]}
51                 case ${data:$((offset+x)):1} in
52                     0)
53                         image+=" "
54                         continue 2
55                         ;;
56                     1)
57                         image+="#"
58                         continue 2
59                         ;;
60                 esac
61             done
62             image+="."
63         done
64     done
65
66     printf "=%.0s" {0..26}
67     echo
68     for (( y=0; y<$image_height; y++ )); do
69         offset=$(($image_width*$y))
70         echo "|${image:$offset:25}|"
71     done
72     printf "=%.0s" {0..26}
73     echo
74 }
75
76 draw_image