Skip to content

Instantly share code, notes, and snippets.

@benpitman
Last active June 23, 2020 15:45
Show Gist options
  • Save benpitman/ae9173500abad1b713ec61125ca51eee to your computer and use it in GitHub Desktop.
Save benpitman/ae9173500abad1b713ec61125ca51eee to your computer and use it in GitHub Desktop.
Randomly generates an identicon. Parameters are width, height and a boolean for symmetry.
#!/usr/bin/env bash
bool='^[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]$'
digit='^[0-9]+$'
width=5
symmetrical=false
if [[ -n "$1" ]]; then
if [[ "$1" =~ $digit ]]; then
width=$(( $1 < 1 ? 1 : $1 ))
elif [[ "$1" =~ $bool ]]; then
symmetrical="${1,,}"
fi
fi
if [[ -n "$2" ]]; then
if [[ "$2" =~ $digit ]]; then
height=$(( $2 < 1 ? 1 : $2 ))
elif [[ "$2" =~ $bool ]]; then
symmetrical="${2,,}"
fi
fi
if [[ -n "$3" ]] && [[ "$3" =~ $bool ]]; then
symmetrical="${3,,}"
fi
[[ -z "$height" ]] && height=$width
if $symmetrical; then
(( width % 2 )) && remainder=true || remainder=false
(( width /= 2 ))
fi
border=
if $symmetrical; then
for (( w = 0; $w < $width; w++ )); do
border+=$'\u2500\u2500\u2500\u2500'
done
$remainder && border+=$'\u2500\u2500'
else
for (( w = 0; $w < $width; w++ )); do
border+=$'\u2500\u2500'
done
fi
printf '\u250C%b\u2510\n' "$border"
for (( s = $height; $s > 0; s-- )); do
if $symmetrical; then
line=
reverse=
for (( b = 0; $b < $width; b++ )); do
line+=$(( $RANDOM & 1 ))
done
$remainder && line+=$(( $RANDOM & 1 ))
for (( b = 0; $b < $width; b++ )); do
reverse="${line:$b:1}$reverse"
done
line+="$reverse"
else
line=
for (( b = 0; $b < $width; b++ )); do
line+=$(( $RANDOM & 1 ))
done
fi
line=${line//1/\\u2588\\u2588}
line=${line//0/\\u0020\\u0020}
printf '\u2502%b\u2502\n' "$line"
done
printf '\u2514%b\u2518\n' "$border"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment