39 lines
1.1 KiB
Bash
Executable File
39 lines
1.1 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Elementary cellular automatons (rule X) in pure Bash (zero dependencies)
|
|
# Usage: echo 'state' | elem rule# [iterations]
|
|
# Created by Luxferre in 2026, released into public domain
|
|
|
|
D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
|
|
RULENO="$1"
|
|
if ((RULENO > 255 || RULENO < 0)); then
|
|
echo "Invalid rule number!"
|
|
exit 1
|
|
fi
|
|
rule="${D2B[RULENO]}"
|
|
|
|
ITERS="$2"
|
|
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
|
|
[[ -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
|
|
|
|
for ((i=0; i<ITERS; ++i)); do
|
|
state="0${state}0" # pad the current state from both sides
|
|
newstate=''
|
|
for ((k=0; k<slen; ++k)); do
|
|
vidx=$((2#${state:k:3}))
|
|
newstate="${newstate}${rule:$vidx:1}"
|
|
done
|
|
state="$newstate"
|
|
newstate="${newstate//0/ }"
|
|
printf '%s\n' "${newstate//1/$RENDER_CHAR}"
|
|
done
|