Skip to content

Commit 82ad1a7

Browse files
committed
22: Fix error in final calculation
Broken in commit 3d72e77bc18b1a4f43800541749885418cde04b. "${A[*]}" is a single string, while ${A[*]} and "${A[@]}" is a list. Minor cleanup Thanks to Bruno Raoult for pointing this out
1 parent 5acc2fd commit 82ad1a7

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

22.sh

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,44 @@
11
#! /usr/bin/env bash
22
C=($(grep "^[0-9]" "${1:-22.txt}"))
3-
A=(${C[@]:0:${#C[@]}/2})
4-
B=(${C[@]:${#C[@]}/2})
3+
N=${#C[@]}
4+
A=(${C[@]:0:N/2})
5+
B=(${C[@]:$N/2})
56

67
score() {
78
local sum=0 S=("$@")
8-
for i in "${!S[@]}"; do ((sum+=S[i]*(50-i))); done
9+
for i in "${!S[@]}"; do ((sum+=S[i]*(N-i))); done
910
echo $sum
1011
}
1112

12-
#round=0
13-
while [[ ${#A[@]} != 0 && ${#B[@]} != 0 ]]; do
13+
# shellcheck disable=SC2128
14+
while [[ -n "$A" && -n "$B" ]]; do
1415
if [[ $A -gt $B ]]; then A+=($A $B); else B+=($B $A); fi
1516
A=(${A[@]:1})
1617
B=(${B[@]:1})
1718
#((++round%500==0)) && echo "$round: ${#A[@]}/${#B[@]}"
1819
done
19-
echo "22A: $(score "${A[*]}" "${B[*]}")"
20+
echo "22A: $(score "${A[@]}" "${B[@]}")"
2021

2122
r() {
22-
local X="$*"
2323
declare -A H
24-
local a=(${X/ X*}) b=(${X/*X }) hash
25-
while [[ ${#a[@]} != 0 && ${#b[@]} != 0 ]]; do
24+
local a=($1) b=($2) hash
25+
# shellcheck disable=SC2128,SC2181
26+
while [[ -n "$a" && -n "$b" ]]; do
2627
hash=${a[*]}X${b[*]}
27-
hash=${hash// /_}
28-
if [[ -n "${H[$hash]}" ]]; then
28+
if (( H[${hash// /_}]++ > 0)); then
2929
return 0
3030
elif [[ $a -lt ${#a[@]} && $b -lt ${#b[@]} ]]; then
31-
r "${a[*]:1:a}" X "${b[*]:1:b}"
31+
r "${a[*]:1:a}" "${b[*]:1:b}"
3232
else
3333
[[ $a -gt $b ]]
3434
fi
35-
# shellcheck disable=SC2181,SC2128
3635
if [[ $? == 0 ]]; then a+=($a $b); else b+=($b $a); fi
37-
H[$hash]=1
3836
a=(${a[@]:1})
3937
b=(${b[@]:1})
4038
#((${#H[@]}%1000==0)) && echo "$round:${#H[@]}: ${#a[@]}/${#b[@]}"
4139
done
42-
((${#a[*]}+${#b[*]} == 50)) && echo "22B: $(score "${a[*]}" "${b[*]}")"
40+
((${#a[*]}+${#b[*]} == N)) && echo "22B: $(score "${a[@]}" "${b[@]}")"
4341
return ${#b[@]}
4442
}
4543

46-
A=(${C[@]:0:${#C[@]}/2})
47-
B=(${C[@]:${#C[@]}/2})
48-
r "${A[*]}" X "${B[*]}"
44+
r "${C[*]:0:N/2}" "${C[*]:N/2}"

0 commit comments

Comments
 (0)