day 13 optimize
[aoc_eblake.git] / 2015 / advent14.sh
blobcbc8f5e2d3ad7a7a509667fcd008fa79811cee21
1 limit=${1-2503}
2 count=0
3 while read speed duration rest; do
4 echo "using speed $speed, fly duration $duration, rest duration $rest"
5 s[$count]=$speed d[$count]=$duration r[$count]=$rest points[$count]=0
6 : $((count++))
7 done < <(sed 's/.*fly //; s,km/s for ,,; s/seconds.*for//; s/ seconds.$//')
8 echo "parsed details on $count racers"
10 # race speed duration rest time # reports distance in $dist for racer at time
11 race() {
12 local speed=$1 duration=$2 rest=$3 limit=$4
13 dist=$((speed*duration * (limit/(duration+rest))))
14 tail=$((limit%(duration+rest)))
15 if [[ $tail -gt $duration ]]; then
16 dist=$((dist+speed*duration))
17 else
18 dist=$((dist+speed*tail))
21 # compute time # sets max to max distance, and increments points[$n] of winners
22 compute() {
23 max=0
24 local i=0
25 while [[ $i -lt ${#s[*]} ]]; do
26 race ${s[i]} ${d[i]} ${r[i]} $1
27 # echo "distance $dist"
28 [[ $dist -gt $max ]] && max=$dist
29 : $((i++))
30 done
31 i=0
32 while [[ $i -lt ${#s[*]} ]]; do
33 race ${s[i]} ${d[i]} ${r[i]} $1
34 [[ $dist == $max ]] && : $((points[i]++))
35 : $((i++))
36 done
38 i=0
39 while [[ $i -lt $limit ]]; do
40 echo "racing at second $i"
41 compute $((++i))
42 done
43 echo "furthest racer at end: $max"
44 echo ${points[*]}
45 max=0 i=0
46 while [[ $i -lt ${#s[*]} ]]; do
47 [[ $max -gt ${points[i]} ]] || max=${points[i]}
48 : $((i++))
49 done
50 echo "max points: $max"