Skip to content

Instantly share code, notes, and snippets.

@kbakdev
Created January 19, 2024 22:09
Show Gist options
  • Save kbakdev/103523c07d27e86804ae9287c206565e to your computer and use it in GitHub Desktop.
Save kbakdev/103523c07d27e86804ae9287c206565e to your computer and use it in GitHub Desktop.
#!/bin/bash
# Default values
button_count=8 # Total number of buttons
required_presses=-1 # Required number of buttons pressed (-1 means no requirement)
generate=false # Flag to check if we should generate combinations
# Function to display help
show_help() {
echo "Usage: $0 [-b BUTTON_COUNT] [-r REQUIRED_PRESSES] [-g]"
echo " -b BUTTON_COUNT Specify the total number of buttons (default is 8)."
echo " -r REQUIRED_PRESSES Specify the exact number of buttons that must be pressed (optional)."
echo " -g Generate combinations. Without this flag, the script will only show help."
echo " -h Display this help and exit."
}
# Show help if no arguments are passed
if [ $# -eq 0 ]; then
show_help
exit 0
fi
# Read arguments
while getopts "hgb:r:" opt; do
case $opt in
h) show_help; exit 0;;
g) generate=true;;
b) button_count=$OPTARG;;
r) required_presses=$OPTARG;;
\?) show_help; exit 1;;
esac
done
# Only generate combinations if the -g flag is set
if [ "$generate" = true ]; then
# Calculate the maximum number of digits (combinations)
max_digits=$((2**button_count - 1))
# Loop through all numbers from 0 to the maximum number
for ((i=0; i<=max_digits; i++)); do
# Convert number to binary with padding on the left
binary=$(printf "%0${button_count}d" $(bc <<< "obase=2;$i"))
# Count number of presses (number of 1s in the binary string)
presses=$(grep -o "1" <<< "$binary" | wc -l)
# Check if the number of presses meets the required number (if specified)
if [ $required_presses -ne -1 ] && [ $presses -ne $required_presses ]; then
continue
fi
# Prepare the human-readable format
human_readable=""
for ((j=0; j<${#binary}; j++)); do
if [ "${binary:$j:1}" == "1" ]; then
# Append the button number to the human-readable string
human_readable="$human_readable $((j+1))"
fi
done
# Print the result
if [ -z "$human_readable" ]; then
echo "$i: Don't press any button."
else
echo "$i: Press button(s):$human_readable."
fi
done
else
show_help
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment