Initial commit

This commit is contained in:
2022-12-06 11:44:37 +01:00
commit 41b1b887b3
18 changed files with 7035 additions and 0 deletions

20
src/day1/main.rs Normal file
View File

@ -0,0 +1,20 @@
use base::*;
fn main() {
let lines = read_file("day1.txt");
let mut sums: Vec<u32> = vec![];
lines.split(|line|line.is_empty()).for_each(|sub|
sums.push(sub.iter().map(|line|line.parse::<u32>().expect("Error while parsing")).sum())
);
sums.sort();
sums.reverse();
let top = &sums[0..=2];
top.iter().enumerate().for_each(|(index, cal)|
println!("{}. with value {cal}", index + 1)
);
let sum = top.iter().sum::<u32>();
println!("Sums of top three: {sum}");
}

140
src/day2/main.rs Normal file
View File

@ -0,0 +1,140 @@
use base::*;
#[derive(Debug, PartialEq, Clone, Copy)]
enum Move {
Rock,
Paper,
Scissors
}
enum GameResult {
Win,
Draw,
Lose
}
impl GameResult {
pub fn from_str(c: &str) -> GameResult {
return match c {
"X" => {GameResult::Lose}
"Y" => {GameResult::Draw}
"Z" | _ => {GameResult::Win}
}
}
}
impl Move {
pub fn from_str(c: &str) -> Move {
return match c {
"A" | "X" => {
Move::Rock
}
"B" | "Y" => {
Move::Paper
}
"C" | "Z" | _ => {
Move::Scissors
}
}
}
pub fn score(self) -> u32 {
return match self {
Move::Rock => {1}
Move::Paper => {2}
Move::Scissors => {3}
}
}
pub fn result(self, other: Move) -> GameResult {
if self == other {
return GameResult::Draw;
}
match self {
Move::Rock => {
if other == Move::Scissors {
return GameResult::Win
}
}
Move::Paper => {
if other == Move::Rock {
return GameResult::Win
}
}
Move::Scissors => {
if other == Move::Paper {
return GameResult::Win
}
}
}
GameResult::Lose
}
}
struct GameMove(Move, Move);
impl GameMove {
fn calc_score(&self) -> u32 {
let result = self.1.result(self.0);
let score = self.1.score();
return match result {
GameResult::Win => {
score + 6
}
GameResult::Draw => {
score + 3
}
GameResult::Lose => {
score
}
}
}
fn from_opponent_move(opponent_move: Move, result: GameResult) -> GameMove {
return match result {
GameResult::Draw => {
GameMove(opponent_move, opponent_move)
}
GameResult::Win => {
let our_move = match opponent_move {
Move::Rock => {Move::Paper}
Move::Paper => {Move::Scissors}
Move::Scissors => {Move::Rock}
};
GameMove(opponent_move, our_move)
}
GameResult::Lose => {
let our_move = match opponent_move {
Move::Rock => {Move::Scissors}
Move::Paper => {Move::Rock}
Move::Scissors => {Move::Paper}
};
GameMove(opponent_move, our_move)
}
}
}
}
fn main() {
let lines = read_file("day2.txt");
let sum = lines.iter().map(|line| {
let symbols_per_move = line.split(" ");
let mut symbols_iter = symbols_per_move.map(|symbol| Move::from_str(symbol)).take(2);
GameMove(symbols_iter.next().unwrap(), symbols_iter.next().unwrap())
}).map(|game_move|game_move.calc_score()).sum::<u32>();
println!("Task 1: Got sum: {sum}");
let sum = lines.iter().map(|line| {
let mut symbols_per_move = line.split(" ");
GameMove::from_opponent_move(Move::from_str(symbols_per_move.next().unwrap()), GameResult::from_str(symbols_per_move.next().unwrap()))
}).map(|game_move|game_move.calc_score()).sum::<u32>();
println!("Task 2: Got sum: {sum}");
}

58
src/day3/main.rs Normal file
View File

@ -0,0 +1,58 @@
use base::*;
fn calc_prio(item: char) -> u32{
if item.is_lowercase() {
item as u32 - ('a' as u32) + 1
} else {
item as u32 - ('A' as u32) + 27
}
}
fn main() {
let lines = read_file("day3.txt");
let sum = lines.iter()
.map(|line|line.split_at(line.len() / 2))
.map(|(first_half, second_half)| {
for char_0 in first_half.chars() {
for char_1 in second_half.chars() {
if char_0 == char_1 {
return Some(char_0);
}
}
}
None
})
.map(|item| {
match item{
None => 0,
Some(item) => calc_prio(item)
}
}).sum::<u32>();
println!("Task 1: {sum}");
let sum = lines.chunks_exact(3).map(|chunk| {
for char_0 in chunk[0].chars() {
for char_1 in chunk[1].chars() {
if char_0 == char_1 {
for char_2 in chunk[2].chars() {
if char_1 == char_2 {
return Some(char_0);
}
}
}
}
}
None
}).map(|item|{
match item {
None => 0,
Some(item) => calc_prio(item)
}
}).sum::<u32>();
println!("Task 2: {sum}");
}

68
src/day4/main.rs Normal file
View File

@ -0,0 +1,68 @@
use std::fs::read_to_string;
struct Range {
start: u32,
end: u32
}
impl Range {
fn new(start: u32 , end: u32) -> Self{
Range {start, end}
}
fn contains(&self, number: u32) -> bool {
number >= self.start && number <= self.end
}
fn fully_overlap(&self, other: &Range) -> bool {
self.contains(other.start) && self.contains(other.end)
}
fn partly_overlap(&self, other: &Range) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}
fn main() {
let input = read_to_string("day4.txt").unwrap();
let count = input
.split_whitespace()
.flat_map(|line| line.split(","))
.flat_map(|line_range| line_range.split("-"))
.map(|number| number.parse::<u32>().unwrap())
.collect::<Vec<_>>()
.chunks_exact(2)
.map(|chunk| Range::new(chunk[0], chunk[1]))
.collect::<Vec<_>>()
.chunks_exact(2)
.filter_map(|range_pair|{
if range_pair[0].fully_overlap(&range_pair[1]) || range_pair[1].fully_overlap(&range_pair[0]) {
Some(())
}
else { None }
})
.count();
println!("Task1: {count}");
let count = input
.split_whitespace()
.flat_map(|line| line.split(","))
.flat_map(|line_range| line_range.split("-"))
.map(|number| number.parse::<u32>().unwrap())
.collect::<Vec<_>>()
.chunks_exact(2)
.map(|chunk| Range::new(chunk[0], chunk[1]))
.collect::<Vec<_>>()
.chunks_exact(2)
.filter_map(|range_pair|{
if range_pair[0].partly_overlap(&range_pair[1]) || range_pair[1].partly_overlap(&range_pair[0]) {
Some(())
}
else { None }
})
.count();
println!("Task2: {count}");
}

100
src/day5/main.rs Normal file
View File

@ -0,0 +1,100 @@
use std::collections::HashMap;
use base::read_file;
#[derive(Debug, Clone)]
struct CrateStorage {
stacks: HashMap<usize, Vec<char>>
}
impl CrateStorage {
fn print_top(&self) {
for k in 0..(9 as usize) {
match self.stacks.get(&k) {
None => {
print!(" ")
}
Some(v) => {
print!("{}", v[v.len() - 1]);
}
}
}
println!()
}
}
#[derive(Debug)]
struct MoveOp {
amount: usize,
from: usize,
to: usize
}
impl MoveOp {
fn apply(&self, storge: &mut CrateStorage, task_1 : bool) {
if task_1 {
for _ in 0..self.amount {
let vec = storge.stacks.get_mut(&self.from).unwrap();
let element = vec.remove(vec.len() - 1);
storge.stacks.get_mut(&self.to).unwrap().push(element);
}
} else {
let mut temp = vec![];
for _ in 0..self.amount {
let vec = storge.stacks.get_mut(&self.from).unwrap();
temp.push(vec.remove(vec.len() - 1));
}
temp.reverse();
for i in 0..self.amount {
storge.stacks.get_mut(&self.to).unwrap().push(temp[i]);
}
}
dbg!(&storge);
}
}
fn main() {
let lines = read_file("day5_test.txt");
let mut storage = CrateStorage{
stacks: HashMap::new()
};
let mut moves =vec![];
for line in lines {
if line.starts_with("[") {
let mut iter = line.chars().enumerate();
loop {
match iter.next() {
Some((idx, char)) => {
if char == '[' {
let idx = idx / 4;
if let Some((_, value)) = iter.next() {
let vec = storage.stacks.entry(idx).or_insert_with(|| Vec::new());
vec.insert(0, value);
} else {
break;
}
}
}
None => break
}
}
} else if line.starts_with("move") {
let split = line.split_whitespace().collect::<Vec<_>>();
let amount = split[1].parse::<usize>().unwrap();
let from = split[3].parse::<usize>().unwrap() - 1;
let to = split[5].parse::<usize>().unwrap() - 1;
moves.push(MoveOp{amount, from, to});
}
}
let mut storage_task_1 = storage.clone();
moves.iter().for_each(|move_op| move_op.apply(&mut storage_task_1, true));
storage_task_1.print_top();
let mut storage_task_2 = storage;
moves.iter().for_each(|move_op| move_op.apply(&mut storage_task_2, false));
storage_task_2.print_top();
}

21
src/day6/main.rs Normal file
View File

@ -0,0 +1,21 @@
use std::collections::HashSet;
use std::fs::read_to_string;
fn find_marker(content: &str, size: usize) -> Option<usize> {
for (idx, chars) in content.chars().collect::<Vec<_>>().windows(size).enumerate() {
let set = chars.iter().map(|char|*char).collect::<HashSet<_>>();
if set.len() == size {
let idx = idx + size;
return Some(idx);
}
}
None
}
fn main() {
let content = read_to_string("day6.txt").unwrap();
println!("Task 1: {}", find_marker(&content, 4).unwrap());
println!("Task 2: {}", find_marker(&content, 14).unwrap());
}

16
src/lib.rs Normal file
View File

@ -0,0 +1,16 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
pub fn read_file(name: &str) -> Vec<String> {
let file = File::open(name);
return match file {
Ok(file) => {
BufReader::new(file).lines().map(|line|line.ok()).flatten().collect::<Vec<_>>()
}
Err(_) => {
vec![]
}
}
}