dfriedenberger
: dfriedenberger
dfriedenberger |
Have used https://adventofcode.com/2018/day/2 for first steps on day zero.
cargo run
Open Project in VS Code Devcontainer https://code.visualstudio.com/docs/remote/containers
src/main.rs
use std::fs::File;
use std::io::{self,BufRead};
use std::path::Path;
use dfrieden_day00::parser::Parser;
fn main() {
let path = Path::new("input.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let file = match File::open(&path) {
Err(why) => panic!("couldn't open {}: {}", display, why),
Ok(file) => file,
};
let lines = io::BufReader::new(file).lines();
let p = Parser {};
let mut two = 0;
let mut three = 0;
for line in lines {
match line {
Err(why) => panic!("couldn't read line: {}", why),
Ok(l) => {
let (a,b) = p.parse(&l);
two += a;
three += b;
}
}
};
println!("{}",two * three);
}
cargo build
./target/debug/dfrieden_day00
pub mod parser;
#[cfg(test)]
mod tests {
use crate::parser::Parser;
#[test]
fn it_works() {
let p = Parser {};
assert_eq!(p.parse("abcdef"), (0,0));
assert_eq!(p.parse("bababc"), (1,1));
assert_eq!(p.parse("abbcde"), (1,0));
assert_eq!(p.parse("abcccd"), (0,1));
assert_eq!(p.parse("aabcdd"), (1,0));
assert_eq!(p.parse("abcdee"), (1,0));
assert_eq!(p.parse("ababab"), (0,1));
}
}
cargo build
Find the full puzzle https://adventofcode.com/2021/day/1 |
As the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine. For example, suppose you had the following report:
let vec1 = vec![
199,
200,
208,
210,
200,
207,
240,
269,
260,
263
];
This report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on. The first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something.
To do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.)
pub fn calculate_increases(data : &Vec<i32>) -> std::io::Result<i32>
{
let mut sum = 0;
let l = data.len();
for ix in 1..l {
if data[ix] > data[ix-1] { sum+= 1; }
}
return Ok(sum);
}
In the example above, the changes are as follows:
199 (N/A - no previous measurement)
200 (increased)
208 (increased)
210 (increased)
200 (decreased)
207 (increased)
240 (increased)
269 (increased)
260 (decreased)
263 (increased)
In this example, there are 7 measurements that are larger than the previous measurement.
assert_eq!(calculate_increases(&vec1).unwrap(), 7);
How many measurements are larger than the previous measurement?
let data = read_file("input.txt").unwrap();
println!("star1 {}",calculate_increases(&data).unwrap());
Considering every single measurement isn't as useful as you expected: there's just too much noise in the data. Instead, consider sums of a three-measurement sliding window. Again considering the above example:
199 A
200 A B
208 A B C
210 B C D
200 E C D
207 E F D
240 E F G
269 F G H
260 G H
263 H
Start by comparing the first and second three-measurement windows. The measurements in the first window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased.
Start by comparing the first and second three-measurement windows. The measurements in the first window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased.
Your goal now is to count the number of times the sum of measurements in this sliding window increases from the previous sum. So, compare A with B, then compare B with C, then C with D, and so on. Stop when there aren't enough measurements left to create a new three-measurement sum.
pub fn calculate_window(data : &Vec<i32>) -> std::io::Result<Vec<i32>>
{
let l = data.len();
let mut data2 = Vec::new();
for ix in 2..l {
let window = data[ix] + data[ix-1] + data[ix-2];
data2.push(window)
}
return Ok(data2);
}
In the above example, the sum of each three-measurement window is as follows:
A: 607 (N/A - no previous sum)
B: 618 (increased)
C: 618 (no change)
D: 617 (decreased)
E: 647 (increased)
F: 716 (increased)
G: 769 (increased)
H: 792 (increased)
In this example, there are 5 sums that are larger than the previous sum.
let vec2 = calculate_window(&vec1).unwrap();
assert_eq!(calculate_increases(&vec2).unwrap(), 5);
Consider sums of a three-measurement sliding window. How many sums are larger than the previous sum?
let data2 = calculate_window(&data).unwrap();
println!("star2 {}",calculate_increases(&data2).unwrap());
Find the full puzzle https://adventofcode.com/2021/day/2 |
Now, you need to figure out how to pilot this thing. It seems like the submarine can take a series of commands like forward 1, down 2, or up 3: forward X increases the horizontal position by X units. down X increases the depth by X units. up X decreases the depth by X units. Note that since you're on a submarine, down and up affect your depth, and so they have the opposite result of what you might expect. The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example:
Calculate the horizontal position and depth you would have after following the planned course.
let vec1 = vec![
String::from("forward 5"),
String::from("down 5"),
String::from("forward 8"),
String::from("up 3"),
String::from("down 8"),
String::from("forward 2")
];
Your horizontal position and depth both start at 0. The steps above would then modify them as follows: forward 5 adds 5 to your horizontal position, a total of 5. down 5 adds 5 to your depth, resulting in a value of 5. forward 8 adds 8 to your horizontal position, a total of 13. up 3 decreases your depth by 3, resulting in a value of 2. down 8 adds 8 to your depth, resulting in a value of 10. forward 2 adds 2 to your horizontal position, a total of 15. After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.)
let parsed = parse(&vec1).unwrap();
let (position,deep) = course(&parsed).unwrap();
assert_eq!(position, 15);
assert_eq!(deep, 10);
assert_eq!(position * deep, 150);
Calculate the horizontal position and depth you would have after following the planned course.
pub fn course(data: &Vec<(String,i32)>) -> std::io::Result<(i32,i32)> {
let mut deep = 0;
let mut position = 0;
let l = data.len();
for i in 0..l {
let step = data.get(i).unwrap();
if step.0 == "forward" { position += step.1 }
if step.0 == "up" { deep -= step.1; }
if step.0 == "down" { deep += step.1; }
}
return Ok((position,deep))
}
What do you get if you multiply your final horizontal position by your final depth?
let data = read_file("input.txt").unwrap();
let parsed = parse(&data).unwrap();
let (position,deep) = course(&parsed).unwrap();
println!("star 1 {}",position * deep);
Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated. In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought: down X increases your aim by X units. up X decreases your aim by X units. forward X does two things: It increases your horizontal position by X units. It increases your depth by your aim multiplied by X. Again note that since you're on a submarine, down and up do the opposite of what you might expect: "down" means aiming in the positive direction.
pub fn course2(data: &Vec<(String,i32)>) -> std::io::Result<(i32,i32)> {
let mut deep = 0;
let mut position = 0;
let mut aim = 0;
let l = data.len();
for i in 0..l {
let step = data.get(i).unwrap();
if step.0 == "forward" { position += step.1; deep += aim * step.1; }
if step.0 == "up" { aim -= step.1; }
if step.0 == "down" { aim += step.1; }
}
return Ok((position,deep))
}
Now, the above example does something different:
forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change.
down 5 adds 5 to your aim, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40.
up 3 decreases your aim by 3, resulting in a value of 2.
down 8 adds 8 to your aim, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60.
After following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.)
let (position,deep) = course2(&parsed).unwrap();
assert_eq!(position, 15);
assert_eq!(deep, 60);
assert_eq!(position * deep, 900);
Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?
let (position,deep) = course2(&parsed).unwrap();
println!("star 2 {}",position * deep);
Find the full puzzle https://adventofcode.com/2021/day/3 |
The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption. You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate. Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report:
let vec1 = vec![
String::from("00100"),
String::from("11110"),
String::from("10110"),
String::from("10111"),
String::from("10101"),
String::from("01111"),
String::from("00111"),
String::from("11100"),
String::from("10000"),
String::from("11001"),
String::from("00010"),
String::from("01010")
];
Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1. The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0. The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110. So, the gamma rate is the binary number 10110, or 22 in decimal. The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198.
let bits = count_bits(&vec1).unwrap();
let (gamma , epsilon) = power_consumption(&bits,vec1.len()).unwrap();
assert_eq!(gamma, 22);
assert_eq!(epsilon, 9);
assert_eq!(gamma * epsilon, 198);
pub fn count_bits(data: &Vec<String>) -> std::io::Result<Vec<i32>> {
let mut bits = Vec::new();
let l = data.len();
let size = data.get(0).unwrap().len();
for _p in 0..size {
bits.push(0);
}
for i in 0..l {
let line = data.get(i).unwrap();
let b: &[u8] = line.as_bytes();
for p in 0..size {
let c: char = b[p] as char;
match c {
'1' => bits[p] += 1,
'0' => (),
_ => panic!("unknown char {}",c)
}
}
}
return Ok(bits)
}
pub fn power_consumption(bits: &Vec<i32>,numbers : usize) -> std::io::Result<(i32,i32)> {
let mut gamma : i32 = 0;
let mut epsilon : i32 = 0;
let l = bits.len();
for ix in 0..l {
gamma <<= 1;
epsilon <<= 1;
let cnt1 = *bits.get(ix).unwrap();
if cnt1 > ((numbers as i32)/2)
{
//'1' is the most common bit
gamma += 1;
}
else
{
//'0' is the most common bit
epsilon += 1;
}
}
Ok((gamma,epsilon))
}
Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.)
let data = read_file("input.txt").unwrap();
let bits = count_bits(&data).unwrap();
let (gamma , epsilon) = power_consumption(&bits,data.len()).unwrap();
println!("start 1 {}",gamma * epsilon);
Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating. Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then: Keep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria. If you only have one number left, stop; this is the rating value for which you are searching. Otherwise, repeat the process, considering the next bit to the right. The bit criteria depends on which type of rating value you want to find: To find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered. To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered.
For example, to determine the oxygen generator rating value using the same example diagnostic report from above: Start with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: 11110, 10110, 10111, 10101, 11100, 10000, and 11001. Then, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000. In the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101. In the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111. In the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111. As there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal. Then, to determine the CO2 scrubber rating value from the same example above: Start again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010. Then, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010. In the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010. As there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal. Finally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230.
let (oxygen_generator_rating , co2_scrubber_rating) = filter(&vec1).unwrap();
assert_eq!(oxygen_generator_rating, 23);
assert_eq!(co2_scrubber_rating, 10);
assert_eq!(oxygen_generator_rating * co2_scrubber_rating, 230);
For each type of rating value we filter the list until one element is left.
pub fn filter_by_strategy(data: &Vec<String>,filterStrategy : FilterStrategy) -> std::io::Result<i32> {
let mut ref_data : Vec<String> = data.to_vec();
let ll = data.get(0).unwrap().len();
for p in 0..ll {
match ref_data.len() {
0 => panic!("something went wrong"),
1 => /* ready */ break,
_ => (),
}
//reduce
let bit = count_bit(&ref_data,p,filterStrategy).unwrap();
let bl = ref_data.len();
ref_data = filter_by_criteria(&ref_data,bit,p).unwrap();
let al = ref_data.len();
}
if ref_data.len() != 1 {
panic!("Something went wrong")
}
let number = convert2number(ref_data.get(0).unwrap()).unwrap();
return Ok(number);
}
Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.)
let (oxygen_generator_rating , co2_scrubber_rating) = filter(&data).unwrap();
println!("start 2 {}",oxygen_generator_rating * co2_scrubber_rating);
Find the full puzzle https://adventofcode.com/2021/day/4 |
The score of the winning board can now be calculated. Start by finding the sum of all unmarked numbers on that board; in this case, the sum is 188. Then, multiply that sum by the number that was just called when the board won, 24, to get the final score, 188 * 24 = 4512. To guarantee victory against the giant squid, figure out which board will win first. What will your final score be if you choose that board?
let vec1 = vec![
String::from("7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1"),
String::from(""),
String::from("22 13 17 11 0"),
String::from(" 8 2 23 4 24"),
String::from("21 9 14 16 7"),
String::from(" 6 10 3 18 5"),
String::from(" 1 12 20 15 19"),
String::from(""),
String::from(" 3 15 0 2 22"),
String::from(" 9 18 13 17 5"),
String::from("19 8 7 25 23"),
String::from("20 11 10 24 4"),
String::from("14 21 16 12 6"),
String::from(""),
String::from("14 21 17 24 4"),
String::from("10 16 15 9 19"),
String::from("18 8 23 26 20"),
String::from("22 11 13 6 5"),
String::from(" 2 0 12 3 7"),
];
let (unmarked_numbers,called_number) = play_game_util_first_bingo(&numbers,&mut boards).unwrap();
assert_eq!(unmarked_numbers,188);
assert_eq!(called_number,24);
assert_eq!(unmarked_numbers * called_number,4512);
pub fn play_game_util_first_bingo(numbers: &Vec<i32>,boards : &mut Vec<Board>) -> std::io::Result<(i32,i32)>
{
for &n in numbers {
let l = boards.len();
for i in 0..l {
boards[i].mark_number(n);
if boards[i].has_bingo() {
return Ok((boards[i].summarize_unmarked_numbers(),n))
}
}
}
Err(Error::new(ErrorKind::Other, "oh no!"))
}
Figure out which board will win last. Once it wins, what would its final score be?
For this we need to adjust the algorithm just a little bit. === Solution
if boards[i].has_bingo() {
if all_boards_ready(boards) {
return Ok((boards[i].summarize_unmarked_numbers(),n))
}
}
Find the full puzzle https://adventofcode.com/2021/day/5 |
You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible. They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example:
let vec1 = vec![
String::from("0,9 -> 5,9"),
String::from("8,0 -> 0,8"),
String::from("9,4 -> 3,4"),
String::from("2,2 -> 2,1"),
String::from("7,0 -> 7,4"),
String::from("6,4 -> 2,0"),
String::from("0,9 -> 2,9"),
String::from("3,4 -> 1,4"),
String::from("0,0 -> 8,8"),
String::from("5,5 -> 8,2")
];
To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of 5 points.
let board = create_game(&vec1,false).unwrap();
board.dump(10,10);
assert_eq!(board.count_crossing(), 5);
The diagram (here it is called Board, because the class was allready created yesterday :-) ) was implemented.
pub struct Board {
field : HashMap<String, i32>
}
impl Board {
pub fn new() -> Board
{
Board {
field : HashMap::new()
}
}
pub fn set(&mut self,x : i32,y : i32)
{
let key = format!("{},{}", x,y);
let val = match self.field.get(&key) {
Some(cnt) => *cnt,
None => 0
};
self.field.insert(key,val+1);
}
pub fn count_crossing(&self) -> i32
{
let mut sum = 0;
for (_key, val) in self.field.iter() {
if *val > 1 { sum += 1;}
}
return sum;
}
pub fn dump(&self,width : usize,height : usize)
{
for y in 0..height {
let mut line = String::new();
for x in 0..width {
let key = format!("{},{}", x,y);
let val = match self.field.get(&key) {
Some(cnt) => format!("{}",*cnt),
None => ".".to_string()
};
line.push_str(&val);
}
println!("{}",line);
}
}
}
Finally, the horizontal and vertical lines were simply drawn on the board. Ohhh. There are also lines that go from bottom to top and from left to right.
if x1 > x2 {
let xs = x1;
x1 = x2;
x2 = xs;
}
if y1 > y2 {
let ys = y1;
y1 = y2;
y2 = ys;
}
for x in x1..x2+1 {
for y in y1..y2+1 {
board.set(x,y);
}
}
Same problem and solution, but consider also diagonals.
You still need to determine the number of points where at least two lines overlap. In the above example, this is still anywhere in the diagram with a 2 or larger - now a total of 12 points.
let board = create_game(&vec1,true).unwrap();
board.dump(10,10);
assert_eq!(board.count_crossing(), 12);
let mut x = x1;
let mut y = y1;
let xo = if x1 < x2 { 1 } else { -1};
let yo = if y1 < y2 { 1 } else { -1};
let cnt = if x1 < x2 { x2 - x1 + 1 } else { x1 - x2 + 1 };
for _i in 0..cnt {
board.set(x,y);
x += xo;
y += yo;
}
Find the full puzzle https://adventofcode.com/2021/day/6 |
Exponentially growth rate of lanternfishs.
let vec1 = vec![
"3,4,3,1,2"
];
This list means that the first fish has an internal timer of 3, the second fish has an internal timer of 4, and so on until the fifth fish, which has an internal timer of 2.
let mut swarm = create_swarm(&vec2).unwrap();
let cnt = incr_and_count(&mut swarm,18);
assert_eq!(cnt, 26);
let cnt = incr_and_count(&mut swarm,80 - 18);
assert_eq!(cnt, 5934);
Because the '''exponentially''' keyword triggers us, I used one counter per fish age as the data structure instread managing each fish individually.
pub fn create_swarm(data: &Vec<String>) -> std::io::Result<Vec<u64>> {
let mut swarm = vec![0,0,0,0,0,0,0,0,0];
let first_line = data.get(0).unwrap();
let numbers: Vec<u64> = first_line.split(",").map(|s| s.parse().unwrap()).collect();
for n in numbers {
let i = n as usize;
swarm[i] += 1;
}
return Ok(swarm)
}
So is was easy to calculate the numbers of fishes.
pub fn incr_and_count(data: &mut Vec<u64>,days: u32) -> u64 {
for _d in 0..days {
let n = data.remove(0);
data.push(0);
data[6] += n;
data[8] += n;
}
let mut sum = 0;
for n in data {
sum += *n;
}
return sum;
}
let data = read_file("input.txt").unwrap();
let mut swarm = create_swarm(&data).unwrap();
let cnt = incr_and_count(&mut swarm,80);
println!("star 1 {}",cnt);
For solving, had to need change u32 values to u64 values. One advantage of Rust I learned today, was that rust throw integer overflow exception.
Calculate 256-80 more days. ;-)
let cnt = incr_and_count(&mut swarm,256-80);
println!("star 2 {}",cnt);
Find the full puzzle https://adventofcode.com/2021/day/7 |
Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible.
let vec1 = vec![
"16,1,2,0,4,2,7,1,2,14"
];
This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on.
let swarm = create_swarm(&vec2).unwrap();
let cnt = calculate_fuel(&swarm,2,linear);
assert_eq!(cnt, 37);
let cnt = calculate_fuel(&swarm,10,linear);
assert_eq!(cnt, 71);
let mut min = 0;
for h in 0..10 {
let cnt = calculate_fuel(&swarm,h,linear);
println!("sum {}",cnt);
if min == 0 || cnt < min {
min = cnt;
}
}
assert_eq!(min, 37);
Calculate used fuel for each position
pub fn calculate_fuel(data: &Vec<u32>,h : u32,fuel : fn(u32) -> u32) -> u32 {
let mut sum = 0;
for d in data {
let distance = if *d < h {
h - *d
} else {
*d - h
};
sum += fuel(distance);
}
return sum;
}
and find minimum.
let data = read_file("input.txt").unwrap();
let swarm = create_swarm(&data).unwrap();
let mut min = 0;
for h in 0..2000 {
let cnt = calculate_fuel(&swarm,h,linear);
if min == 0 || cnt < min {
min = cnt;
}
}
println!("star 1 {}",min);
As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on.
So for calulating fuel we use gaussian sum.
pub fn gaussian_sum(v : u32) -> u32 {
return (v * (v+1)) / 2;
}
and use same algorithm.
let mut min = 0;
for h in 0..2000 {
let cnt = calculate_fuel(&swarm,h,gaussian_sum);
if min == 0 || cnt < min {
min = cnt;
}
}
println!("star 2 {}",min);
Find the full puzzle https://adventofcode.com/2021/day/8 |
In the output values, how many times do digits 1, 4, 7, or 8 appear?
let vec1 = vec![
"be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe",
"edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc",
"fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg",
"fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb",
"aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea",
"fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb",
"dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe",
"bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef",
"egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb",
"gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce"
];
let vec2 : Vec<String> = vec1.into_iter().map(|e| String::from(e)).collect();
let entries = parse_entries(&vec2).unwrap();
assert_eq!(entries.len(), 10);
let cnt = count_digits1478(&entries);
assert_eq!(cnt, 26);
pub fn count_digits1478(&self) -> u32 {
let mut cnt = 0;
for diget in &self.digets {
let l = diget.len();
if l == 2 || l == 3 || l == 4 || l == 7 {
cnt += 1;
}
}
return cnt;
}
For each entry, determine all of the wire/segment connections and decode the four-digit output values. What do you get if you add up all of the output values?
let nr = entries[0].determine();
assert_eq!(nr, 8394);
let all = determine(&entries);
assert_eq!(all, 61229);
pub fn determine(&self) -> u32 {
let n1 = self.get(2);
let n7 = self.get(3);
let n4 = self.get(4);
let n235 = self.get(5);
let n069 = self.get(6);
let n8 = self.get(7);
let d48 = diff(&n4[0],&n8[0]); //segments eg
let d41 = diff(&n4[0],&n1[0]); //segments bd
let (n2 , n35) = split(&n235,&d48);
let (n06 , n9) = split(&n069,&d48);
let (n5, n3) = split(&n35,&d41);
let (n6, n0) = split(&n06,&d41);
let mut num = 0;
for diget in &self.digets {
num *= 10;
let mut z = 0;
if n0[0] == *diget { z = 0; }
if n1[0] == *diget { z = 1; }
if n2[0] == *diget { z = 2; }
if n3[0] == *diget { z = 3; }
if n4[0] == *diget { z = 4; }
if n5[0] == *diget { z = 5; }
if n6[0] == *diget { z = 6; }
if n7[0] == *diget { z = 7; }
if n8[0] == *diget { z = 8; }
if n9[0] == *diget { z = 9; }
num += z;
}
return num;
}
Find the full puzzle https://adventofcode.com/2021/day/9 |
Your first goal is to find the low points - the locations that are lower than any of its adjacent locations. Most locations have four adjacent locations (up, down, left, and right); locations on the edge or corner of the map have three or two adjacent locations, respectively. (Diagonal locations do not count as adjacent.)
let vec1 = vec![
"2199943210",
"3987894921",
"9856789892",
"8767896789",
"9899965678"
];
let vec2 : Vec<String> = vec1.into_iter().map(|e| String::from(e)).collect();
let heightmap = create_heightmap(&vec2).unwrap();
assert_eq!(heightmap.cnt_risk_levels(), 15);
What do you get if you multiply together the sizes of the three largest basins?
assert_eq!(heightmap.largest_basin_sizes(), 1134);
HeightMap
use array2d::Array2D;
//Array2D based field
pub struct HeightMap {
array : Array2D<u32>
}
impl HeightMap {
pub fn new(rows : Vec<Vec<u32>>) -> HeightMap
{
HeightMap {
array : Array2D::from_rows(&rows)
}
}
pub fn get(&self,x : usize,y : usize) -> u32
{
return *self.array.get(x,y).unwrap();
}
pub fn is_low_point(&self,x : usize,y : usize) -> bool {
let lx = self.array.column_len() - 1;
let ly = self.array.row_len() - 1;
let i = self.get(x,y);
if 0 < x && self.get(x-1,y) <= i { return false }
if 0 < y && self.get(x,y-1) <= i { return false }
if x < lx && self.get(x+1,y) <= i { return false }
if y < ly && self.get(x,y+1) <= i { return false }
return true
}
pub fn basin_size(&self,visited : &mut Array2D<bool> , x : usize,y : usize) -> u32 {
let lastx = self.array.column_len() - 1;
let lasty = self.array.row_len() - 1;
if *visited.get(x,y).unwrap() { return 0; }
visited.set(x,y,true).ok();
let i = self.get(x,y);
if i == 9 { return 0; }
let mut size = 1;
if x > 0 { size += self.basin_size(visited,x-1,y) }
if x < lastx { size += self.basin_size(visited,x+1,y) }
if y > 0 { size += self.basin_size(visited,x,y-1) }
if y < lasty { size += self.basin_size(visited,x,y+1) }
return size;
}
pub fn lowest_points(&self) -> Vec<(usize,usize)> {
let mut points = Vec::new();
for y in 0..self.array.row_len() {
for x in 0..self.array.column_len() {
if self.is_low_point(x,y) {
points.push((x,y));
}
}
}
return points;
}
pub fn cnt_risk_levels(&self) -> u32
{
let lp = self.lowest_points();
let mut sum = 0;
for (x,y) in lp {
let i = self.get(x,y);
sum += i + 1;
}
return sum;
}
pub fn largest_basin_sizes(&self) -> u32
{
let mut sizes : Vec<u32> = Vec::new();
let lp = self.lowest_points();
for (x,y) in lp {
let mut visited = Array2D::filled_with(false,self.array.column_len(),self.array.row_len());
sizes.push(self.basin_size(&mut visited,x,y));
}
sizes.sort_by(|a, b| b.cmp(a));
return sizes[0] * sizes[1] * sizes[2]
}
}
Find the full puzzle https://adventofcode.com/2021/day/10 |
Find all corrupt lines (ignore incomplete lines) and calculate error score.
To calculate the syntax error score for a line, take the first illegal character on the line and look it up in the following table: ): 3 points. ]: 57 points. }: 1197 points. >: 25137 points.
let vec1 = vec![
"[({(<(())[]>[[{[]{<()<>>",
"[(()[<>])]({[<{<<[]>>(",
"{([(<{}[<>[]}>{[]{[(<()>",
"(((({<>}<{<{<>}{[]{[]{}",
"[[<[([]))<([[{}[[()]]]",
"[{[{({}]{}}([{[{{{}}([]",
"{<[[]]>}<{[{[{[]{()[[[]",
"[<(<(<(<{}))><([]([]()",
"<{([([[(<>()){}]>(<<{{",
"<{([{{}}[<[[[<>{}]]]>[]]"
];
let vec2 : Vec<String> = vec1.into_iter().map(|e| String::from(e)).collect();
let err = validate(&vec2).unwrap();
assert_eq!(err, 26397);
Find all incomplete lines (ignore corrupt lines) and calculate autocomplete score.
The score is determined by considering the completion string character-by-character. Start with a total score of 0. Then, for each character, multiply the total score by 5 and then increase the total score by the point value given for the character in the following table: ): 1 point. ]: 2 points. }: 3 points. >: 4 points.
let score = autocomplete(&vec2).unwrap();
assert_eq!(score, 288957);
pub fn index(str : &str,z : char) -> i32 {
match str.find(z) {
Some(a) => a as i32,
None => -1
}
}
pub fn checkline(line : &String) -> Option<char> {
let row: Vec<char> = line.chars().collect();
//validate
let mut stack: Vec<char> = Vec::new();
for c in row {
if index("[({<",c) >= 0 {
stack.push(c);
}
if index("])}>",c) >= 0 {
//try pop_back
let c2 = stack.remove(stack.len() - 1);
if index("[({<",c2) != index("])}>",c)
{
//println!("corrupt line: {} != {} in line {}",c2,c,line);
return Some(c);
}
}
//println!("Stack {:?}",stack);
}
if stack.len() != 0
{
//println!("incomplete line: {}",line);
}
return None;
}
pub fn checkline2(line : &String) -> Option<Vec<char>> {
let row: Vec<char> = line.chars().collect();
//validate
let mut stack: Vec<char> = Vec::new();
for c in row {
if index("[({<",c) >= 0 {
stack.push(c);
}
if index("])}>",c) >= 0 {
//try pop_back
let c2 = stack.remove(stack.len() - 1);
if index("[({<",c2) != index("])}>",c)
{
//println!("corrupt line: {} != {} in line {}",c2,c,line);
return None;
}
}
//println!("Stack {:?}",stack);
}
if stack.len() != 0
{
//println!("incomplete line: {}",line);
return Some(stack);
}
return None;
}
//tag::create_bingo_boards[]
pub fn validate(data: &Vec<String>) -> std::io::Result<u32> {
let l = data.len();
let mut err = 0;
for i in 0..l {
let line = data.get(i).unwrap();
match checkline(line) {
Some(c) => {
err += match c {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
_ => panic!(" unknown char {}",c)
}
},
None => {}
}
}
return Ok(err)
}
pub fn autocomplete(data: &Vec<String>) -> std::io::Result<u64> {
let l = data.len();
let mut scores = Vec::new();
for i in 0..l {
let line = data.get(i).unwrap();
match checkline2(line) {
Some(stack) => {
let mut score : u64 = 0;
for c in stack.iter().rev() {
score *= 5;
score += match c {
'(' => 1,
'[' => 2,
'{' => 3,
'<' => 4,
_ => panic!(" unknown char {}",c)
}
}
scores.push(score);
//println!("Stack {:?} scores {} in line {}",stack,score,line)
},
None => {}
}
}
//return middle of scores
scores.sort();
let l = scores.len();
return Ok(*scores.get((l-1)/2).unwrap())
}
Find the full puzzle https://adventofcode.com/2021/day/11 |
Given the starting energy levels of the dumbo octopuses in your cavern, simulate 100 steps. How many total flashes are there after 100 steps?
let vec1 = vec![
"5483143223",
"2745854711",
"5264556173",
"6141336146",
"6357385478",
"4167524645",
"2176841721",
"6882881134",
"4846848554",
"5283751526"
];
let vec2 : Vec<String> = vec1.into_iter().map(|e| String::from(e)).collect();
let mut grid = create_octopus_grid(&vec2).unwrap();
let cnt = simulate_steps(&mut grid,100);
assert_eq!(cnt, 1656);
If you can calculate the exact moments when the octopuses will all flash simultaneously, you should be able to navigate through the cavern. What is the first step during which all octopuses flash?
let mut grid = create_octopus_grid(&vec2).unwrap();
let steps = simulate_until_superflash(&mut grid);
assert_eq!(steps, 195);
Parser
use crate::fields::OctopusGrid;
//tag::create_octopus_grid[]
pub fn create_octopus_grid(data: &Vec<String>) -> std::io::Result<OctopusGrid> {
let l = data.len();
let mut rows = Vec::new();
for i in 0..l {
let line = data.get(i).unwrap();
let row: Vec<u32> = line.chars().map(|c| c.to_digit(10).unwrap()).collect();
rows.push(row);
}
return Ok(OctopusGrid::new(rows))
}
//end::create_octopus_grid[]
//tag::simulate_steps[]
pub fn simulate_steps(grid : &mut OctopusGrid,steps : u32) -> u32
{
let mut flashes = 0;
for _i in 0..steps {
grid.incr();
grid.flash();
flashes += grid.zero();
}
return flashes;
}
//end::simulate_steps[]
//tag::simulate_until_superflash[]
pub fn simulate_until_superflash(grid : &mut OctopusGrid) -> u32
{
let mut cnt = 0;
let size = grid.size() as u32;
loop {
cnt += 1;
grid.incr();
grid.flash();
let sum = grid.zero();
if sum == size {
//Superflash 8-)
return cnt;
}
}
}
//end::simulate_until_superflash[]
Fields
//Playing fields
use array2d::Array2D;
//Array2D based field
pub struct OctopusGrid {
array : Array2D<u32>
}
impl OctopusGrid {
pub fn new(rows : Vec<Vec<u32>>) -> OctopusGrid
{
OctopusGrid {
array : Array2D::from_rows(&rows)
}
}
pub fn get(&self,x : usize,y : usize) -> u32
{
return *self.array.get(x,y).unwrap();
}
pub fn set(&mut self,x : usize,y : usize,v : u32)
{
self.array.set(x,y,v).ok();
}
pub fn size(&self) -> usize {
self.array.row_len() * self.array.column_len()
}
pub fn incr(&mut self)
{
for y in 0..self.array.row_len() {
for x in 0..self.array.column_len() {
let v = self.get(x,y);
self.set(x,y,v + 1);
}
}
}
pub fn start_points(&self) -> Vec<(usize,usize)> {
let mut points = Vec::new();
for y in 0..self.array.row_len() {
for x in 0..self.array.column_len() {
let v = self.get(x,y);
if v > 9 {
points.push((x,y));
}
}
}
return points;
}
pub fn point_test_incr_flash(&mut self,flashes : &mut Array2D<bool>,x : usize,y : usize,xoff : i32,yoff : i32)
{
let lastx = self.array.column_len() - 1;
let lasty = self.array.row_len() - 1;
//test
if xoff == -1 && x == 0 { return; }
if xoff == 1 && x == lastx { return; }
if yoff == -1 && y == 0 { return; }
if yoff == 1 && y == lasty { return; }
let nx : usize = (x as i32 + xoff) as usize;
let ny : usize = (y as i32 + yoff) as usize;
let v = self.get(nx,ny) + 1;
self.set(nx,ny,v);
if v > 9 {
self.flash_point(flashes,nx,ny);
}
}
pub fn flash_point(&mut self,flashes : &mut Array2D<bool>,x : usize,y : usize)
{
if *flashes.get(x,y).unwrap() {
return;
}
flashes.set(x,y,true).ok();
//incr around this point
self.point_test_incr_flash(flashes,x,y,-1,-1);
self.point_test_incr_flash(flashes,x,y,-1,0);
self.point_test_incr_flash(flashes,x,y,-1,1);
self.point_test_incr_flash(flashes,x,y,0,-1);
self.point_test_incr_flash(flashes,x,y,0,1);
self.point_test_incr_flash(flashes,x,y,1,-1);
self.point_test_incr_flash(flashes,x,y,1,0);
self.point_test_incr_flash(flashes,x,y,1,1);
}
pub fn flash(&mut self)
{
let mut flashes = Array2D::filled_with(false,self.array.column_len(),self.array.row_len());
let sp = self.start_points();
for (x,y) in sp {
self.flash_point(&mut flashes,x,y);
}
}
pub fn zero(&mut self) -> u32
{
let mut sum = 0;
for y in 0..self.array.row_len() {
for x in 0..self.array.column_len() {
let v = self.get(x,y);
if v > 9 {
sum += 1;
self.set(x,y,0);
}
}
}
return sum;
}
}
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)
Find the full puzzles at https://adventofcode.com/2021/ |
Unfortunately, no more time to write documentation. Solving the riddles takes more time than available. Since nobody reads this documentation, including me, it is a wasted effort. Besides, I develop test driven. A hint. If you look into the source code, don't be surprised about the names of variables and functions. I recycle since the second day the code from the day before ;-)