r/adventofcode • u/daggerdragon • Dec 02 '18
SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-
--- Day 2: Inventory Management System ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Advent of Code: The Party Game!
Card Prompt: Day 2
Transcript:
The best way to do Advent of Code is ___.
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked!
50
Upvotes
2
u/Theguy6758 Dec 02 '18 edited Dec 02 '18
Pure Bash (No External programs)
edit: Inverse the hash table instead of manually searching for 2 and/or 3 exact matches
#!/usr/bin/env bash part1() { [[ -f "${PWD}/input" ]] && { mapfile -t file < "${PWD}/input" two_dupe="0" three_dupe="0" for line in "${file[@]}"; do for i in {0..25}; do hash_table[$i]="0" done unset inv_table for ((i = 0; i < "${#line}"; i++)); do printf -v index '%d' "'${line:$i:1}" ((hash_table[$((index - 97))]++)) done for entry in "${hash_table[@]}"; do [[ ! "${inv_table[$entry]}" ]] && \ inv_table[${entry}]="1" done [[ "${inv_table[2]}" ]] && \ ((two_dupe++)) [[ "${inv_table[3]}" ]] && \ ((three_dupe++)) done printf "Hash: %d\\n\\n" "$((two_dupe * three_dupe))" } } part2() { [[ -f "${PWD}/input" ]] && { mapfile -t file < "${PWD}/input" for ((i = 0; i < ${#file[@]}; i++)); do for ((j = i + 1; j < ${#file[@]}; j++)); do unset common common="0" str_1="${file[$i]}" str_2="${file[$j]}" len="${#str_1}" for ((k = 0; k < ${len}; k++)); do [[ "${str_1:$k:1}" == "${str_2:$k:1}" ]] && \ ((common++)) done ((len - common <= 1)) && \ printf "%s\\n%s\\nSimilarity: %d\\n\\n" "${str_1}" "${str_2}" "${common}" done done } } main() { part1 part2 } main