Compare commits

...

6 Commits

Author SHA1 Message Date
e33875103f [CLEANUP] Removed duplicate code in Day 10 2022-12-11 20:08:48 +01:00
afa80765cf [TASK] Solved Day 10 2022-12-11 16:17:45 +01:00
563cddce78 [TASK] Solved Day 9 2022-12-11 14:52:15 +01:00
ae90aad6dc [TASK] Implemented Day 8 2022-12-11 12:17:43 +01:00
f6132bbf24 [TASK] Optimized Day 7: removed directory names 2022-12-10 16:53:36 +01:00
8754356dbc [TASK] Solved Day 7 2022-12-10 16:30:05 +01:00
14 changed files with 4084 additions and 18 deletions

45
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,45 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'advent-of-code-2022-rust'",
"cargo": {
"args": [
"build",
"--bin=advent-of-code-2022-rust",
"--package=advent-of-code-2022-rust"
],
"filter": {
"name": "advent-of-code-2022-rust",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in executable 'advent-of-code-2022-rust'",
"cargo": {
"args": [
"test",
"--no-run",
"--bin=advent-of-code-2022-rust",
"--package=advent-of-code-2022-rust"
],
"filter": {
"name": "advent-of-code-2022-rust",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}

139
input/day10.txt Normal file
View File

@@ -0,0 +1,139 @@
addx 1
noop
noop
noop
addx 5
addx 5
noop
noop
addx 9
addx -5
addx 1
addx 4
noop
noop
noop
addx 6
addx -1
noop
addx 5
addx -2
addx 7
noop
addx 3
addx -2
addx -38
noop
noop
addx 32
addx -22
noop
addx 2
addx 3
noop
addx 2
addx -2
addx 7
addx -2
noop
addx 3
addx 2
addx 5
addx 2
addx -5
addx 10
noop
addx 3
noop
addx -38
addx 1
addx 27
noop
addx -20
noop
addx 2
addx 27
noop
addx -22
noop
noop
noop
noop
addx 3
addx 5
addx 2
addx -11
addx 16
addx -2
addx -17
addx 24
noop
noop
addx 1
addx -38
addx 15
addx 10
addx -15
noop
addx 2
addx 26
noop
addx -21
addx 19
addx -33
addx 19
noop
addx -6
addx 9
addx 3
addx 4
addx -21
addx 4
addx 20
noop
addx 3
addx -38
addx 28
addx -21
addx 9
addx -8
addx 2
addx 5
addx 2
addx -9
addx 14
addx -2
addx -5
addx 12
addx 3
addx -2
addx 2
addx 7
noop
noop
addx -27
addx 28
addx -36
noop
addx 1
addx 5
addx -1
noop
addx 6
addx -1
addx 5
addx 5
noop
noop
addx -2
addx 20
addx -10
addx -3
addx 1
addx 3
addx 2
addx 4
addx 3
noop
addx -30
noop

146
input/day10_example.txt Normal file
View File

@@ -0,0 +1,146 @@
addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop

1089
input/day7.txt Normal file

File diff suppressed because it is too large Load Diff

99
input/day8.txt Normal file
View File

@@ -0,0 +1,99 @@
131102031022411233124153000402524132243245422402002121234345453535321113450535302430144220243210033
210030011133442111442145434004231353202400601331445042106230540242340014332243105022302133441101011
201302044230110302341330012044051130055046354663404014033243655520410125432425532024143403330032232
210303103204034020151134514120046162664361356330261302226530654326452225134535222440444443410101130
021310332113230035544033314213544254421233042151226601345516101654005025035545035333140023212102212
220140301231432453044535532323066560244052510442522465306425021511260132313424322110345422300411332
103013240142011245425311001542145655516105003352455141424412415222100145355043202120423034202120403
314103304322445325255534650156565303510461206034672755654106425161056213552330050310445352323213402
243430113305332145305400366156126611120357766767667531265661631510215134106224240155532142014202020
344044011305120500223111213354316112154646744635155132374774442641061323024416155344101304242413014
210001340311202411013214565026366577746364242672331436164352252445110000414212215202321411504422400
001030344254033552521244445311464542617442572153467545366653342426676363026234406640015310103000111
123004351234415456501532136126535464236513321263256111263236363424471316560661104630322511135024314
243444301010130503501065440067414335615573435151661324666436573133444251763541254166141130405531401
301333054435342646553265615125271561444757162666247563564724434377461174733226461663122454115301022
313333115034033032461152521554721624436564356545874583322623147632365263427634464233444421123452114
434441324240044110131332722354256132333522657745624745724323263635746316535120231124164652542245541
020013043025261604606066777717675561448878622688884553346728286853164272251311263510330645452212040
225405401530036646635664123763243188844858643328244728344354343287813231363771264361344552214134043
444013205241103641532477643143435563484567276423226466226434857664377176552653732212146514023430325
235444033555452351644577725572733823223422438445886848336238372267477767173715122521014452405344110
022222500504231055646646534633724257646568684735488756288737857786232268232655151633323530463425151
412102254551210100735562467375656382325864659764674335534465738553284326347575542675435335613154320
202304233522424114651647265763556544532358373769578879369385574555386666783363244334360301665155255
400235422666401262236327746826382638573848989589958764697958946664233887757677777164614616200413302
413211350405512664175712772346875822558798479568486643787487763573785465875336133314155235265153544
412112650043523364626154522655787734369585968849884958638795656846722736645822544573361050432101002
040151232015244534675233447267274466883354564933934639355395374945757347634723116764261154205631025
053511566106055552733487866435428673379594867554589579573759867856436754328455243315565403452366550
402441261342655261311663778728277373873487457867467678497684746937764462833722831553364205512206541
401560462601374333165687778774966694644847875679669694796453568554383377242683474675113640166014002
245431640441276372256235534578677594558499466595957658548574676357557473852362834636123725105611001
140325466637452621767678632447835458776865576466546548894776445753494487385328422645157221103664133
253440020224216474125727543697395446885846849486744757588954688447585337348374328857266123303626032
522360463154354425644334277863647479565896696996775849896649575745746557964548536537415577142552050
402351634474624167474857559553949899894799879644496759587555549787974996993634823833353424316316042
414140006077774645384224689955449865767867876647679668857949995687773539976755288762714471242526254
032242255462211412258653836566746764685477947565799869886769647489953985859547537844111624535631156
241646435225236526565228495485878686676559956669957869665758947786478934645637286347261114426145563
512215356337536722737525437473645894558456658976958699776986594778559569864962457825216143344215016
322625244746336257345525895486859454957989669585766859958667775649875866654855238722721513671212305
044600535247217686848675385837958687859856856865869679556868995579875763985654342678317263541605554
430320424173321746345287493633447589689698796959599858768985856685945573454358785585284454656334025
232026013361136674773333583555589876467998965697988698997966777468454666855894285223681327425505166
354332536226232536453676489538955896788985786767799998876886965757444485955456462568453444425456521
016154147271566788586769489946847647867857556667888797775895768988576579978395627453672756147414326
463454162462563733454784956555887864475857986666689767978699985965647598648778424456255355723655466
021001072567511684363734454496747746785559778677966778897776558954997794766634668356686124441524525
234605435156344755776859794859864756797769876888968689787579998559856654953446748662382433262116262
030666223611312438477278595797684446757958596668696976678757986797965899875556377876865147373650335
245046541536764737224694794369857786796969878968689968797958865856864988656773724353268427134461620
265066622261247542566375373496969757789659688887789988798956868878668565665794723743572475263161166
422245453144736877586299945587888888767997586686876996879786788998867747683776448657845662361505315
210351625547722865278485967857788659769765586689699988976775596895984657648869967252632246417436621
141004614422116428487735355858968995455599988699767679796595755979678769336598642342483777532511004
533362561377622426377686383498446767487997987976886899988585956569875694463399574483265564264622314
456163507723454276868637866355647859456998677889778989889969998954684957667483346372863274465245646
030644251421316636263479555487765499846688669798677798668968599994746869757876565775844144255106462
510135336311735337436764935399965949469956999767696876898578576969547984463869253278467243311543030
466524526117724766584368696865578944888566858759789698699778689456856774865884337672615767136523254
254110631463762333865539645936466585858655857657659586556989585456479575455563845762632676471423233
562434653773762262468663566995359545869887797866957588766855659579865834576343438465353323754454240
112066240641477224475587449447989749648974898785555767886979489566644938356955638286634724441631625
330443313353347713822865768695549469777556759786896565758769775757475566378642426537546311412140051
040065350247621726448577745444446666557767548565886798996759654466566755698345662584625446342463260
330536625076531353825376746548345995946649894668956867559446757474398638639624464682343654214032311
530251120326432762683357643388548466489576697998869899549584977659746869733837538723573545213461105
255356015316555756432734833639785737748988987965669458947565666746847669548847254811135737404226043
454354550123557227257454326863468487794448666674495859497588676766356646553276336612337324063553462
144340525160235512164242786385886753536996894579865659848488534457479379684556654637432614663443613
305316054035171372138527636345993984687638579458566486795488343446895753373444445772513544116215313
543055400456632262131666826787874497775946535566897457748984377394483964377555447341647525602315351
412546632444321676125286364645444448636496473746537653585847369856994564666782226566264742530022340
044233444612165527122563533685825959374668734768758953663536843946435452847223172365277563546141540
340030454102343151253211647666557354334348799955649644348678747758347287426221514313112316663165454
011020051334501654522762446268866586389746656669789443696677886848328248582411315534364123146250501
305413453334030464614216442476475733478966457359966737766476988846463467574624373625606065562242335
034215112203016427473135421577622448726677469646375339565639944867546662453345521671403262325021214
132210543140531252452317342463454885388566728556533533877354846446665578244115675240031664244524501
201140051634662646614612354714626525722377445426842485568735384726362363654642742661135663265002510
025011353243541235316415314133578633558245363633567643474723462264656821637416273202656565602515322
121540314222665224011553176734444466578255884322834667368468238484254776573264467333645106223352155
233134314541654641520531771126551528746557387438726348653238283875537147555615754035502132555444301
424510000505066600303343337525732714723283556468834467558232644677477536766533666404266150255104242
041433452552331436330125237255465337374884372735358382327855756643676341445255435062065033314033212
141025211241314363206626056633223121353133645783244374622462256271457773212200625560321421020100213
224101010422251643133220616233621223532466525114754865347141165612135423157400060111225313054434032
004040052225144131342364656025377722754756627621767354111575442445436452322335541156250421012350243
043322120521041516241540153402233524371432721521521276133447761312616332565246332656140342120501432
200232013354533102134562014146621725413251577715376671261144475237357064044430050234040121014304202
011420212054031401033241133121106532344212712314572323662643147467661343340045361122545415103011124
102223410325432324313243446514164004156475643254444557477323147134144354265066260422110450012141414
031411112311321035125554420606413626050373327654774373667767140605036115333551650220414205214132024
210204032200320524351051665115025502044361230251377575706601164652440120455165201034431244211004301
331131223444034015143142430503454436431142412165246111316106164251614223504203533022310134023423343
120300034332102045152234220042512653414152606411234665213124345325420542210314454221024423343223220
200230420442302210441134513143532363040132120013505235035543064245636124512505054404233133430423011
000202411243122420140310501035333204626352325031215630345206242502134153000033354044334042221310101
111301302244231442013332415144033330063530643146335532313306033656410450441505505240142210004121122

5
input/day8_example.txt Normal file
View File

@@ -0,0 +1,5 @@
30373
25512
65332
33549
35390

2000
input/day9.txt Normal file

File diff suppressed because it is too large Load Diff

8
input/day9_example.txt Normal file
View File

@@ -0,0 +1,8 @@
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2

8
input/day9_example2.txt Normal file
View File

@@ -0,0 +1,8 @@
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20

96
src/day10.rs Normal file
View File

@@ -0,0 +1,96 @@
use crate::day_solver::DaySolver;
use super::util;
pub struct Day10 {
instructions: Vec<Instruction>
}
impl Day10 {
pub fn create() -> Self {
// let lines = util::read_file("input/day10_example.txt");
let lines = util::read_file("input/day10.txt");
// Put the input into the day struct
return Day10 {
instructions: lines.iter()
.map(|s| {
if s == "noop" {
Instruction::Noop
} else if s.starts_with("addx") {
Instruction::Addx(s.split_whitespace().last().unwrap().parse::<i32>().unwrap())
} else {
panic!("Unknown instruction {}", s)
}
})
.collect(),
}
}
fn execute<F>(&self, mut cycle_fun: F) where F: FnMut(&i32, &i32) {
let mut x: i32 = 1;
let mut cycle = 1;
for instr in &self.instructions {
for _ in 0..instr.cycles() {
cycle_fun(&cycle, &x);
cycle += 1;
}
if let Instruction::Addx(addx) = instr {
x += addx;
}
}
}
}
impl DaySolver for Day10 {
fn solve_part1(&mut self) -> String {
let mut interesting_cycle_sum = 0;
self.execute(|cycle, x| {
if (cycle + 20) % 40 == 0 {
// println!("{} * {} = {}", x, cycle, x * cycle);
interesting_cycle_sum += x * cycle;
}
});
return interesting_cycle_sum.to_string();
}
fn solve_part2(&mut self) -> String {
let mut res = String::from("\n");
self.execute(|cycle, x| {
if x.abs_diff((cycle - 1) % 40) <= 1 {
res += "#";
} else {
res += "."
}
if cycle % 40 == 0 {
res += "\n";
}
});
return res;
}
}
#[derive(Debug, Clone)]
enum Instruction {
Noop,
Addx(i32)
}
impl Instruction {
fn cycles(&self) -> u8 {
match self {
Self::Addx(_) => 2,
_ => 1
}
}
}

View File

@@ -1,3 +1,4 @@
use crate::day_solver::DaySolver;
use super::util;
@@ -5,12 +6,9 @@ use super::util;
#[derive(Debug)]
enum FileSystemEntry {
File {
name: String,
size: usize
},
Directory {
name: String,
}
Directory
}
#[derive(Debug)]
@@ -26,28 +24,27 @@ pub struct Day7 {
impl Day7 {
pub fn create() -> Self {
let lines = util::read_file("input/day7_example.txt");
// let lines = util::read_file("input/day7.txt");
// let lines = util::read_file("input/day7_example.txt");
let lines = util::read_file("input/day7.txt");
let mut lines_iter = lines.iter().peekable();
let mut commands = Vec::new();
while let Some(line) = lines_iter.next() {
if line == "$ ls" {
if line == "$ ls" {
let mut result = Vec::new();
if let Some(result_line) = lines_iter.peek() {
while let Some(result_line) = lines_iter.peek() {
if !result_line.starts_with("$") {
if result_line.starts_with("dir") {
result.push(FileSystemEntry::Directory {
name: result_line.split_whitespace().skip(1).next().unwrap().to_string()
})
result.push(FileSystemEntry::Directory)
} else {
let mut result_split = result_line.split_whitespace();
result.push(FileSystemEntry::File {
size: result_split.next().unwrap().parse::<usize>().unwrap(),
name: result_split.next().unwrap().to_owned()
size: result_split.next().unwrap().parse::<usize>().unwrap()
});
}
lines_iter.next();
} else {
break;
}
}
commands.push(Command::LS {
@@ -60,22 +57,91 @@ impl Day7 {
}
}
println!("{:?}", commands);
// println!("{:?}", commands);
// Put the input into the day struct
return Day7 {
commands
}
}
fn calculate_dir_sizes(&self) -> Vec<usize> {
let mut size_stack: Vec<usize> = Vec::new();
size_stack.push(0);
let mut dir_sizes: Vec<usize> = Vec::new();
for command in &self.commands {
// In the first pass, we only count files directly under it, then in the final pass we also include children.
match command {
Command::CD { target } => {
if target == ".." {
Day7::move_up_dir(&mut dir_sizes, &mut size_stack);
} else if target == "/" {
Day7::move_to_root(&mut dir_sizes, &mut size_stack);
} else {
size_stack.push(0);
}
}
Command::LS { result } => {
let file_size: usize = result.iter()
.map(|f| if let FileSystemEntry::File { size } = f { size.to_owned() } else { 0usize })
.sum();
Day7::increment_last(&mut size_stack, file_size);
}
}
}
Day7::move_to_root(&mut dir_sizes, &mut size_stack);
let root_size: usize = size_stack.last().unwrap().to_owned();
dir_sizes.push(root_size);
dir_sizes
}
fn move_to_root(dir_sizes: &mut Vec<usize>, size_stack: &mut Vec<usize>) {
// Note that the size stack must always have at least one entry left (for the root)
while size_stack.len() > 1 {
Day7::move_up_dir(dir_sizes, size_stack);
}
}
fn move_up_dir(dir_sizes: &mut Vec<usize>, size_stack: &mut Vec<usize>) {
// If we leave the directory, we should have collected all sizes of subdirs
dir_sizes.push(size_stack.last().unwrap().to_owned());
// We also need to add the child size to the size of the "parent"
if let Some(child_size) = size_stack.pop() {
Day7::increment_last(size_stack, child_size);
} else {
panic!("I kind of expected to always have a child size?");
}
}
fn increment_last(size_stack: &mut Vec<usize>, size: usize) {
if let Some(last) = size_stack.last_mut() {
*last += size;
}
}
}
impl DaySolver for Day7 {
fn solve_part1(&mut self) -> String {
return 0.to_string();
let dir_sizes = self.calculate_dir_sizes();
return dir_sizes.iter()
.filter(|size| size <= &&100000usize)
.sum::<usize>().to_string();
}
fn solve_part2(&mut self) -> String {
return 0.to_string();
let dir_sizes = self.calculate_dir_sizes();
let root_size = dir_sizes.last().unwrap();
let min_delete_size = 30_000_000usize - (70_000_000usize - root_size);
return dir_sizes.iter()
.filter(|s| s > &&min_delete_size)
.min().unwrap().to_string();
}
}

201
src/day8.rs Normal file
View File

@@ -0,0 +1,201 @@
use std::{fmt::{Debug, Display}};
use crate::day_solver::DaySolver;
use super::util;
#[derive(Debug, Clone)]
pub struct Grid<T> {
width: usize,
data: Vec<T>
}
impl<T: Clone + Sized> Grid<T> {
#[allow(dead_code)]
fn set_row(&mut self, x: usize, v: T) {
// let range = &mut self.data[x * self.width..(x+1) * self.width];
for i in self.width * x..self.width * (x + 1) {
self.data[i] = v.to_owned();
}
}
#[allow(dead_code)]
fn set_col(&mut self, x: usize, v: T) {
for y in 0..self.height() {
let idx = self.idx(&x, &y);
self.data[idx] = v.to_owned();
}
}
fn idx(&self, x: &usize, y: &usize) -> usize {
y * self.width + x
}
fn height(&self) -> usize {
self.data.len() / self.width
}
fn get(&self, x: &usize, y: &usize) -> &T {
let idx = self.idx(x, y);
&self.data[idx]
}
}
impl <T: Display + Clone + Sized> Grid<T> {
#[allow(dead_code)]
fn print(&self) {
for y in 0..self.height() {
for x in 0..self.width {
print!("{}", self.get(&x, &y))
}
println!();
}
}
}
#[derive(Debug, Clone)]
pub struct Day8 {
grid: Grid<u8>
}
impl Day8 {
pub fn create() -> Self {
// let lines = util::read_file("input/day8_example.txt");
let lines = util::read_file("input/day8.txt");
// Put the input into the day struct
let grid = Grid {
width: lines.first().unwrap().len(),
data: lines.join("").chars().map(|c| c.to_digit(10).unwrap() as u8).collect()
};
// println!("{:?}", grid);
return Day8 {
grid
}
}
fn calc_required_heights_for_x_range<R>(&self, y: usize, required_heights: &mut Grid<u8>, range: R)
where R: IntoIterator<Item = usize> {
let mut min_required_height = 0;
for x in range {
self.update_required_heights(x, y, required_heights, &mut min_required_height);
if min_required_height >= 10 { break }
}
}
fn calc_required_heights_for_y_range<R>(&self, x: usize, required_heights: &mut Grid<u8>, range: R)
where R: IntoIterator<Item = usize> {
let mut min_required_height = 0;
for y in range {
self.update_required_heights(x, y, required_heights, &mut min_required_height);
if min_required_height >= 10 { break }
}
}
fn update_required_heights(&self, x: usize, y: usize, required_heights: &mut Grid<u8>, min_required_height: &mut u8) {
let idx = self.grid.idx(&x, &y);
if required_heights.data[idx] >= *min_required_height {
required_heights.data[idx] = *min_required_height
}
let tree_height = self.grid.data[idx];
if tree_height + 1 > *min_required_height {
*min_required_height = tree_height + 1;
}
}
fn calc_viewing_dist_x<R>(&self, cur_height: &u8, x_range: R, y: &usize) -> usize
where R: IntoIterator<Item = usize> {
let mut count = 0;
for x in x_range {
count += 1;
if self.grid.get(&x, &y) >= cur_height {
break;
}
}
count
}
fn calc_viewing_dist_y<R>(&self, cur_height: &u8, x: &usize, y_range: R) -> usize
where R: IntoIterator<Item = usize> {
let mut count = 0;
for y in y_range {
count += 1;
if self.grid.get(&x, &y) >= &cur_height {
break;
}
}
count
}
}
impl DaySolver for Day8 {
fn solve_part1(&mut self) -> String {
let mut required_heights: Grid<u8> = Grid {
width: self.grid.width,
data: vec![10u8; self.grid.data.len()]
};
// First, we go over the rows, scanning them left-to-right
for y in 0..self.grid.height() {
self.calc_required_heights_for_x_range(y, &mut required_heights, 0..self.grid.width);
// println!("After y = {} L2R", y);
// required_heights.print();
self.calc_required_heights_for_x_range(y, &mut required_heights, (0..self.grid.width).rev());
// println!("After y = {} R2L", y);
// required_heights.print();
}
for x in 0..self.grid.width {
self.calc_required_heights_for_y_range(x, &mut required_heights, 0..self.grid.height());
self.calc_required_heights_for_y_range(x, &mut required_heights, (0..self.grid.height()).rev());
}
// required_heights.print();
let mut visible_trees = 0;
for i in 0..required_heights.data.len() {
if self.grid.data[i] >= required_heights.data[i] {
visible_trees += 1;
}
}
return visible_trees.to_string();
}
fn solve_part2(&mut self) -> String {
// Note that we skip the edges; since one of the distances is 0, the scenic score will also be 0
let mut max_scenic_score = 0;
for y in 1..self.grid.height() - 1 {
for x in 1..self.grid.width - 1 {
let cur_height = self.grid.get(&x, &y);
let right_view = self.calc_viewing_dist_x(cur_height, x+1..self.grid.width, &y);
let left_view = self.calc_viewing_dist_x(cur_height, (0..x).rev(), &y);
let up_view = self.calc_viewing_dist_y(cur_height, &x, y + 1..self.grid.height());
let down_view = self.calc_viewing_dist_y(cur_height, &x, (0..y).rev());
let scenic_score = left_view * right_view * up_view * down_view;
if scenic_score > max_scenic_score {
max_scenic_score = scenic_score;
}
}
}
return max_scenic_score.to_string();
}
}

155
src/day9.rs Normal file
View File

@@ -0,0 +1,155 @@
use std::collections::HashSet;
use crate::day_solver::DaySolver;
use super::util;
pub struct Day9 {
commands: Vec<Command>
}
impl Day9 {
pub fn create() -> Self {
// let lines = util::read_file("input/day9_example.txt");
// let lines = util::read_file(/"input/day9_example2.txt");
let lines = util::read_file("input/day9.txt");
// Put the input into the day struct
return Day9 {
commands: lines.iter()
.map(|s| {
let mut split = s.split_whitespace();
Command {
direction: split.next().unwrap().chars().next().unwrap(),
steps: split.next().unwrap().parse().unwrap()
}
})
.collect()
}
}
}
impl DaySolver for Day9 {
fn solve_part1(&mut self) -> String {
let mut head = Vec2 { x: 0, y: 0 };
let mut tail = Vec2 { x: 0, y: 0 };
let mut tail_positions: HashSet<Vec2> = HashSet::new();
tail_positions.insert(tail.to_owned());
for command in &self.commands {
for _ in 0..command.steps {
head.move_into_direction(&command.direction);
if !tail.is_adjacent(&head) {
tail.move_towards(&head);
tail_positions.insert(tail.to_owned());
}
}
}
return tail_positions.len().to_string();
}
fn solve_part2(&mut self) -> String {
let mut knot_positions = vec![Vec2 { x: 0, y: 0 }; 9];
let mut head = Vec2 { x: 0, y: 0 };
let mut tail_positions: HashSet<Vec2> = HashSet::new();
tail_positions.insert(knot_positions.last().unwrap().to_owned());
for command in &self.commands {
for _ in 0..command.steps {
head.move_into_direction(&command.direction);
let mut connected_knot = &head;
for knot in &mut knot_positions {
if !knot.is_adjacent(connected_knot) {
knot.move_towards(connected_knot);
}
connected_knot = knot;
}
tail_positions.insert(knot_positions.last().unwrap().to_owned());
}
// println!("After step {} {}", command.direction, command.steps);
// draw_rope(&head, &knot_positions);
}
return tail_positions.len().to_string();
}
}
#[derive(Debug, Clone)]
struct Command {
direction: char,
steps: i32
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Vec2 {
x: i32,
y: i32
}
impl Vec2 {
fn is_adjacent(&self, other: &Vec2) -> bool {
self.x.abs_diff(other.x) <= 1 && self.y.abs_diff(other.y) <= 1
}
fn move_into_direction(&mut self, direction: &char) {
match direction {
'U' => self.y += 1,
'D' => self.y -= 1,
'L' => self.x -= 1,
'R' => self.x += 1,
_ => panic!("Unknown direction: {}", direction)
}
}
fn move_towards(&mut self, target: &Vec2) {
if target.x > self.x {
self.x += 1;
} else if target.x < self.x {
self.x -= 1;
}
if target.y > self.y {
self.y += 1;
} else if target.y < self.y {
self.y -= 1;
}
}
}
#[allow(dead_code)]
fn draw_rope(head: &Vec2, knot_positions: &Vec<Vec2>) {
let min_x = 0.min(head.x.min(knot_positions.iter().map(|k| k.x).min().unwrap()));
let max_x = head.x.max(knot_positions.iter().map(|k| k.x).max().unwrap());
let min_y = 0.min(head.y.min(knot_positions.iter().map(|k| k.y).min().unwrap()));
let max_y = head.y.max(knot_positions.iter().map(|k| k.y).max().unwrap());
for y in (min_y..max_y+1).rev() {
for x in min_x..max_x+1 {
if head.x == x && head.y == y {
print!("H")
} else if let Some(k) = knot_positions.iter().enumerate()
.find_map(|(i, k)| if k.x == x && k.y == y { Some(i)} else { None }) {
if k == knot_positions.len() - 1 {
print!("T");
} else {
print!("{}", k + 1);
}
} else if x == 0 && y == 0 {
print!("s");
} else {
print!(".");
}
}
println!()
}
}

View File

@@ -6,6 +6,9 @@ use crate::day4::Day4;
use crate::day5::Day5;
use crate::day6::Day6;
use crate::day7::Day7;
use crate::day8::Day8;
use crate::day9::Day9;
use crate::day10::Day10;
use crate::day_solver::DaySolver;
mod util;
@@ -17,8 +20,11 @@ mod day4;
mod day5;
mod day6;
mod day7;
mod day8;
mod day9;
mod day10;
const MAX_DAY: u8 = 7;
const MAX_DAY: u8 = 9;
const DEFAULT_BENCHMARK_AMOUNT: u32 = 100;
fn main() {
@@ -89,6 +95,9 @@ fn build_day_solver(day: u8) -> Option<Box<dyn DaySolver>> {
5 => Some(Box::new(Day5::create())),
6 => Some(Box::new(Day6::create())),
7 => Some(Box::new(Day7::create())),
8 => Some(Box::new(Day8::create())),
9 => Some(Box::new(Day9::create())),
10 => Some(Box::new(Day10::create())),
_ => None
}
}
@@ -112,7 +121,7 @@ fn solve(day: u8, silent: bool) -> AocBenchResult {
let (part2, pt2_time) = bench(|| s.solve_part2());
part2_time = pt2_time;
if !silent {
println!("Day {} Part 1: {}", day, part2);
println!("Day {} Part 2: {}", day, part2);
}
},
None => panic!("This day is not yet implemented")