first commit

This commit is contained in:
Zenn 2023-09-12 09:55:00 +02:00
commit cfe3798d17
42 changed files with 9617 additions and 0 deletions

1
2022/day1/.gitignore vendored Executable file
View file

@ -0,0 +1 @@
/target

7
2022/day1/Cargo.lock generated Executable file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day1"
version = "0.1.0"

8
2022/day1/Cargo.toml Executable file
View file

@ -0,0 +1,8 @@
[package]
name = "day1"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

35
2022/day1/Task Executable file
View file

@ -0,0 +1,35 @@
The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input).
The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line.
For example, suppose the Elves finish writing their items' Calories and end up with the following list:
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
This list represents the Calories of the food carried by five Elves:
The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories.
The second Elf is carrying one food item with 4000 Calories.
The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories.
The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories.
The fifth Elf is carrying one food item with 10000 Calories.
In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf).
Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
Answer: 71934
duration 390.9µs - 950.1µs

2255
2022/day1/data Executable file

File diff suppressed because it is too large Load diff

39
2022/day1/src/main.rs Executable file
View file

@ -0,0 +1,39 @@
use std::fs::File;
use std::io::prelude::*;
use std::io::Result;
use std::time::Instant;
fn main() -> Result<()> {
let start_time = Instant::now();
let mut x = File::open("./data").expect("file not found");
let mut content = String::new();
x.read_to_string(&mut content)?;
// Part 1
let mut elf: Vec<i32> = content
.split("\n")
.collect::<Vec<&str>>()
.split(|line| line.is_empty())
.map(|line| line.iter().fold(0, |acc, x| acc + x.parse::<i32>().unwrap()))
.collect();
// Part 1 version 2
// let mut elf: Vec<i32> = content
// .lines()
// .map(|line| line.parse::<i32>().unwrap_or_default())
// .collect::<Vec<i32>>()
// .split(|line| *line == 0)
// .map(|x| x.iter().fold(0, |acc, x| acc + x))
// .collect();
println!("Elf with: {} Calories", elf.iter().max().unwrap());
let duration = start_time.elapsed();
println!("{:?}", duration);
// Part 2
elf.sort();
let max = elf.pop().unwrap();
let mid = elf.pop().unwrap();
let min = elf.pop().unwrap();
println!("{:?}", max + mid + min);
Ok(())
}

1
2022/day2/.gitignore vendored Executable file
View file

@ -0,0 +1 @@
/target

7
2022/day2/Cargo.lock generated Executable file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day2"
version = "0.1.0"

8
2022/day2/Cargo.toml Executable file
View file

@ -0,0 +1,8 @@
[package]
name = "day2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

2500
2022/day2/data Executable file

File diff suppressed because it is too large Load diff

142
2022/day2/src/main.rs Executable file
View file

@ -0,0 +1,142 @@
use std::{
fs::File,
io::{Read, Result},
time::Instant,
};
#[derive(Debug, PartialEq)]
#[allow(dead_code)]
enum State {
Rock,
Paper,
Scissors,
Win,
Lose,
Draw,
None,
}
impl State {
fn new(x: &str) -> Self {
match x {
"A" => State::Rock,
"X" => State::Rock,
"B" => State::Paper,
"Y" => State::Paper,
"C" => State::Scissors,
"Z" => State::Scissors,
_ => State::None,
}
}
fn new_part2(x: &str) -> Self {
match x {
"A" => State::Rock,
"X" => State::Lose,
"B" => State::Paper,
"Y" => State::Draw,
"C" => State::Scissors,
"Z" => State::Win,
_ => State::None,
}
}
fn get_points(&self) -> i32 {
match self {
Self::Rock => 1,
Self::Paper => 2,
Self::Scissors => 3,
_ => 0,
}
}
}
#[derive(Debug)]
struct Turn {
oponent: State,
my: State,
points: i32,
}
impl Turn {
fn new(oponent: State, my: State) -> Self {
Turn {
oponent,
my,
points: 0,
}
}
fn count_points(&mut self) {
self.points += self.my.get_points();
if self.oponent == self.my {
self.points += 3;
return;
}
let turn = (&self.my, &self.oponent);
match turn {
(State::Rock, State::Scissors) => self.points += 6,
(State::Paper, State::Rock) => self.points += 6,
(State::Scissors, State::Paper) => self.points += 6,
_ => (),
};
}
fn change_my(&mut self) {
match self.my {
State::Win => match self.oponent {
State::Rock => self.my = State::Paper,
State::Paper => self.my = State::Scissors,
State::Scissors => self.my = State::Rock,
_ => (),
},
State::Draw => match self.oponent {
State::Rock => self.my = State::Rock,
State::Paper => self.my = State::Paper,
State::Scissors => self.my = State::Scissors,
_ => (),
},
State::Lose => match self.oponent {
State::Rock => self.my = State::Scissors,
State::Paper => self.my = State::Rock,
State::Scissors => self.my = State::Paper,
_ => (),
},
_ => (),
}
}
}
fn main() -> Result<()> {
let start = Instant::now();
let mut file = File::open("./data").expect("File not Found");
let mut content = String::new();
file.read_to_string(&mut content)?;
// Part 1
let turns: Vec<Turn> = content
.split("\n")
.map(|line| {
let felds: Vec<&str> = line.split(" ").collect();
let mut turn = Turn::new(State::new(felds[0]), State::new(felds[1]));
turn.count_points();
turn
})
.collect();
let points = turns.iter().fold(0, |acc, x| acc + x.points);
println!("{}", points);
let end = start.elapsed();
println!("{:?}", end);
// Part 2
let start = Instant::now();
let turns: Vec<Turn> = content
.split("\n")
.map(|line| {
let felds: Vec<&str> = line.split(" ").collect();
let mut turn = Turn::new(State::new(felds[0]), State::new_part2(felds[1]));
turn.change_my();
turn.count_points();
turn
})
.collect();
let points = turns.iter().fold(0, |acc, x| acc + x.points);
println!("{}", points);
let end = start.elapsed();
println!("{:?}", end);
Ok(())
}

31
2022/day2/task Executable file
View file

@ -0,0 +1,31 @@
--- Day 2: Rock Paper Scissors ---
The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress.
Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw.
Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent.
The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen.
The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).
Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide.
For example, suppose you were given the following strategy guide:
A Y
B X
C Z
This strategy guide predicts and recommends the following:
In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won).
In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0).
The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6.
In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6).
What would your total score be if everything goes exactly according to your strategy guide?
Answer:

1
2022/day3/.gitignore vendored Executable file
View file

@ -0,0 +1 @@
/target

7
2022/day3/Cargo.lock generated Executable file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day3"
version = "0.1.0"

8
2022/day3/Cargo.toml Executable file
View file

@ -0,0 +1,8 @@
[package]
name = "day3"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

300
2022/day3/data Executable file
View file

@ -0,0 +1,300 @@
WVHGHwddqSsNjsjwqVvdwZRCbcJcZTCcsZbLcJJsCZ
hngprFFhFDFhrDpzzQDhtnBJJRJZbZvTcvbfRCJfBRcBJl
DmptngtFwvvMmwmm
HFddrJnLdqtHBMQBmmVm
gbvNsbhsvQtmZTbQPT
vDshDlczcDhcssscwzQwslLJrSJLpqrrzpnCrSfLSnqq
pDGQDSpFDGzFDQSJqzDhjhQMTjTrwTstbTBTjTtLtbTMBT
zgzVNHHgMwMLbLNB
WRWPgdHCZccggJmJGzJmzGhGCD
sVJNlhldShpdpnnwVnwCwtwggt
WLFFcHWQLPPZQCgtnCgmbtbHwt
MPLWzRMMcGgRrWNDpSSSfDflMlTd
BBMZJcgBRjCZZzBpSvHQvbLvvHCQLQ
VlVTFwDTVGnfWSQPtsDPbvrpDS
wWdqhWlwGVfGwlfTVqFWfWWjzZZBJmMZMNdzZJMpjzNjgJ
FBWFphQBmDmpmMSpDWVcVcvsPcRbrjPMcMsr
HHtdnHnwNCHCTJRTPTzrbvVbcVRr
lHqHwlnlqnGCNGGmWDvvZfpZvG
mfVtmPtsccMmHcHCFfmhVmnpgZLbWPZqWnpqZbZWpgPW
zzvwBrzdQDvpZJfQJZJpLf
BrTBwRdNcfNmfStc
sTlhFLfZTTLcfsLlLDZflvQvRNqRJFNvRMRNvQQRBQ
CWcgwStWwCWWwvgNQvJBvQMQRB
wptGzbzGWVGSCVVlVlLDcVVsfhLTlf
HVnMVGwLLbsGnVsLnwLSBggMhjmgmgmhtmqhtgMhMj
zrZzJRZfzZfrPCrFcWccPdTdHHlvdmlgTghCtmtTgq
NFfcZWWzZrrHLBpBBGVGNG
HqFhhCBCBLmwwCqJCHFvvFdcprrrSSrjRFRjpgrggb
VGzWtQzGGQPVtlVNslVWs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hlJMpWW
TMPcsPDjdDhsDcDcTTTDvdvghBNFGGtmNrSrgSSBGNtNFg
CVCbJqlRVVWWpRqRQZRWVWJZBtmSFGNmggGmtmmBFbrGMGMt
JRqHVJVCRLZWTjMnfLTPcfLd
TRTZFTTrghrZVhVWdWZpMmbzbdzBmtDpDDzmzB
wcsSSsjfPfGPqQwqsQcfJJCtJGpppCBJzCbzJzCb
sPjflcwljfjfvqNcTZTRhtVWrNrVLnrR
rVLLsmwmCWTmsCTdwQrdTmqWDjDHjNGNPbjDBPNDNsZRDBjH
cFcSvgJvfhfLnShtMJtPHRRvRbBBGBPNBHPbND
hgLcgcLpJSMwzmrmzqQrmp

64
2022/day3/src/main.rs Executable file
View file

@ -0,0 +1,64 @@
use std::{
fs::File,
io::{Read, Result},
};
fn main() -> Result<()> {
let mut file = File::open("./data").expect("Data file not found");
let mut content = String::new();
file.read_to_string(&mut content)?;
// Part 1
let rucksack: Vec<char> = content
.split("\n")
.map(|line| {
let mid = line.len() / 2;
let left = &line[..mid];
let right = &line[mid..];
let mut left_chars = left.chars();
left_chars.find(|c| right.contains(c.to_owned())).unwrap()
})
.collect();
let weigth = vec![
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
let priority: Vec<usize> = rucksack
.iter()
.map(|c| weigth.iter().position(|x| x == c).unwrap())
.collect();
println!("{:?}", priority.iter().map(|x| x + 1).sum::<usize>());
// Part 2
let mut rucksacks: Vec<&str> = content.split("\n").collect();
let mut group = Vec::new();
for _ in 0..rucksacks.len() / 3 {
let one = rucksacks.pop().unwrap();
let two = rucksacks.pop().unwrap();
let three = rucksacks.pop().unwrap();
group.push(vec![one, two, three])
}
let group: Vec<char> = group
.iter()
.map(|group| {
let one = group[0];
let two = group[1];
let three = group[2];
let one_chars = one.chars();
let three_chars = three.chars();
let one_two = one_chars.filter(|&c| two.contains(c)).collect::<Vec<char>>();
let mut one_two_three =
three_chars.filter(|&c| one_two.contains(&c)).collect::<Vec<char>>();
one_two_three.pop().unwrap()
//three_chars.find(|c|one_two.)
})
.collect();
let priority: Vec<usize> = group
.iter()
.map(|c| weigth.iter().position(|x| x == c).unwrap())
.collect();
println!("{:?}", priority.iter().map(|x| x + 1).sum::<usize>());
Ok(())
}

66
2022/day3/task Executable file
View file

@ -0,0 +1,66 @@
--- Day 3: Rucksack Reorganization ---
One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.
Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).
The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.
For example, suppose you have the following list of contents from six rucksacks:
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L.
The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
The fourth rucksack's compartments only share item type v.
The fifth rucksack's compartments only share item type t.
The sixth rucksack's compartments only share item type s.
To help prioritize item rearrangement, every item type can be converted to a priority:
Lowercase item types a through z have priorities 1 through 26.
Uppercase item types A through Z have priorities 27 through 52.
In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?
answer part 1: 7763
--- Part Two ---
As you finish identifying the misplaced items, the Elves come to you with another issue.
For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group's badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type.
The problem is that someone forgot to put this year's updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached.
Additionally, nobody wrote down which item type corresponds to each group's badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group.
Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group's rucksacks are the first three lines:
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
And the second group's rucksacks are the next three lines:
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z.
Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for the first group and 52 (Z) for the second group. The sum of these is 70.
Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?
answer part 2: 2569

1
2022/day4/.gitignore vendored Executable file
View file

@ -0,0 +1 @@
/target

7
2022/day4/Cargo.lock generated Executable file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day4"
version = "0.1.0"

8
2022/day4/Cargo.toml Executable file
View file

@ -0,0 +1,8 @@
[package]
name = "day4"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1000
2022/day4/data Executable file

File diff suppressed because it is too large Load diff

56
2022/day4/src/main.rs Executable file
View file

@ -0,0 +1,56 @@
use std::{
fs::File,
io::{Read, Result},
};
fn main() -> Result<()> {
let mut file = File::open("./data").expect("Data file not found");
let mut content = String::new();
file.read_to_string(&mut content)?;
let data = content
.split("\n")
.collect::<Vec<&str>>()
.iter()
.map(|line| {
line.split(",")
.map(|x| {
x.split("-")
.filter_map(|x| x.parse::<i32>().ok())
.collect::<Vec<i32>>()
})
.collect::<Vec<Vec<i32>>>()
})
.collect::<Vec<Vec<Vec<i32>>>>()
.iter()
.map(|x| (x[0].to_owned(), x[1].to_owned()))
.collect::<Vec<(Vec<i32>, Vec<i32>)>>();
// Part 1
let containig_pairs: Vec<&(Vec<i32>, Vec<i32>)> = data
.iter()
.filter(|(x, y)| {
let ll = &x[0];
let lr = &x[1];
let rl = &y[0];
let rr = &y[1];
ll >= rl && lr <= rr || rl >= ll && rr <= lr
})
.collect();
println!("data len: {:?}", data.len());
println!("containig pairs: {:?}", containig_pairs.len());
// Part 2
let overlaping: Vec<&(Vec<i32>, Vec<i32>)> = data
.iter()
.filter(|(x, y)| {
let ll = &x[0];
let lr = &x[1];
let rl = &y[0];
let rr = &y[1];
lr >= rl && lr <= rr || rr >= ll && rr <= lr
})
.collect();
println!("overlaping: {:?}", overlaping.len());
Ok(())
}

66
2022/day4/task.txt Executable file
View file

@ -0,0 +1,66 @@
--- Day 4: Camp Cleanup ---
Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned a range of section IDs.
However, as some of the Elves compare their section assignments with each other, they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input).
For example, consider the following list of section assignment pairs:
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
For the first few pairs, this list means:
Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf was assigned sections 6-8 (sections 6, 7, 8).
The Elves in the second pair were each assigned two sections.
The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, while the other also got 7, plus 8 and 9.
This example list uses single-digit section IDs to make it easier to draw; your actual list might contain larger numbers. Visually, these pairs of section assignments look like this:
.234..... 2-4
.....678. 6-8
.23...... 2-3
...45.... 4-5
....567.. 5-7
......789 7-9
.2345678. 2-8
..34567.. 3-7
.....6... 6-6
...456... 4-6
.23456... 2-6
...45678. 4-8
Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most in need of reconsideration. In this example, there are 2 such pairs.
In how many assignment pairs does one range fully contain the other?
Answer Part1: 540
--- Part Two ---
It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number of pairs that overlap at all.
In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap:
5-7,7-9 overlaps in a single section, 7.
2-8,3-7 overlaps all of the sections 3 through 7.
6-6,4-6 overlaps in a single section, 6.
2-6,4-8 overlaps in sections 4, 5, and 6.
So, in this example, the number of overlapping assignment pairs is 4.
In how many assignment pairs do the ranges overlap?
Answer part2: 872
935 to high
705 to low
716 to low

1
2022/day5/.gitignore vendored Executable file
View file

@ -0,0 +1 @@
/target

7
2022/day5/Cargo.lock generated Executable file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day5"
version = "0.1.0"

8
2022/day5/Cargo.toml Executable file
View file

@ -0,0 +1,8 @@
[package]
name = "day5"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

512
2022/day5/data Executable file
View file

@ -0,0 +1,512 @@
[F] [Q] [Q]
[B] [Q] [V] [D] [S]
[S] [P] [T] [R] [M] [D]
[J] [V] [W] [M] [F] [J] [J]
[Z] [G] [S] [W] [N] [D] [R] [T]
[V] [M] [B] [G] [S] [C] [T] [V] [S]
[D] [S] [L] [J] [L] [G] [G] [F] [R]
[G] [Z] [C] [H] [C] [R] [H] [P] [D]
1 2 3 4 5 6 7 8 9
1 5 9 13 17 21 25 29 32
move 3 from 5 to 2
move 3 from 8 to 4
move 7 from 7 to 3
move 14 from 3 to 9
move 8 from 4 to 1
move 1 from 7 to 5
move 2 from 6 to 4
move 4 from 5 to 7
move 1 from 3 to 6
move 3 from 4 to 3
move 1 from 4 to 1
move 5 from 1 to 9
move 1 from 4 to 6
move 4 from 7 to 4
move 15 from 9 to 2
move 7 from 1 to 6
move 3 from 3 to 5
move 1 from 4 to 9
move 2 from 5 to 3
move 2 from 4 to 9
move 4 from 1 to 6
move 1 from 3 to 1
move 1 from 3 to 2
move 4 from 6 to 3
move 24 from 2 to 8
move 4 from 9 to 8
move 1 from 1 to 3
move 2 from 5 to 4
move 1 from 2 to 4
move 19 from 8 to 1
move 5 from 3 to 9
move 8 from 1 to 3
move 3 from 4 to 1
move 6 from 9 to 5
move 2 from 3 to 4
move 1 from 8 to 5
move 2 from 4 to 6
move 11 from 6 to 1
move 8 from 8 to 7
move 1 from 6 to 5
move 13 from 1 to 3
move 1 from 1 to 7
move 2 from 7 to 8
move 5 from 7 to 1
move 2 from 8 to 4
move 3 from 5 to 3
move 11 from 3 to 1
move 2 from 5 to 3
move 2 from 5 to 3
move 2 from 7 to 1
move 7 from 3 to 1
move 1 from 4 to 5
move 1 from 6 to 4
move 3 from 4 to 7
move 3 from 7 to 1
move 6 from 3 to 5
move 1 from 5 to 9
move 4 from 5 to 4
move 2 from 3 to 4
move 8 from 9 to 2
move 5 from 4 to 6
move 1 from 6 to 5
move 1 from 4 to 9
move 39 from 1 to 7
move 7 from 2 to 6
move 1 from 9 to 3
move 1 from 2 to 7
move 1 from 3 to 1
move 5 from 7 to 3
move 4 from 5 to 1
move 19 from 7 to 9
move 1 from 9 to 8
move 1 from 9 to 7
move 5 from 9 to 3
move 6 from 6 to 7
move 1 from 8 to 3
move 4 from 1 to 4
move 23 from 7 to 6
move 1 from 1 to 6
move 21 from 6 to 2
move 3 from 4 to 8
move 7 from 6 to 1
move 1 from 4 to 9
move 1 from 6 to 7
move 6 from 1 to 2
move 1 from 7 to 4
move 15 from 2 to 8
move 5 from 3 to 8
move 22 from 8 to 7
move 1 from 8 to 1
move 5 from 3 to 4
move 1 from 3 to 2
move 1 from 1 to 2
move 3 from 4 to 8
move 3 from 8 to 9
move 11 from 2 to 1
move 2 from 1 to 4
move 15 from 9 to 5
move 22 from 7 to 3
move 2 from 4 to 9
move 3 from 4 to 2
move 8 from 1 to 8
move 6 from 8 to 6
move 1 from 6 to 2
move 3 from 6 to 9
move 3 from 2 to 7
move 4 from 2 to 9
move 2 from 7 to 5
move 1 from 1 to 7
move 2 from 8 to 2
move 2 from 7 to 5
move 9 from 5 to 3
move 8 from 5 to 2
move 1 from 6 to 4
move 1 from 6 to 9
move 1 from 2 to 9
move 2 from 5 to 1
move 7 from 2 to 3
move 1 from 4 to 3
move 1 from 2 to 4
move 5 from 3 to 4
move 6 from 9 to 3
move 1 from 2 to 6
move 6 from 9 to 6
move 2 from 1 to 8
move 3 from 6 to 3
move 2 from 8 to 6
move 6 from 4 to 1
move 14 from 3 to 9
move 1 from 6 to 4
move 3 from 3 to 9
move 1 from 4 to 5
move 10 from 9 to 6
move 6 from 6 to 7
move 2 from 1 to 8
move 1 from 8 to 6
move 16 from 3 to 2
move 1 from 8 to 1
move 1 from 7 to 1
move 7 from 3 to 4
move 1 from 6 to 5
move 4 from 2 to 3
move 5 from 4 to 9
move 2 from 4 to 5
move 4 from 7 to 4
move 5 from 9 to 6
move 2 from 5 to 4
move 11 from 6 to 7
move 1 from 6 to 8
move 5 from 1 to 5
move 2 from 6 to 4
move 7 from 7 to 3
move 1 from 8 to 6
move 2 from 7 to 3
move 1 from 1 to 3
move 3 from 2 to 8
move 9 from 2 to 5
move 1 from 6 to 1
move 1 from 4 to 8
move 7 from 4 to 7
move 8 from 5 to 6
move 1 from 7 to 2
move 1 from 7 to 4
move 3 from 7 to 8
move 1 from 2 to 3
move 1 from 1 to 2
move 1 from 1 to 7
move 3 from 7 to 6
move 11 from 6 to 2
move 4 from 8 to 7
move 2 from 8 to 7
move 15 from 3 to 2
move 7 from 9 to 4
move 3 from 3 to 2
move 4 from 4 to 7
move 5 from 7 to 3
move 3 from 4 to 6
move 3 from 6 to 9
move 1 from 4 to 2
move 1 from 8 to 1
move 2 from 3 to 7
move 2 from 3 to 7
move 23 from 2 to 5
move 1 from 9 to 1
move 1 from 7 to 9
move 1 from 1 to 8
move 8 from 7 to 1
move 1 from 8 to 4
move 1 from 4 to 2
move 3 from 9 to 8
move 1 from 7 to 9
move 22 from 5 to 9
move 1 from 8 to 5
move 1 from 7 to 4
move 1 from 4 to 5
move 1 from 8 to 3
move 2 from 9 to 3
move 5 from 5 to 2
move 5 from 5 to 4
move 3 from 2 to 7
move 1 from 7 to 3
move 6 from 1 to 7
move 4 from 3 to 1
move 6 from 2 to 8
move 1 from 5 to 6
move 2 from 8 to 1
move 12 from 9 to 4
move 8 from 9 to 4
move 1 from 2 to 9
move 2 from 9 to 8
move 3 from 2 to 8
move 5 from 8 to 6
move 7 from 7 to 1
move 4 from 8 to 9
move 1 from 6 to 1
move 17 from 4 to 7
move 1 from 2 to 4
move 2 from 4 to 1
move 6 from 4 to 6
move 1 from 1 to 4
move 7 from 1 to 5
move 9 from 7 to 9
move 8 from 9 to 8
move 5 from 8 to 3
move 1 from 5 to 6
move 2 from 3 to 6
move 1 from 9 to 1
move 1 from 6 to 1
move 10 from 6 to 1
move 1 from 5 to 1
move 2 from 9 to 1
move 1 from 9 to 7
move 2 from 6 to 8
move 2 from 8 to 2
move 1 from 6 to 8
move 22 from 1 to 9
move 9 from 7 to 5
move 1 from 8 to 1
move 2 from 8 to 3
move 4 from 5 to 9
move 1 from 8 to 3
move 5 from 1 to 9
move 2 from 7 to 3
move 2 from 4 to 7
move 1 from 8 to 5
move 2 from 2 to 4
move 1 from 5 to 8
move 9 from 5 to 8
move 2 from 7 to 5
move 2 from 4 to 5
move 3 from 8 to 4
move 3 from 4 to 3
move 2 from 8 to 6
move 1 from 6 to 4
move 3 from 5 to 9
move 1 from 6 to 3
move 12 from 3 to 5
move 1 from 3 to 1
move 7 from 5 to 4
move 1 from 1 to 3
move 1 from 8 to 1
move 7 from 5 to 1
move 6 from 9 to 6
move 29 from 9 to 5
move 2 from 4 to 6
move 26 from 5 to 2
move 24 from 2 to 7
move 1 from 3 to 2
move 8 from 1 to 7
move 7 from 6 to 9
move 2 from 5 to 3
move 1 from 6 to 4
move 3 from 8 to 5
move 2 from 3 to 8
move 2 from 2 to 8
move 5 from 9 to 2
move 27 from 7 to 2
move 2 from 8 to 3
move 2 from 9 to 5
move 3 from 8 to 5
move 2 from 7 to 4
move 3 from 4 to 7
move 2 from 3 to 2
move 4 from 5 to 1
move 5 from 7 to 2
move 29 from 2 to 8
move 9 from 8 to 3
move 2 from 4 to 8
move 7 from 3 to 2
move 3 from 5 to 4
move 1 from 7 to 5
move 3 from 5 to 6
move 2 from 1 to 8
move 2 from 6 to 8
move 3 from 4 to 2
move 4 from 4 to 2
move 1 from 6 to 8
move 8 from 2 to 4
move 2 from 3 to 5
move 1 from 4 to 1
move 3 from 1 to 2
move 4 from 8 to 2
move 3 from 4 to 9
move 3 from 4 to 1
move 2 from 9 to 5
move 1 from 4 to 6
move 4 from 5 to 1
move 1 from 6 to 8
move 1 from 9 to 3
move 4 from 2 to 3
move 15 from 8 to 2
move 9 from 8 to 1
move 1 from 3 to 9
move 5 from 1 to 9
move 3 from 9 to 7
move 2 from 7 to 6
move 3 from 3 to 2
move 1 from 7 to 8
move 1 from 9 to 6
move 1 from 9 to 8
move 2 from 8 to 2
move 1 from 1 to 2
move 1 from 3 to 7
move 4 from 1 to 7
move 19 from 2 to 5
move 1 from 1 to 4
move 1 from 7 to 4
move 1 from 1 to 5
move 3 from 1 to 4
move 1 from 1 to 8
move 6 from 2 to 4
move 7 from 2 to 1
move 2 from 7 to 9
move 8 from 2 to 8
move 2 from 7 to 3
move 1 from 6 to 4
move 10 from 4 to 6
move 5 from 6 to 7
move 2 from 9 to 8
move 6 from 8 to 9
move 1 from 2 to 3
move 2 from 8 to 3
move 5 from 1 to 8
move 8 from 5 to 2
move 8 from 8 to 7
move 7 from 2 to 8
move 1 from 1 to 2
move 1 from 9 to 7
move 1 from 4 to 2
move 2 from 2 to 6
move 5 from 9 to 3
move 2 from 8 to 6
move 2 from 3 to 9
move 4 from 8 to 6
move 7 from 6 to 1
move 8 from 1 to 5
move 1 from 8 to 7
move 1 from 9 to 6
move 12 from 5 to 3
move 1 from 4 to 8
move 2 from 9 to 5
move 1 from 2 to 3
move 3 from 5 to 1
move 1 from 1 to 5
move 21 from 3 to 8
move 2 from 1 to 5
move 6 from 5 to 7
move 2 from 5 to 6
move 10 from 6 to 9
move 1 from 6 to 8
move 13 from 8 to 2
move 2 from 5 to 4
move 2 from 4 to 3
move 4 from 9 to 1
move 5 from 7 to 8
move 12 from 8 to 1
move 5 from 9 to 6
move 1 from 3 to 7
move 2 from 6 to 5
move 11 from 2 to 1
move 1 from 8 to 4
move 16 from 1 to 9
move 1 from 2 to 6
move 1 from 8 to 5
move 12 from 9 to 3
move 14 from 7 to 2
move 1 from 7 to 9
move 1 from 4 to 2
move 1 from 7 to 5
move 3 from 9 to 5
move 4 from 6 to 9
move 3 from 9 to 4
move 1 from 8 to 4
move 2 from 4 to 5
move 1 from 7 to 1
move 5 from 3 to 5
move 2 from 4 to 2
move 8 from 2 to 7
move 7 from 2 to 4
move 1 from 3 to 7
move 3 from 9 to 7
move 2 from 2 to 9
move 3 from 4 to 5
move 6 from 1 to 8
move 6 from 1 to 5
move 3 from 9 to 2
move 22 from 5 to 9
move 1 from 5 to 6
move 2 from 2 to 3
move 5 from 7 to 6
move 5 from 8 to 9
move 2 from 7 to 2
move 20 from 9 to 4
move 1 from 8 to 3
move 2 from 2 to 5
move 1 from 2 to 5
move 15 from 4 to 8
move 1 from 5 to 7
move 6 from 9 to 1
move 5 from 4 to 8
move 2 from 4 to 8
move 1 from 2 to 1
move 5 from 6 to 5
move 5 from 5 to 7
move 1 from 9 to 8
move 5 from 7 to 2
move 2 from 5 to 1
move 4 from 7 to 5
move 1 from 5 to 9
move 1 from 6 to 8
move 1 from 7 to 2
move 6 from 3 to 4
move 3 from 5 to 7
move 1 from 9 to 2
move 6 from 2 to 3
move 1 from 3 to 4
move 13 from 8 to 9
move 7 from 1 to 5
move 6 from 9 to 2
move 1 from 1 to 4
move 6 from 2 to 3
move 1 from 1 to 4
move 5 from 9 to 7
move 11 from 8 to 4
move 7 from 7 to 3
move 2 from 7 to 8
move 1 from 8 to 2
move 8 from 4 to 1
move 2 from 1 to 6
move 2 from 5 to 8
move 3 from 1 to 9
move 1 from 8 to 2
move 11 from 3 to 2
move 2 from 8 to 9
move 9 from 4 to 7
move 11 from 3 to 8
move 7 from 9 to 6
move 5 from 4 to 6
move 3 from 7 to 3
move 1 from 7 to 1
move 5 from 7 to 6
move 2 from 3 to 5
move 1 from 3 to 4
move 5 from 2 to 5
move 1 from 1 to 7
move 1 from 4 to 8
move 1 from 7 to 6
move 7 from 5 to 7
move 2 from 5 to 7
move 3 from 1 to 7
move 1 from 2 to 3
move 1 from 6 to 4
move 1 from 3 to 4
move 1 from 5 to 3
move 18 from 6 to 4
move 9 from 7 to 1
move 14 from 4 to 6
move 3 from 6 to 4
move 12 from 6 to 7
move 2 from 5 to 3
move 3 from 7 to 4
move 6 from 4 to 7
move 5 from 1 to 7
move 5 from 4 to 5
move 5 from 2 to 1
move 9 from 8 to 4
move 9 from 1 to 3
move 2 from 8 to 2
move 4 from 2 to 4
move 1 from 7 to 6
move 1 from 2 to 3
move 1 from 8 to 9
move 1 from 6 to 9
move 2 from 9 to 3
move 3 from 4 to 1
move 13 from 3 to 5
move 12 from 5 to 1
move 7 from 1 to 8
move 1 from 3 to 6
move 4 from 5 to 4
move 1 from 5 to 2
move 8 from 4 to 9

195
2022/day5/src/main.rs Executable file
View file

@ -0,0 +1,195 @@
use std::{
fs::File,
io::{Read, Result},
};
#[derive(Debug)]
struct Playground {
stack1: Vec<char>,
stack2: Vec<char>,
stack3: Vec<char>,
stack4: Vec<char>,
stack5: Vec<char>,
stack6: Vec<char>,
stack7: Vec<char>,
stack8: Vec<char>,
stack9: Vec<char>,
}
impl Playground {
fn new() -> Playground {
Playground {
stack1: vec![],
stack2: vec![],
stack3: vec![],
stack4: vec![],
stack5: vec![],
stack6: vec![],
stack7: vec![],
stack8: vec![],
stack9: vec![],
}
}
fn print_result(&mut self) {
println!(
"{}{}{}{}{}{}{}{}{}",
self.stack1.pop().unwrap(),
self.stack2.pop().unwrap(),
self.stack3.pop().unwrap(),
self.stack4.pop().unwrap(),
self.stack5.pop().unwrap(),
self.stack6.pop().unwrap(),
self.stack7.pop().unwrap(),
self.stack8.pop().unwrap(),
self.stack9.pop().unwrap(),
)
}
fn move_crain(&mut self, turn: &Turn) {
for _ in 0..turn.amount {
let from = match turn.from {
1 => &mut self.stack1,
2 => &mut self.stack2,
3 => &mut self.stack3,
4 => &mut self.stack4,
5 => &mut self.stack5,
6 => &mut self.stack6,
7 => &mut self.stack7,
8 => &mut self.stack8,
9 => &mut self.stack9,
_ => &mut self.stack1,
};
let c = from.pop().unwrap().to_owned();
drop(from);
let to = match turn.to {
1 => &mut self.stack1,
2 => &mut self.stack2,
3 => &mut self.stack3,
4 => &mut self.stack4,
5 => &mut self.stack5,
6 => &mut self.stack6,
7 => &mut self.stack7,
8 => &mut self.stack8,
9 => &mut self.stack9,
_ => &mut self.stack1,
};
to.push(c)
}
}
fn move_crain9001(&mut self, turn: &Turn) {
let mut mov: Vec<char> = vec![];
for _ in 0..turn.amount {
let from = match turn.from {
1 => &mut self.stack1,
2 => &mut self.stack2,
3 => &mut self.stack3,
4 => &mut self.stack4,
5 => &mut self.stack5,
6 => &mut self.stack6,
7 => &mut self.stack7,
8 => &mut self.stack8,
9 => &mut self.stack9,
_ => &mut self.stack1,
};
let c = from.pop().unwrap().to_owned();
drop(from);
mov.push(c)
}
let to = match turn.to {
1 => &mut self.stack1,
2 => &mut self.stack2,
3 => &mut self.stack3,
4 => &mut self.stack4,
5 => &mut self.stack5,
6 => &mut self.stack6,
7 => &mut self.stack7,
8 => &mut self.stack8,
9 => &mut self.stack9,
_ => &mut self.stack1,
};
for _ in 0..mov.len() {
to.push(mov.pop().unwrap())
}
}
}
#[derive(Debug)]
struct Turn {
amount: i32,
from: i32,
to: i32,
}
fn load_playground_data(content: &String) -> Playground {
let mut playground = Playground::new();
let cont = content.lines().take(8).collect::<Vec<&str>>();
cont.iter().rev().for_each(|s| {
s.chars().enumerate().for_each(|(i, c)| {
if c == ' ' {
return;
}
let c = c.clone();
match i {
1 => playground.stack1.push(c),
5 => playground.stack2.push(c),
9 => playground.stack3.push(c),
13 => playground.stack4.push(c),
17 => playground.stack5.push(c),
21 => playground.stack6.push(c),
25 => playground.stack7.push(c),
29 => playground.stack8.push(c),
33 => playground.stack9.push(c),
_ => (),
}
});
});
playground
}
fn load_play_data(content: &String) -> Vec<Turn> {
let mut turns: Vec<Turn> = Vec::new();
let binding = content
.lines()
.collect::<Vec<&str>>()
.splice(10.., [])
.collect::<Vec<&str>>();
binding.iter().for_each(|s| {
let t = s
.split(" ")
.filter(|c| c.parse::<i32>().is_ok())
.map(|d| d.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
turns.push(Turn {
amount: t[0],
from: t[1],
to: t[2],
})
});
turns
}
fn load_file() -> Result<String> {
let mut file = File::open("./data").expect("Data file not found");
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
fn run(part: i32) {
let content = load_file().unwrap();
let mut playground = load_playground_data(&content);
let turns = load_play_data(&content);
for turn in turns.iter() {
if part == 1 {
playground.move_crain9001(turn);
} else {
playground.move_crain(turn);
}
}
println!("Result of part {}:", part);
playground.print_result();
}
fn main() -> Result<()> {
run(1);
run(2);
Ok(())
}

58
2022/day5/task.txt Executable file
View file

@ -0,0 +1,58 @@
--- Day 5: Supply Stacks ---
The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.
The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.
The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.
They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P.
Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates:
[Z]
[N]
[C] [D]
[M] [P]
1 2 3
Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M:
[Z]
[N]
[M] [D]
[C] [P]
1 2 3
Finally, one crate is moved from stack 1 to stack 2:
[Z]
[N]
[D]
[C] [M] [P]
1 2 3
The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ.
After the rearrangement procedure completes, what crate ends up on top of each stack?
Answer Part1: WCZTHTMPS

1
2022/day6/.gitignore vendored Executable file
View file

@ -0,0 +1 @@
/target

7
2022/day6/Cargo.lock generated Executable file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day6"
version = "0.1.0"

8
2022/day6/Cargo.toml Executable file
View file

@ -0,0 +1,8 @@
[package]
name = "day6"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1
2022/day6/data Executable file
View file

@ -0,0 +1 @@
qvllndllhzhfzhhdzhddhjdjggvnvhvccmffwllqgqmmfjfqfhhtrrzczjczzlplddfpptqqfbqffmnmjnnqppfjfccgnnmqqsvvdbbgppjvpjvpjjctjjttwtrrdldlcddrvddqndqnqwqwzwfwwzczggcppgzpzhpzhppprfffbhhwmhhtftstrsrvsrvsrvvshvssnwwpllhfhnnfflcltlblzlqlvqlvlcldcccpptggtdgdjdbbrggmbmnncscbssqrrjddvcvgvfflpppgpvphvphhpcpzpzvvctvctvthtwtfwwbrrhhlplmlwwlqlnlhhtmhmmqlqplllrvrgvrvrffzfgfjfjtjmjvmjmwmvvjffmpfphfhvfvmfvmmhpphhltthgttgccqggpzpfpqpcpvcpvcvvqtqvqbbrlrtllmrmllhmhvmhhvzhvzvrrrzjzbbtvvbgvbbfnnqndqnnpnbnbnlnggwqggmgmqmgmbbmccgqcqbccpvcvnnhvvrvlrrcwrcwrcwrwbrwwzbwbdbfddpttntzzjszsnznbndnzngzgccjrcjchcffmlmqqlrqqzsqzzsbsnsttzpztpzpggzrrttbqqplpqlqjjqcqvccdzdccthccvfcvvqvhqhfhhzwzpzwppgpttntssflfjjrwrqrjrppptlltptpvttpfpwpswpppzzsrzssqllbnlljpllrjllsrlrhrdrmdrmrrpsrprnrffgrffdqdhdqhhrhggwqqlddsbsqbqtqdtdhdvhhbdhdzhdhhtrrppzddgfgzgpzpvpfpnpptggltggbnbppqffzfrzzzsbsrrdgrddwsdsqddhpdpbpvpfvppfsfgfngffzmzbzlblclsccvqvqmmjtjqtjjlcjllsddjqddhldlvlrrbgbrgbrrdzzpfpggqnqbqrrqbbgjgppqgpgwgqqndncndnpdnnbvbnvnwnjjgppzlplqqdgqghqgqzggjssqmmwwcfcpptrpprggrppgbplmzwmdtnpqwzcrthqbppwbgcvgqrpfpnbscnhvrllpvpqwnsslcjrqtvdccprvqfrpswtpvzdzlgtmmvppdmhgdbbsmrbqpqspdhpqgfjznqzphrnggcbzhdqrgvzcfzrhtrlssgmjjghqsjtghhnwjffqrrfslfnsvvdvfjqbfpffrrstdhggvbfwtfpfgswqlfdrnjpjmwzptlbmwgghgwqrphcrvfmhrplllgbnjlprllmjwccphsflntgpnbmdbfqcdsbgvrnfznfrlcfvswqfrqvdnbjsflnsmlcrdstzppmcvbgdtcvgztbdzqbwhmwcfvbwjjcdgbnwjwzrrdqhpgscwtnztjsfstzfwftcldjgvdvwbzrlbdslwttbqpnlwbjcjwqgtrgcglsgtdqbqbnqznptzzbwffwlwzvvtdpcjbvhnswzptclpbndcdvsfmcrmwwgzdfsszqjjdztmtsqgfqzjpctfdpwnzbpnzzwngqnghntblndfrnjzdrmgbqmzbdqfzctrgshwqgfgqssqjltrqlzjswjhmpgwwjdwcjpnsvgrvbfpmlmmwzmbdjwsrjthppfrccjgnmwlvqlprgslbwtbbzlqbznczmsmhsfdcqnwblprcpbzzwfllbnldvpjcwsdhglrzjsptmsjdjqzsmgvhjfjrrtvvbjlmzjsntnrggwbpjlrjggfgqzvswtggthzfmfjnmrzrttbzqpwpsnmdtnbfblpfgslgcmjlbdpshnnrbhvwsbrnvdmjqhvhdjhbfzjmqrmqmdthhzvnrmqcnbtwcdjdqfvdgvmfbhrfqnmdncrddggtcppjlznbsnntppjtnsqsrjwvfrzpnzqcrzhhdflfmmtmwcvtpzbqhdwsczffcqhtdbdjblmgnrmhlqcsvcpgghhvwqhdtzpzlpfllchzltqgcwgfqnbzhgzmdwqdlwnvhqmpqjqnjbhjctslghdqvctdmjfwdfpdjnhdndzwsfjzlmsbmfmzvnvpqgqhtngvgqmlrrzsfmwlcwsscvghjvrzjjqbnplnjzqswpblwzwczhwbhhnjmctnmwlbqqfmnlwdcrptlmfjpjrnpcvmhffjhwhmntdzpdjzwzhrrsdvmjlwdtcpvjfmfzfsrgjghhlvmjjjczgmhvrfpgqbnhldwbrjgzmnszzbssfzcggrwmdfvddwsdmnwtwfwlfnwlvzlctfblbtrjvcwjjdljplcrjhwqslppwwtvfqwsjlfmdznmcdzdmgvmmsrfcclcvhtrhlsjzrbjwrjlfnvqhqvmpzmdttnbhfcvnqlrqbcsvtvwfccjstjpmhqgwlnrzjjmfdszflmglrdbpqhqhqsdfzrcljbdvvnlcqfllmnqcjfzjppdsjwshfschzqbnwfqnpwhqnmwsjbtcgvrljsrtzvcvghcjjlqsngglcggqpntrrhbjpbfhmvpltmnfmfdtwnczwfbvjcqnhvppjftwvwsrlhvvcjtsfptpqgrmrqwwddnqmnmfgrlnphbpqhhhvglqgtwvnwvnbssftmwttmfrffwtzhrpqspclvgchwqwcsgwqwwvpgcwngrcfmhbhflwfbfchlphdzdcrflfmfclsngtlwrqcrsgrdzcpdsvvcdbhgtljmbntbbcqgjqfsbfwzlfsnljpjdcnmjlqrwpmlvwgdlrrdgfhdqhzgltmclzgzzhmrbggsmgtpqdrgmjtlzwstrwbpvhppvsmdqvvwwglzjgdswjszqmrdbmshbhhcstpcsjdbvgjnvcmvhbtclrlmlgnvppgvncsrfchdbqjrclwwlnchmcgvshfsbsvvcvjrsgjlnsfqtqmgntffwnqjtldcqbcqhsgztllstswwqnfrswpchqhnfzzzszqjztzfrgrbjdbjlpvqfqrlrmmpbfbbcclrgmnlzwqrjhqrstswjpgsrtnlwsbqthzpvdzllzqmdmbvvtcztftvlwphhjzbfnrvccfmhmvmzlbrzlnppfzcsffjvjmbgpvlwgwszpztjpsrbnftqtdrbnljtbrjzzbwlsvtwtlwptdtnmtncvcblcmdngjzmctlqtzchncccnwjzrrmmmnllbhrnhwtqjsnvcslrqjfbfndqvdlrjshdzmlprtzbtnhthdqhplwzdbnjmgzlzrbzrvrqnflwfmsmbssqnbcddnvdpltpmplpdzvtjrslcdcnrdplwtjtvctwfzhlvwwqqtbqcjjwhhnpmvgzhqmqfgthwbphrmrtdghchsmwghdqjgjgmpddbrtngtvhqgjfrplrdgpbnhqvswrmqhcmsqvsqmqsgwjndwjrbrhvrctmmrmfwpsgfgdlrzpslpflgvwrgcthgcrnhgrzsmqdgdssjgspfhmqfmjfpmwqhnfjdvqzhpndvnbmqglbrjmdrwgmgctrgzpsdvfbmcstcslblmvnprphntgslmlrqwthrndrhtbccgzzfsglhgqztcsnqjwfzbzlvrpbvswbhrwdsrhrrpnrmsbvbvjccbdsdcfrrzpgwjtnnnvjwlcppwzdqsbdzpfjplrlfgvjpsmbzwpwlghnvqgddfjvrsztrpzlfgmqqzrfcgglghndbhgbmldglclhldljjdslvhzshshtqwhqnbzhvqrcmwdmcmhjcrmdmhrwnwcbhvbbrwrbtfdnztwnbpdfjfhgrmcpngftsvbsmsptnwcvvllnmbnsntbzmwnhfdptbtzswtjzdqwjdhprnjwvhzpscjvlsgrhdrmmrmhzhwwtslzdjqmzfncnmgplhnmwrvqhslvchtjcmpzpjpnpfbjptvvwcsmhgdjtsqrjlfpnfdncpqqmpgpvtlvwljlsqbnhtsqgfwlsmdjpgtvgjvjcrnnzmbllqzlrfdnlffgmtphhhgbcjgdlpzqpwmjwtcmdrsmtnmddftwczbsddtppsptbwfvpnfnsqmsgcfqfmnzffzqgcdvwzrgdwhmnzmrlhcdpdsltnsmjzdqwmmpwvjqbbwsrfgzh

113
2022/day6/src/main.rs Executable file
View file

@ -0,0 +1,113 @@
use std::{
fs::File,
io::{Read, Result},
ops::Deref,
};
fn load_data() -> Result<String> {
let mut file = File::open("./data").expect("Data file not found");
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
fn count_chars_to_firt_sop_marker(data: &str) -> usize {
let arr: Vec<_> = data.chars().collect();
for i in 3..arr.len() {
let mut char: [char; 4] = ['a'; 4];
char.clone_from_slice(&arr[i - 3..=i]);
let mut char: Vec<char> = char.into();
char.sort();
char.dedup();
println!("{:?}", char);
if char.len() == 4 {
return i + 1;
}
}
10
}
fn count_chars_to_firt_som_marker(data: &str) -> usize {
let arr: Vec<_> = data.chars().collect();
for i in 13..arr.len() {
let mut char: [char; 14] = ['a'; 14];
char.clone_from_slice(&arr[i - 13..=i]);
let mut char: Vec<char> = char.into();
char.sort();
char.dedup();
println!("{:?}", char);
if char.len() == 14 {
return i + 1;
}
}
10
}
fn main() {
let data = load_data().unwrap();
let packet_point = count_chars_to_firt_sop_marker(&data);
let message_point = count_chars_to_firt_som_marker(&data);
println!("start of packet: {}", packet_point);
println!("start of message: {}", message_point)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sop1() {
let data = String::from("bvwbjplbgvbhsrlpgdmjqwftvncz");
let point = count_chars_to_firt_sop_marker(&data);
assert_eq!(point, 5);
}
#[test]
fn sop2() {
let data = String::from("nppdvjthqldpwncqszvftbrmjlhg");
let point = count_chars_to_firt_sop_marker(&data);
assert_eq!(point, 6);
}
#[test]
fn sop3() {
let data = String::from("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg");
let point = count_chars_to_firt_sop_marker(&data);
assert_eq!(point, 10);
}
#[test]
fn sop4() {
let data = String::from("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw");
let point = count_chars_to_firt_sop_marker(&data);
assert_eq!(point, 11);
}
#[test]
fn som1() {
let data = String::from("mjqjpqmgbljsphdztnvjfqwrcgsmlb");
let point = count_chars_to_firt_som_marker(&data);
assert_eq!(point, 19);
}
#[test]
fn som2() {
let data = String::from("bvwbjplbgvbhsrlpgdmjqwftvncz");
let point = count_chars_to_firt_som_marker(&data);
assert_eq!(point, 23);
}
#[test]
fn som3() {
let data = String::from("nppdvjthqldpwncqszvftbrmjlhg");
let point = count_chars_to_firt_som_marker(&data);
assert_eq!(point, 23);
}
#[test]
fn som4() {
let data = String::from("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg");
let point = count_chars_to_firt_som_marker(&data);
assert_eq!(point, 29);
}
#[test]
fn som5() {
let data = String::from("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw");
let point = count_chars_to_firt_som_marker(&data);
assert_eq!(point, 26);
}
}

34
2022/day6/task.txt Executable file
View file

@ -0,0 +1,34 @@
--- Day 6: Tuning Trouble ---
The preparations are finally complete; you and the Elves leave camp on foot and begin to make your way toward the star fruit grove.
As you move through the dense undergrowth, one of the Elves gives you a handheld device. He says that it has many fancy features, but the most important one to set up right now is the communication system.
However, because he's heard you have significant experience dealing with signal-based systems, he convinced the other Elves that it would be okay to give you their one malfunctioning device - surely you'll have no problem fixing it.
As if inspired by comedic timing, the device emits a few colorful sparks.
To be able to communicate with the Elves, the device needs to lock on to their signal. The signal is a series of seemingly-random characters that the device receives one at a time.
To fix the communication system, you need to add a subroutine to the device that detects a start-of-packet marker in the datastream. In the protocol being used by the Elves, the start of a packet is indicated by a sequence of four characters that are all different.
The device will send your subroutine a datastream buffer (your puzzle input); your subroutine needs to identify the first position where the four most recently received characters were all different. Specifically, it needs to report the number of characters from the beginning of the buffer to the end of the first such four-character marker.
For example, suppose you receive the following datastream buffer:
mjqjpqmgbljsphdztnvjfqwrcgsmlb
After the first three characters (mjq) have been received, there haven't been enough characters received yet to find the marker. The first time a marker could occur is after the fourth character is received, making the most recent four characters mjqj. Because j is repeated, this isn't a marker.
The first time a marker appears is after the seventh character arrives. Once it does, the last four characters received are jpqm, which are all different. In this case, your subroutine should report the value 7, because the first start-of-packet marker is complete after 7 characters have been processed.
Here are a few more examples:
bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 5
nppdvjthqldpwncqszvftbrmjlhg: first marker after character 6
nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 10
zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 11
How many characters need to be processed before the first start-of-packet marker is detected?
answer part1 :

589
2022/day7/Cargo.lock generated Executable file
View file

@ -0,0 +1,589 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "ahash"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"
dependencies = [
"getrandom",
"once_cell",
"version_check",
]
[[package]]
name = "aho-corasick"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b13c32d80ecc7ab747b80c3784bce54ee8a7a0cc4fbda9bf4cda2cf6fe90854"
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "base64"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
[[package]]
name = "bincode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
dependencies = [
"serde",
]
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cc"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crc32fast"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [
"cfg-if",
]
[[package]]
name = "day7"
version = "0.1.0"
dependencies = [
"anyhow",
"dbg-pls",
"nom",
"transiter",
]
[[package]]
name = "dbg-pls"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90db85e18e7fad119e7fc1d3252b49e81910b00751f4e63934571b4f7994082b"
dependencies = [
"dbg-pls-derive",
"itoa",
"once_cell",
"prettyplease",
"proc-macro2",
"quote",
"ryu",
"syn",
"syntect",
"textwrap",
]
[[package]]
name = "dbg-pls-derive"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adfbcca6067d039b0079333826bfa6574a98ea6a068440c51cec69b99b03b4bf"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "flate2"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash",
]
[[package]]
name = "indexmap"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "line-wrap"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f30344350a2a51da54c1d53be93fade8a237e545dbcc4bdbe635413f2117cab9"
dependencies = [
"safemem",
]
[[package]]
name = "linked-hash-map"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
[[package]]
name = "memchr"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7"
dependencies = [
"adler",
]
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "once_cell"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "onig"
version = "6.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c4b31c8722ad9171c6d77d3557db078cab2bd50afcc9d09c8b315c59df8ca4f"
dependencies = [
"bitflags",
"libc",
"once_cell",
"onig_sys",
]
[[package]]
name = "onig_sys"
version = "69.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b829e3d7e9cc74c7e315ee8edb185bf4190da5acde74afd7fc59c35b1f086e7"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "pkg-config"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964"
[[package]]
name = "plist"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdc0001cfea3db57a2e24bc0d818e9e20e554b5f97fabb9bc231dc240269ae06"
dependencies = [
"base64",
"indexmap",
"line-wrap",
"quick-xml",
"serde",
"time",
]
[[package]]
name = "prettyplease"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92139198957b410250d43fad93e630d956499a625c527eda65175c8680f83387"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quick-xml"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81b9228215d82c7b61490fec1de287136b5de6f5700f6e58ea9ad61a7964ca51"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fe8a65d69dd0808184ebb5f836ab526bb259db23c657efa38711b1072ee47f0"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2eae68fc220f7cf2532e4494aded17545fce192d59cd996e0fe7887f4ceb575"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax 0.7.4",
]
[[package]]
name = "regex-automata"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39354c10dd07468c2e73926b23bb9c2caca74c5501e38a35da70406f1d923310"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax 0.7.4",
]
[[package]]
name = "regex-syntax"
version = "0.6.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
[[package]]
name = "regex-syntax"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2"
[[package]]
name = "ryu"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
[[package]]
name = "safemem"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.171"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30e27d1e4fd7659406c492fd6cfaf2066ba8773de45ca75e855590f856dc34a9"
[[package]]
name = "serde_derive"
version = "1.0.171"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389894603bd18c46fa56231694f8d827779c0951a667087194cf9de94ed24682"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d03b412469450d4404fe8499a268edd7f8b79fecb074b0d812ad64ca21f4031b"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "smawk"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043"
[[package]]
name = "syn"
version = "2.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45c3457aacde3c65315de5031ec191ce46604304d2446e803d71ade03308d970"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syntect"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6c454c27d9d7d9a84c7803aaa3c50cd088d2906fe3c6e42da3209aa623576a8"
dependencies = [
"bincode",
"bitflags",
"flate2",
"fnv",
"lazy_static",
"once_cell",
"onig",
"plist",
"regex-syntax 0.6.29",
"serde",
"serde_derive",
"serde_json",
"thiserror",
"walkdir",
"yaml-rust",
]
[[package]]
name = "textwrap"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
dependencies = [
"smawk",
"unicode-linebreak",
"unicode-width",
]
[[package]]
name = "thiserror"
version = "1.0.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a35fc5b8971143ca348fa6df4f024d4d55264f3468c71ad1c2f365b0a4d58c42"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "463fe12d7993d3b327787537ce8dd4dfa058de32fc2b195ef3cde03dc4771e8f"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "time"
version = "0.3.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59e399c068f43a5d116fedaf73b203fa4f9c519f17e2b34f63221d3792f81446"
dependencies = [
"itoa",
"serde",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb"
[[package]]
name = "time-macros"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96ba15a897f3c86766b757e5ac7221554c6750054d74d5b28844fce5fb36a6c4"
dependencies = [
"time-core",
]
[[package]]
name = "transiter"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45d99e91bfdf55d8a22dda2f226997e6b280592f0cf6a633e8e0f57c666f04b4"
[[package]]
name = "unicode-ident"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
[[package]]
name = "unicode-linebreak"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5faade31a542b8b35855fff6e8def199853b2da8da256da52f52f1316ee3137"
dependencies = [
"hashbrown",
"regex",
]
[[package]]
name = "unicode-width"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "walkdir"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]

12
2022/day7/Cargo.toml Executable file
View file

@ -0,0 +1,12 @@
[package]
name = "day7"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.69"
dbg-pls = { version = "0.4.1", features = ["colors", "derive"] }
nom = "7.1.3"
transiter = "0.2.0"

979
2022/day7/data Executable file
View file

@ -0,0 +1,979 @@
$ cd /
$ ls
dir plws
dir pwlbgbz
dir pwtpltr
dir szn
$ cd plws
$ ls
dir ffpzc
dir frcmjzts
92461 nbvnzg
dir phqcg
21621 vqgsglwq
$ cd ffpzc
$ ls
48459 dzdfc.vqq
143107 jql.jzl
208330 mmnvqn.hqb
290122 svjvhflz
218008 wjlmgq
$ cd ..
$ cd frcmjzts
$ ls
dir bsltmjz
dir jfzgrbm
$ cd bsltmjz
$ ls
34237 dzdfc.vqq
58741 mdgdhqgw
$ cd ..
$ cd jfzgrbm
$ ls
132811 fcmpng
103661 lgt.swt
173031 vqgsglwq
29134 wprjfg.zbr
$ cd ..
$ cd ..
$ cd phqcg
$ ls
955 jgfs.zjw
$ cd ..
$ cd ..
$ cd pwlbgbz
$ ls
dir gbg
dir mjzhcwrd
dir njcscpj
dir sphbzn
dir tbgjpphc
55938 tvrfpczc.djm
4840 twd
$ cd gbg
$ ls
287003 fcsjl.bzm
dir wgq
$ cd wgq
$ ls
22963 fcsjl.fcm
$ cd ..
$ cd ..
$ cd mjzhcwrd
$ ls
228632 clfnpmbq.zmb
28276 dzdfc.vqq
2982 tdbg.wgn
$ cd ..
$ cd njcscpj
$ ls
dir dqzgqgv
275186 ffpzc
192491 gjnflc.plq
$ cd dqzgqgv
$ ls
70309 dzdfc.vqq
56139 fcsjl
142095 sgwz.cdz
dir snjntth
dir sphbzn
284618 wjlmgq
$ cd snjntth
$ ls
51918 ffpzc
dir vrfgfds
$ cd vrfgfds
$ ls
155233 jlscz
$ cd ..
$ cd ..
$ cd sphbzn
$ ls
dir qbzwrrw
dir qwpzn
$ cd qbzwrrw
$ ls
278531 fcsjl.tqj
211591 snjntth.gpd
$ cd ..
$ cd qwpzn
$ ls
174183 vqgsglwq
$ cd ..
$ cd ..
$ cd ..
$ cd ..
$ cd sphbzn
$ ls
185471 bsltmjz.fqz
dir bsvh
dir fvzcs
dir ndw
dir nlml
dir pcbt
286260 zhcmrpvt
$ cd bsvh
$ ls
130814 wjlmgq
$ cd ..
$ cd fvzcs
$ ls
dir cgmv
dir ggzwljr
298241 qvzghdpw.lms
dir snjntth
dir sphbzn
$ cd cgmv
$ ls
46843 dzdfc.vqq
dir lmqcbbm
dir rstcqsmd
215261 snjntth
$ cd lmqcbbm
$ ls
229898 bdmbvgp
25529 ffpzc.stm
16871 lnpjzvg.qlj
$ cd ..
$ cd rstcqsmd
$ ls
289038 zrbbbwng.smf
$ cd ..
$ cd ..
$ cd ggzwljr
$ ls
198200 bcthn
$ cd ..
$ cd snjntth
$ ls
191672 fwp.phf
68229 hzs.zpg
dir pggcwb
222426 qbv.bwj
dir snjntth
155354 vmqcm
$ cd pggcwb
$ ls
154272 fqztwvnv.lvv
dir pdjg
62393 vqgsglwq
dir wjhrtg
$ cd pdjg
$ ls
260644 gvhlrcf
209906 wpls.pbd
$ cd ..
$ cd wjhrtg
$ ls
148640 dljf.zrq
172168 dzdfc.vqq
196203 hjdphcfm
247620 sgwz.cdz
$ cd ..
$ cd ..
$ cd snjntth
$ ls
37467 ndlshlmj.cjq
257404 snjntth.nsf
$ cd ..
$ cd ..
$ cd sphbzn
$ ls
64082 bfdv.lwv
dir bsltmjz
58942 dzdfc.vqq
dir snjntth
$ cd bsltmjz
$ ls
dir bsqqdr
266007 fcsjl.gfm
dir ffpzc
dir frsmrd
72122 nthnhzwf
286705 wjlmgq
$ cd bsqqdr
$ ls
117496 wcqt
$ cd ..
$ cd ffpzc
$ ls
280224 mmnvqn.hqb
105346 vrr
$ cd ..
$ cd frsmrd
$ ls
111509 sphbzn.shz
$ cd ..
$ cd ..
$ cd snjntth
$ ls
177491 mplj
9029 pvbz.jwn
92891 snjntth.zrv
203356 vnnnw.gql
134728 vqgsglwq
$ cd ..
$ cd ..
$ cd ..
$ cd ndw
$ ls
241303 bht.rpj
173068 vqgsglwq
$ cd ..
$ cd nlml
$ ls
228982 hzglfpvq.ftt
114981 sgwz.cdz
$ cd ..
$ cd pcbt
$ ls
dir bsltmjz
dir ffpzc
dir fjsjwfg
dir fwm
dir jvwt
227943 tmr.jdc
dir vwpqzdwh
31258 wjlmgq
$ cd bsltmjz
$ ls
177750 bsltmjz.spj
dir ffpzc
dir flrpwfs
138824 mtmdtcpv.cfj
165770 wzqwczj.qwn
$ cd ffpzc
$ ls
179645 snjntth.dss
$ cd ..
$ cd flrpwfs
$ ls
60566 wvjq.gmm
$ cd ..
$ cd ..
$ cd ffpzc
$ ls
97847 qzhhtmd.bhw
1197 vqgsglwq
$ cd ..
$ cd fjsjwfg
$ ls
152232 dnsdd.jgz
181301 gsb.wsh
dir jqpb
dir jscbg
dir snjntth
227677 snjntth.vvg
dir sphbzn
75358 vqgsglwq
2589 wjlmgq
$ cd jqpb
$ ls
253403 mmnvqn.hqb
108325 rvq.mrc
$ cd ..
$ cd jscbg
$ ls
dir dtm
dir gsdnz
208269 prh
25977 qdzljgh
169262 vmnq.mth
$ cd dtm
$ ls
80072 gzqnb
$ cd ..
$ cd gsdnz
$ ls
dir dsqzjs
297895 sgwz.cdz
129983 vqgsglwq
$ cd dsqzjs
$ ls
2621 jqrlsf.gzs
164844 snjntth
$ cd ..
$ cd ..
$ cd ..
$ cd snjntth
$ ls
118553 cbhql
dir ffpzc
dir snjntth
$ cd ffpzc
$ ls
dir lmn
12104 tvlwn.vhh
$ cd lmn
$ ls
46401 bsltmjz
96888 shrnqhvq
$ cd ..
$ cd ..
$ cd snjntth
$ ls
dir snjntth
dir vlnfhbq
dir wpwl
$ cd snjntth
$ ls
dir ctj
$ cd ctj
$ ls
82485 fcsjl.lfl
$ cd ..
$ cd ..
$ cd vlnfhbq
$ ls
250106 qvf
$ cd ..
$ cd wpwl
$ ls
153950 cmsd.rlg
$ cd ..
$ cd ..
$ cd ..
$ cd sphbzn
$ ls
dir glgq
$ cd glgq
$ ls
285182 wjlmgq
$ cd ..
$ cd ..
$ cd ..
$ cd fwm
$ ls
251865 ffpzc.qgb
279522 zvvpfqtp
$ cd ..
$ cd jvwt
$ ls
48990 bsltmjz.nzp
219604 ffpzc
69573 mvmdfzr.lwb
$ cd ..
$ cd vwpqzdwh
$ ls
267581 pvcch
$ cd ..
$ cd ..
$ cd ..
$ cd tbgjpphc
$ ls
255571 dstpcgr.tfq
dir fdbwbrpp
dir gjzwh
dir hjvrtjt
dir rhzczj
292888 sgwz.cdz
dir wlzhr
149395 wnfzrqgz.dtn
$ cd fdbwbrpp
$ ls
dir ffpzc
dir qbrth
51164 qprp
dir slpt
117026 sphbzn
295685 vqgsglwq
dir znmj
$ cd ffpzc
$ ls
dir jhnzrdvb
$ cd jhnzrdvb
$ ls
217775 ffpzc.sgw
$ cd ..
$ cd ..
$ cd qbrth
$ ls
183969 lpbwgfjv.vcg
47333 wjlmgq
$ cd ..
$ cd slpt
$ ls
32343 tqhtj.jwz
$ cd ..
$ cd znmj
$ ls
55058 mmnvqn.hqb
$ cd ..
$ cd ..
$ cd gjzwh
$ ls
dir dvcbcd
202530 dzdfc.vqq
dir fsgz
dir hfrrqq
54897 jlzn.qsn
16097 ldzqsbb.jzl
225078 pswccrd
dir rqqmldw
292464 rzrdhbp.vld
dir ssqbqqp
dir zsztqrc
$ cd dvcbcd
$ ls
187837 dzdfc.vqq
dir jlwtvf
dir jnjvshs
164053 nrf.fqd
5665 tlp.jmt
13801 wjlmgq
$ cd jlwtvf
$ ls
219985 sphbzn.dvj
$ cd ..
$ cd jnjvshs
$ ls
dir bsltmjz
dir nrpm
$ cd bsltmjz
$ ls
152972 qgdqj
$ cd ..
$ cd nrpm
$ ls
18509 wjlmgq
$ cd ..
$ cd ..
$ cd ..
$ cd fsgz
$ ls
224576 mmnvqn.hqb
$ cd ..
$ cd hfrrqq
$ ls
dir bwgsnfvb
dir fcsjl
294608 ffpzc.gvm
136880 qjcgtw
dir sphbzn
$ cd bwgsnfvb
$ ls
29735 dzdfc.vqq
dir wstmzfml
$ cd wstmzfml
$ ls
158447 bnvhbvvc.nrt
59889 jclclgd
$ cd ..
$ cd ..
$ cd fcsjl
$ ls
138297 ffpzc.szw
$ cd ..
$ cd sphbzn
$ ls
dir wqdths
$ cd wqdths
$ ls
8326 cgvtw.jpz
$ cd ..
$ cd ..
$ cd ..
$ cd rqqmldw
$ ls
226757 dzdfc.vqq
115055 mwb.btc
dir qpts
298524 sgwz.cdz
$ cd qpts
$ ls
60860 bsltmjz.frp
dir fcsjl
94904 sgwz.cdz
dir wnmqqspz
$ cd fcsjl
$ ls
25082 mmnvqn.hqb
$ cd ..
$ cd wnmqqspz
$ ls
165529 sgwz.cdz
$ cd ..
$ cd ..
$ cd ..
$ cd ssqbqqp
$ ls
192477 pvrgm
$ cd ..
$ cd zsztqrc
$ ls
254053 lht.htn
$ cd ..
$ cd ..
$ cd hjvrtjt
$ ls
189942 fwps
$ cd ..
$ cd rhzczj
$ ls
36502 bmtfr
dir ffjz
35148 nctfhmzm.vsz
dir qdgjzcz
208196 rwql
79863 sgwz.cdz
dir snjntth
$ cd ffjz
$ ls
dir grsvhwm
$ cd grsvhwm
$ ls
50231 fwj.rdv
dir snjntth
$ cd snjntth
$ ls
dir dtbgb
$ cd dtbgb
$ ls
150245 vdflm.lmq
$ cd ..
$ cd ..
$ cd ..
$ cd ..
$ cd qdgjzcz
$ ls
222389 dzdfc.vqq
$ cd ..
$ cd snjntth
$ ls
56794 mmnvqn.hqb
$ cd ..
$ cd ..
$ cd wlzhr
$ ls
116628 bsltmjz
60122 jqpbsgnr.fgb
252605 lfss
300065 qwjdl.vhr
$ cd ..
$ cd ..
$ cd ..
$ cd pwtpltr
$ ls
dir dplsvrhl
140951 gwtfzqvd.znb
dir jbvdb
dir jst
dir qhjv
dir snjntth
$ cd dplsvrhl
$ ls
272101 fcsjl
dir ffpzc
58852 mmnvqn.hqb
dir mnhntjz
91899 sgwz.cdz
228077 snjntth.btv
$ cd ffpzc
$ ls
5499 bsltmjz
dir qmfwpjhl
dir rsrb
dir wgt
$ cd qmfwpjhl
$ ls
300362 dzdfc.vqq
$ cd ..
$ cd rsrb
$ ls
252983 dzdfc.vqq
107744 ltssrgqb.zvj
214895 rhglgcwr.wpw
249727 sgwz.cdz
$ cd ..
$ cd wgt
$ ls
141984 dzdfc.vqq
194686 mmnvqn.hqb
258023 pgr
$ cd ..
$ cd ..
$ cd mnhntjz
$ ls
dir bdvght
dir jprwchh
dir snjntth
$ cd bdvght
$ ls
243166 vpsvjdq.wsn
$ cd ..
$ cd jprwchh
$ ls
178943 bmpc.bjb
$ cd ..
$ cd snjntth
$ ls
dir nlbm
dir zjmjntff
$ cd nlbm
$ ls
33050 fcsjl.rcc
dir sphbzn
17446 wjlmgq
$ cd sphbzn
$ ls
214563 prrfhff.pbp
$ cd ..
$ cd ..
$ cd zjmjntff
$ ls
82134 sgwz.cdz
52203 vrtlgdq.crp
$ cd ..
$ cd ..
$ cd ..
$ cd ..
$ cd jbvdb
$ ls
dir wmtjh
$ cd wmtjh
$ ls
dir ggvwn
$ cd ggvwn
$ ls
192285 spqvmf.sdh
$ cd ..
$ cd ..
$ cd ..
$ cd jst
$ ls
dir bsltmjz
212740 dzdfc.vqq
dir gncztvtb
dir jsqjcqnt
286257 jvs
36654 sdcsm.mbg
192040 sgwz.cdz
dir tbqphzb
dir vdcqgts
285843 wjlmgq
$ cd bsltmjz
$ ls
215705 snjntth.gpv
213665 wjlmgq
$ cd ..
$ cd gncztvtb
$ ls
229298 vqgsglwq
$ cd ..
$ cd jsqjcqnt
$ ls
dir bsltmjz
dir fcsjl
dir ffpzc
dir sphbzn
70864 vqgsglwq
$ cd bsltmjz
$ ls
14981 pqzffzjc
$ cd ..
$ cd fcsjl
$ ls
140328 jwhczwbc
$ cd ..
$ cd ffpzc
$ ls
213650 mmnvqn.hqb
$ cd ..
$ cd sphbzn
$ ls
dir psmtphhq
dir sphbzn
$ cd psmtphhq
$ ls
dir ffpzc
123131 tzgwd
$ cd ffpzc
$ ls
49737 cfngvmd
dir gcnrp
172799 gmd.cwl
dir llnztjf
dir nbqs
79661 rrqz
$ cd gcnrp
$ ls
283 vqnrgl.vwp
$ cd ..
$ cd llnztjf
$ ls
63263 tjhm.bwh
$ cd ..
$ cd nbqs
$ ls
dir vssmq
$ cd vssmq
$ ls
88980 dzdfc.vqq
$ cd ..
$ cd ..
$ cd ..
$ cd ..
$ cd sphbzn
$ ls
20140 fcsjl.zrs
260579 snjntth
$ cd ..
$ cd ..
$ cd ..
$ cd tbqphzb
$ ls
93470 sgwz.cdz
$ cd ..
$ cd vdcqgts
$ ls
223564 dzdfc.vqq
dir ffpzc
dir gwhfgwf
dir nbjtqnng
dir snjntth
$ cd ffpzc
$ ls
42813 qwwmw.nmt
$ cd ..
$ cd gwhfgwf
$ ls
59918 jvfv.mpm
dir mjl
211039 pcwl
$ cd mjl
$ ls
13004 pgjb.tpq
195995 tms.fjz
$ cd ..
$ cd ..
$ cd nbjtqnng
$ ls
107058 dzdfc.vqq
dir ldrsd
111631 vqgsglwq
104599 wbzmdljw.tjq
155747 wjlmgq
$ cd ldrsd
$ ls
107439 jvjm
$ cd ..
$ cd ..
$ cd snjntth
$ ls
242680 fgrt.gng
$ cd ..
$ cd ..
$ cd ..
$ cd qhjv
$ ls
dir bmnm
68453 hjjpdgn.hwl
dir sjlbj
dir vqnrj
$ cd bmnm
$ ls
1238 vqgsglwq
$ cd ..
$ cd sjlbj
$ ls
44239 wzzbtmrz.gml
$ cd ..
$ cd vqnrj
$ ls
3286 bsltmjz.qlc
$ cd ..
$ cd ..
$ cd snjntth
$ ls
130833 blm.wmt
dir snjntth
dir tcnmbcgg
218869 wjlmgq
$ cd snjntth
$ ls
dir snmrdfbt
$ cd snmrdfbt
$ ls
281025 bzrsds.lfg
$ cd ..
$ cd ..
$ cd tcnmbcgg
$ ls
194998 fcsjl
dir qdrmpqgn
dir rzqd
dir tcsds
$ cd qdrmpqgn
$ ls
165713 qmzgt.tnc
$ cd ..
$ cd rzqd
$ ls
dir cwhnmlv
57819 fcsjl
246864 pjnzdvd.gjm
$ cd cwhnmlv
$ ls
287539 mmnvqn.hqb
215636 pbnjt.zbn
124638 sqd
$ cd ..
$ cd ..
$ cd tcsds
$ ls
78812 gfmgb.wqj
218987 hnhfvz.dln
209640 mzzhqlq.zqp
102492 nml.ppg
$ cd ..
$ cd ..
$ cd ..
$ cd ..
$ cd szn
$ ls
dir fcsjl
dir snjntth
dir zjbp
$ cd fcsjl
$ ls
158019 jsv.pmz
$ cd ..
$ cd snjntth
$ ls
229510 dfvpvp
191061 fgplbptq.jlt
dir lfb
234911 lfsrwr.wcb
dir lrfcgzl
48031 stbbw
219691 vqgsglwq
dir zshh
$ cd lfb
$ ls
dir btj
99591 dhrjbvvg.gwm
137224 dzdfc.vqq
201972 jtzmqsvj.wnd
9704 mmnvqn.hqb
dir pwg
200308 snjntth.css
dir wcmhcfm
dir zwhvmln
$ cd btj
$ ls
dir rnbzdfgn
51799 wdhsm
dir wvf
$ cd rnbzdfgn
$ ls
117095 bsltmjz.tlv
$ cd ..
$ cd wvf
$ ls
dir ffpzc
dir ncbmgpsc
dir wtwrmjnt
$ cd ffpzc
$ ls
249919 lsth.fmf
$ cd ..
$ cd ncbmgpsc
$ ls
147899 dzdfc.vqq
$ cd ..
$ cd wtwrmjnt
$ ls
252366 pvpdv.jwz
$ cd ..
$ cd ..
$ cd ..
$ cd pwg
$ ls
280845 fcsjl.fjz
44300 sgwz.cdz
dir snjntth
229605 vqgsglwq
$ cd snjntth
$ ls
2053 pflvsnzs
143522 sgwz.cdz
$ cd ..
$ cd ..
$ cd wcmhcfm
$ ls
229329 qsznhwlw.vjg
$ cd ..
$ cd zwhvmln
$ ls
dir ffpzc
dir tjjzbf
dir wzcq
$ cd ffpzc
$ ls
dir ncnj
37497 vqgsglwq
$ cd ncnj
$ ls
40920 htbjhjq
$ cd ..
$ cd ..
$ cd tjjzbf
$ ls
47522 mczn.spd
$ cd ..
$ cd wzcq
$ ls
56662 ffpzc.vwp
dir snjntth
$ cd snjntth
$ ls
117276 wjlmgq
$ cd ..
$ cd ..
$ cd ..
$ cd ..
$ cd lrfcgzl
$ ls
267485 rsjmpph.qqz
$ cd ..
$ cd zshh
$ ls
dir ffpzc
dir gmn
dir snjntth
150048 tgtlh
32020 thfr
72152 vqgsglwq
$ cd ffpzc
$ ls
dir snjntth
$ cd snjntth
$ ls
224945 dpfpz
$ cd ..
$ cd ..
$ cd gmn
$ ls
238996 sgwz.cdz
$ cd ..
$ cd snjntth
$ ls
86775 dzdfc.vqq
19560 vshcmjj
$ cd ..
$ cd ..
$ cd ..
$ cd zjbp
$ ls
dir fcsjl
41522 nlvpb.fpf
dir nmtjtd
$ cd fcsjl
$ ls
276802 fcsjl.psm
197934 sgwz.cdz
$ cd ..
$ cd nmtjtd
$ ls
47477 dvqmqlgw.ths
51081 vqgsglwq

382
2022/day7/src/main.rs Executable file
View file

@ -0,0 +1,382 @@
#![allow(unused_imports)]
use std::{
borrow::BorrowMut,
env::current_dir,
fmt::{format, Display},
fs,
iter::empty,
ops::DerefMut,
};
use transiter::{IntoTransIter, TransIter};
use dbg_pls::{color, DebugPls};
use nom::{
branch::alt,
bytes::complete::{tag, take_till1, take_until1, take_while1},
character::{
complete::{digit1, newline, not_line_ending},
is_alphabetic,
},
combinator::{map_res, opt},
multi::many0,
AsChar, IResult,
};
mod utils;
// PUZZLE: https://web.archive.org/web/20230223113025/https://adventofcode.com/2022/day/7
#[derive(Debug, DebugPls)]
enum File {
Plain { name: String, size: usize },
Dir { name: String, children: Vec<File> },
}
#[derive(Debug, DebugPls)]
#[allow(non_camel_case_types)]
enum Command {
cd { target: String },
ls { files: Vec<File> },
}
pub fn main() {
println!("Hello, AdventOfCode - day 7!");
let content = fs::read_to_string("./data").expect("Read ./input");
println!("PART 1 - RESULT: {}", process_part1(content.clone()));
println!();
println!("PART 2 - RESULT: {}", process_part2(content));
}
fn process_part1(content: String) -> String {
let root = parse_session(content.as_str());
let dirs = root.dirs_recursive();
println!("Dirs: {}", color(&dirs.iter().map(|f| f.name()).collect::<Vec<String>>()));
let dirs_under_size_limit = dirs
.iter()
.filter(|dir| dir.total_size() <= 100000)
.collect::<Vec<_>>();
println!("Dirs under size limit: {}", color(&dirs_under_size_limit));
let total_size = dirs_under_size_limit.iter().map(|f| f.total_size()).sum::<usize>();
total_size.to_string()
}
fn process_part2(content: String) -> String {
let root = parse_session(content.as_str());
let used = root.total_size();
let capacity = 70000000;
let available = capacity - used;
println!("Total size: {} ({} available)", used, available);
let required = 30000000;
let to_be_freed = required - available;
println!("Must be freed: {}", to_be_freed);
let dirs = root.dirs_recursive();
let mut big_enough = dirs
.iter()
.filter(|dir| dir.total_size() >= to_be_freed)
.collect::<Vec<_>>();
big_enough.sort_unstable_by_key(|f| f.total_size());
println!(
"Big enough: {}",
color(
&big_enough
.iter()
.map(|f| format!("[{}] {}", f.total_size(), f.name()))
.collect::<Vec<String>>()
)
);
let smallest_sufficient = big_enough.first().expect("a big enough dir");
smallest_sufficient.total_size().to_string()
}
fn parse_session(content: &str) -> File {
let mut root = File::Dir {
name: "/".into(),
children: vec![],
};
let mut input = content;
let mut cwd: Vec<String> = vec![];
// let mut current_dir = root;
while input.len() > 0 {
let (remaining_input, cmd) = parse_command(input).expect("parse command");
input = remaining_input;
color!(&cmd);
let current_dir: &mut File = get_dir(&mut root, &cwd);
if let File::Dir {
children,
name: current_dir_name,
} = current_dir
{
match cmd {
Command::cd { target } => {
match target.as_str() {
"/" => {
cwd = vec![];
}
".." => {
cwd.pop();
}
_ => {
let target = children
.iter()
.find(|f| {
if let File::Dir { name, .. } = f {
name == &target
} else {
false
}
})
.expect("find cd target");
// current_dir = target;
cwd.push(target.name())
}
}
println!(
"Changed into {} => cwd: {}",
target,
cwd /* .iter().map(|f| f.get_name()).collect::<Vec<_>>() */
.join("/")
)
}
Command::ls { mut files } => {
println!("Adding children to {}: {:#?}", current_dir_name, color(&cwd));
children.append(&mut files);
}
}
} else {
panic!("cwd {} is not a dir: {:?}", cwd.join("/"), current_dir)
}
}
println!();
println!("Final Directory structure: {}", color(&root));
root
}
fn get_dir<'a>(root: &'a mut File, path: &'a Vec<String>) -> &'a mut File {
let mut cwd = root;
for target in path {
if let File::Dir {
ref mut children, ..
} = cwd
{
cwd = children
.into_iter()
.find(|f| {
if let File::Dir { name, .. } = f {
name == target
} else {
false
}
})
.expect("find cd target")
.borrow_mut()
} else {
panic!("get_dir path '{}' is not a dir: {:?}", path.join("/"), cwd)
}
}
cwd
}
fn parse_command(input: &str) -> IResult<&str, Command> {
let (input, cmd_name) = parse_command_name(input).expect("parse command name");
Ok(match cmd_name {
"ls" => {
let (input, files) = parse_ls_output(input).expect("parse command output");
(input, Command::ls { files })
}
"cd" => {
let (input, target) = parse_command_arg(input).expect("parse command arg");
let (input, _) = newline(input)?;
(
input,
Command::cd {
target: target.into(),
},
)
}
&_ => panic!("invalid command {}", cmd_name),
})
}
fn parse_ls_output(input: &str) -> IResult<&str, Vec<File>> {
let (input, output) = parse_command_output(input)?;
let (remaining_output, files) = many0(parse_file)(output)?;
if remaining_output.len() != 0 {
panic!("ls output not fully consumed: '{}'", remaining_output);
}
Ok((input, files))
}
fn parse_file(input: &str) -> IResult<&str, File> {
let (input, dir_or_size) = alt((tag("dir"), digit1))(input)?;
let (input, _) = tag(" ")(input)?;
let (input, name) = till_eol(input)?;
let (input, _) = opt(newline)(input)?;
let file = match dir_or_size {
"dir" => File::Dir {
name: name.into(),
children: vec![],
},
size => File::Plain {
name: name.into(),
size: size.parse().expect("parsable size"),
},
};
color!(&file, input);
Ok((input, file))
}
fn parse_command_name(input: &str) -> IResult<&str, &str> {
let (input, _) = tag("$")(input)?;
let (input, _) = tag(" ")(input)?;
let (input, cmd_name) = take_while1(AsChar::is_alpha)(input)?;
Ok((input, cmd_name))
}
fn parse_command_arg(input: &str) -> IResult<&str, &str> {
let (input, _) = tag(" ")(input)?;
let (input, arg) = till_eol(input)?;
Ok((input, arg))
}
fn parse_command_output(input: &str) -> IResult<&str, &str> {
let (input, _) = newline(input)?;
let (input, output) = take_while1(|c: char| c != '$')(input)?;
Ok((input, output))
}
fn till_eol(input: &str) -> IResult<&str, &str> {
Ok(take_till1(|c: char| c.is_whitespace())(input)?)
}
impl File {
fn name(&self) -> String {
match self {
File::Dir { name, .. } => name.clone(),
File::Plain { name, .. } => name.clone(),
}
}
fn total_size(&self) -> usize {
match self {
File::Plain { size, .. } => *size,
File::Dir { children, .. } => children.into_iter().map(|f| f.total_size()).sum(),
}
}
fn dirs_recursive(&self) -> Vec<&File> {
self.trans_iter_with(|file| {
if let File::Dir { children, .. } = file {
children
.into_iter()
.filter(|f| matches!(f, File::Dir { .. }))
.collect::<Vec<_>>()
} else {
vec![]
}
})
.collect()
}
}
// impl Display for File {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// match self {
// Self::cd { target } => {
// write!(f, "cd {}", target)?;
// }
// Self::ls { files } => {
// write!(
// f,
// "ls\n{:?}",
// files
// .iter()
// .map(|f| format!("{}", color(f)))
// .collect::<Vec<_>>()
// .join("\n")
// )?;
// }
// }
// Ok(())
// }
// }
// impl Display for Command {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// match self {
// Self::cd { target } => {
// write!(f, "cd {}", target)?;
// }
// Self::ls { files } => {
// write!(
// f,
// "ls\n{:?}",
// files
// .iter()
// .map(|f| format!("{}", color(f)))
// .collect::<Vec<_>>()
// .join("\n")
// )?;
// }
// }
// Ok(())
// }
// }
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE: &str = "$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k";
#[test]
fn example_part1() {
let result = process_part1(EXAMPLE.into());
assert_eq!(result, "95437");
}
#[test]
fn real_part1() {
let result = process_part1(fs::read_to_string("./input").expect("Read ./input"));
assert_eq!(result, "1443806");
}
#[test]
fn example_part2() {
let result = process_part2(EXAMPLE.into());
assert_eq!(result, "24933642");
}
#[test]
fn real_part2() {
let result = process_part2(fs::read_to_string("./input").expect("Read ./input"));
assert_eq!(result, "942298");
}
}

12
2022/day7/src/utils.rs Executable file
View file

@ -0,0 +1,12 @@
/// https://stackoverflow.com/a/69324393/1633985
#[macro_export]
macro_rules! cast {
($target: expr, $pat: path) => {{
if let $pat(a) = $target {
// #1
a
} else {
panic!("mismatch variant when cast to {}", stringify!($pat)); // #2
}
}};
}

80
2022/day7/task.txt Executable file
View file

@ -0,0 +1,80 @@
--- Day 7: No Space Left On Device ---
You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?
The device the Elves gave you has problems with more than just its communication system. You try to run a system update:
$ system-update --please --pretty-please-with-sugar-on-top
Error: No space left on device
Perhaps you can delete some files to make space for the update?
You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example:
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in.
Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers:
cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument:
cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory.
cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory.
cd / switches the current directory to the outermost directory, /.
ls means list. It prints out all of the files and directories immediately contained by the current directory:
123 abc means that the current directory contains a file named abc with size 123.
dir xyz means that the current directory contains a directory named xyz.
Given the commands and output in the example above, you can determine that the filesystem looks visually like this:
- / (dir)
- a (dir)
- e (dir)
- i (file, size=584)
- f (file, size=29116)
- g (file, size=2557)
- h.lst (file, size=62596)
- b.txt (file, size=14848514)
- c.dat (file, size=8504156)
- d (dir)
- j (file, size=4060174)
- d.log (file, size=8033020)
- d.ext (file, size=5626152)
- k (file, size=7214296)
Here, there are four directories: / (the outermost directory), a and d (which are in /), and e (which is in a). These directories also contain files of various sizes.
Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.)
The total sizes of the directories above can be found as follows:
The total size of directory e is 584 because it contains a single file i of size 584 and no other directories.
The directory a has total size 94853 because it contains files f (size 29116), g (size 2557), and h.lst (size 62596), plus file i indirectly (a contains e which contains i).
Directory d has total size 24933642.
As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file.
To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a and e; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!)
Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories?