From 4136711a7eaf27b58cbd209456154893e0b9f681 Mon Sep 17 00:00:00 2001 From: Bruno Raoult Date: Sun, 25 Jul 2021 11:24:04 +0200 Subject: [PATCH] count matches w/ string manipulation: ~75% gain, 85-90% gain from V1 --- 2020/day20/ex1.bash | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) mode change 100644 => 100755 2020/day20/ex1.bash diff --git a/2020/day20/ex1.bash b/2020/day20/ex1.bash old mode 100644 new mode 100755 index 589dfff..ecf642d --- a/2020/day20/ex1.bash +++ b/2020/day20/ex1.bash @@ -54,18 +54,21 @@ for key in "${!nums[@]}"; do done -ALL=("${T[@]}" "${R[@]}" "${B[@]}" "${L[@]}" "${RT[@]}" "${RR[@]}" "${RB[@]}" "${RL[@]}") +ALL="${T[@]} ${R[@]} ${B[@]} ${L[@]} ${RT[@]} ${RR[@]} ${RB[@]} ${RL[@]}" +ALLSIZE=${#ALL} + declare -i res=1 count for ((i=0; i<${#nums[@]}; ++i)); do count=0 for t in ${T[$i]} ${R[$i]} ${B[$i]} ${L[$i]}; do - for s in "${ALL[@]}"; do - [[ $t == "$s" ]] && ((count++)) - done + # https://stackoverflow.com/questions/26212889/bash-counting-substrings-in-a-string/50601141#50601141 + S=${ALL//$t} + # 10 is line size + ((count += (ALLSIZE-${#S})/10)) done - - ((count ==6)) && ((res*=${nums[$i]})) + # 6 is 4 for itself, + 2 for other matching + ((count == 6)) && ((res*=${nums[$i]})) done printf "%s : res=%d\n" "$CMD" "$res"