Skip to content

Instantly share code, notes, and snippets.

@smartwatermelon
Created May 15, 2020 22:50
Show Gist options
  • Save smartwatermelon/18d6d8e870254bece94f00abf4fe44c2 to your computer and use it in GitHub Desktop.
Save smartwatermelon/18d6d8e870254bece94f00abf4fe44c2 to your computer and use it in GitHub Desktop.
Logic Gates in bash, based on @cassidoo's interview question from November 11, 2019
#!/usr/bin/env bash
set -eu -o pipefail
about () {
cat <<EOF
$( basename "$0" ) by Andrew Rich <[email protected]>
Based on @cassidoo's interview question from https://tinyletter.com/cassidoo/letters/be-curious-read-widely-try-new-things-what-people-call-intelligence-just-boils-down-to-curiosity-aaron-swartz
Definition and table of logic gates: https://whatis.techtarget.com/definition/logic-gate-AND-OR-XOR-NOT-NAND-NOR-and-XNOR
EOF
}
syntax () {
cat <<EOF
Usage: $( basename "$0" ) <GATE> <VALUE1> [VALUE2]
Possible values for GATE are AND, OR, NOT, NAND, NOR, XOR, XNOR
VALUE1 (required) and VALUE2 (optional) are integers to evaluate with GATE
Examples:
$ logicGate AND 1 1
=> 1
$ logicGate NOT 1
=> 0
$ logicGate NAND 1 0
=> 1
$ logicGate NOR 0 0
=> 1
VALUE2 is ignored if the selected GATE takes only a single value.
EOF
}
if [ $# -lt 2 ]; then
# we need at least two params
about
syntax
exit 1
fi
GATE=$( tr '[:lower:]' '[:upper:]' <<< "$1" )
if [[ ${GATE} != "NOT" ]] && [[ -z ${3+x} ]]; then
# gates other than NOT require two params
syntax
exit 1
fi
case $GATE in
'AND')
echo -e "AND $2 $3: $(( $2&$3 ))"
;;
'OR')
echo -e "OR $2 $3: $(( $2|$3 ))"
;;
'NOT')
echo -e "NOT $2: $(( !$2 ))"
;;
'NAND')
echo -e "NAND $2 $3: $(( !($2&$3) ))"
;;
'NOR')
echo -e "NOR $2 $3: $(( !($2|$3) ))"
;;
'XOR')
echo -e "XOR $2 $3: $(( $2^$3 ))"
;;
'XNOR')
echo -e "XNOR $2 $3: $(( !($2^$3) ))"
;;
*)
echo -e "*** Error: Invalid GATE: $1\n"
syntax
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment