Skip to content

Instantly share code, notes, and snippets.

@lemanschik
Created December 4, 2025 07:28
Show Gist options
  • Select an option

  • Save lemanschik/42c2d27659475c46e730e773842d77d6 to your computer and use it in GitHub Desktop.

Select an option

Save lemanschik/42c2d27659475c46e730e773842d77d6 to your computer and use it in GitHub Desktop.
Final strike

To golf "Option 2" (Pure Bash) for a code challenge, we can aggressively reduce whitespace, inline the logic, and use standard Bash arithmetic tricks.

Here is the significantly shorter version (198 bytes):

mapfile -t G
while c=0;for y in ${!G[@]};do
for((x=0;x<${#G};x++));do
[[ ${G[y]:x:1} == @ ]]&&{
n=0;for k in {0..8};do
[[ ${G[y+k/3-1]:x+k%3-1:1} == @ ]]&&((n++));done
((n<5))&&G[y]=${G[y]:0:x}.${G[y]:x+1}&&((c++,T++));}
done;done;((c));do :;done;echo $T

Explanation of the Golfing Tricks:

  1. mapfile -t G: Reads the entire input grid into an array G instantly, replacing the manual read loop.
  2. while c=0;...;((c));do :;done: This is a "do-while" loop structure. It runs the inner logic (loops), checks if c (changes made) is non-zero, and repeats. If c is 0, it exits.
  3. for k in {0..8}: Instead of two nested loops from -1 to 1, we loop 0 to 8 and use integer math (/3 and %3) to calculate 2D offsets.
  4. [[ ${...} == @ ]]: We use standard substring extraction. If the target neighbor is out of bounds, Bash returns an empty string, which acts as "not @" (dead), effectively handling edge cases automatically.
  5. && chaining: We chain commands with && to avoid braces {} and if/fi statements where possible.
  6. G[y]=${G[y]:0:x}.${G[y]:x+1}: This is the shortest Bash idiom to replace a character at a specific index x within a string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment