Files

35 lines
1.1 KiB
Bash
Raw Permalink Normal View History

2026-05-28 07:02:36 +03:00
#!/usr/bin/env bash
2026-05-28 09:48:15 +03:00
# Jon Millen's 1D Game of Life in pure Bash (zero dependencies)
2026-05-28 07:02:36 +03:00
# Usage: echo 'state' | 1dlife [iterations]
# Created by Luxferre in 2026, released into public domain
ITERS="$1"
2026-05-28 09:48:15 +03:00
if [[ -z "$ITERS" ]]; then # get the iteration count dynamically
shopt -s checkwinsize # enable checking the terminal size
:|: # trigger the WINCH signal to get the size
ITERS=$((LINES - 1)) # the row count is now in LINES
fi
2026-05-28 07:02:36 +03:00
[[ -z "$RENDER_CHAR" ]] && RENDER_CHAR='#'
# read and process the state
IFS= read -r state
state="${state//[[:space:]]/0}"
state="${state//[^0]/1}"
slen=$((${#state} - 1)) # length + 4 (temporary padding) - 5
# complete rule mapping
2026-05-29 08:33:23 +03:00
declare -ar rule=(0 0 0 1 0 0 0 1 0 1 1 1 0 1 1 0 \
0 1 1 1 0 1 1 0 1 1 1 0 1 0 0 1)
2026-05-29 08:31:06 +03:00
2026-05-28 07:02:36 +03:00
for ((i=0; i<ITERS; ++i)); do
state="00${state}00" # pad the current state from both sides
newstate=''
for ((k=0; k<slen; ++k)); do
vidx="${state:k:5}"
2026-05-29 08:33:23 +03:00
newstate="${newstate}${rule[$((2#$vidx))]}"
2026-05-28 07:02:36 +03:00
done
state="$newstate"
newstate="${newstate//0/ }"
printf '%s\n' "${newstate//1/$RENDER_CHAR}"
done