Skip to content

Instantly share code, notes, and snippets.

@Bendzae
Created February 3, 2023 11:04
Show Gist options
  • Save Bendzae/ed7717254606371ca11116d16302434f to your computer and use it in GitHub Desktop.
Save Bendzae/ed7717254606371ca11116d16302434f to your computer and use it in GitHub Desktop.
aoc 22 day 3
use std::fs;
fn find_common_types(input: String) -> Vec<char> {
return input
.lines()
.map(|line| line.trim())
.map(|line| {
let compartment_1 = &line[0..line.len() / 2];
let compartment_2 = &line[line.len() / 2..line.len()];
return compartment_1
.chars()
.find(|c| compartment_2.contains(c.clone()))
.unwrap();
})
.collect::<Vec<char>>();
}
fn find_badge_types(input: String) -> Vec<char> {
return input
.lines()
.collect::<Vec<&str>>()
.chunks(3)
.map(|group| {
let g1 = group.first().unwrap();
let g2 = group.get(1).unwrap();
let g3 = group.get(2).unwrap();
return g1
.trim()
.chars()
.find(|c| g2.contains(c.clone()) && g3.contains(c.clone()))
.expect("No common type found!");
})
.collect::<Vec<char>>();
}
trait ElfItem {
fn to_elf_value(&self) -> u32;
}
impl ElfItem for char {
fn to_elf_value(&self) -> u32 {
if self.is_uppercase() {
return self.clone() as u32 - 64 + 26;
} else {
return self.clone() as u32 - 96;
}
}
}
fn main() {
let data_string = fs::read_to_string("src/input").expect("Error reading file.");
// 1
let result: u32 = find_common_types(data_string.clone())
.iter()
.map(|c| c.to_elf_value())
.sum();
println!("{:?}", result);
// 2
let result: u32 = find_badge_types(data_string)
.iter()
.map(|c| c.to_elf_value())
.sum();
println!("{:?}", result);
}
#[cfg(test)]
mod tests {
use crate::{find_badge_types, find_common_types};
#[test]
fn should_find_first_common_item_types() {
let input = "vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"
.to_string();
assert_eq!(find_common_types(input), vec!['p', 'L', 'P', 'v', 't', 's']);
}
#[test]
fn should_find_badge() {
let input = "vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"
.to_string();
assert_eq!(find_badge_types(input), vec!['r', 'Z']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment