Spyke
adventofcode·Advent of Codebykionite231

part 1 of day 6 of adventofcode 2024 in Rust

use std::fs;

fn update_guard_loc(map: &mut Vec<Vec<char>>, guard_loc: &mut (i32, i32)) {
    match map[guard_loc.0 as usize][guard_loc.1 as usize] {
	'^' => {
	    if map[(guard_loc.0 - 1) as usize][guard_loc.1 as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '>'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.0 -= 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '^';
	    }
	},
	'>' => {
	    if map[guard_loc.0 as usize][(guard_loc.1 + 1) as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'v'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.1 += 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '>';
	    }
	},
	'v' => {
	    if map[(guard_loc.0 + 1) as usize][guard_loc.1 as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '<'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.0 += 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'v';
	    }
	},
	'<' => {
	    if map[guard_loc.0 as usize][(guard_loc.1 - 1) as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '^'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.1 -= 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '<';
	    }
	},

	_ => println!("unreachable"),
    }
}

fn main() {
    let contents = fs::read_to_string("input.txt").expect("Should have able to read the file");
    let mut map: Vec<Vec<char>> = Vec::new();
    let lines = contents.split("\n").collect::<Vec<&str>>();
    for line in lines {
	if line.len() == 0 {
	    // ignore empty line
	    break;
	}
	map.push(line.chars().collect::<Vec<char>>());
    }
    // Getting the first location of guard
    let mut height: i32 = 0;
    let mut width: i32 = 0;
    let mut guard_loc: (i32, i32) = (0, 0);
    for (i, lines) in map.iter().enumerate() {
	for (j, chr) in lines.iter().enumerate() {
	    if *chr == '^' {
		guard_loc.0 = i as i32;
		guard_loc.1 = j as i32;
	    }
	    height = (i + 1) as i32;
	    width = (j + 1) as i32;
	}
    }
    loop {
	update_guard_loc(&mut map, &mut guard_loc);
	match map[guard_loc.0 as usize][guard_loc.1 as usize] {
	    '^' => {
		if guard_loc.0 - 1 < 0 {
		    break;
		}
	    },
	    'v' => {
		if guard_loc.0 + 1 > height - 1 {
		    break;
		}
	    },
	    '>' => {
		if guard_loc.1 + 1 > width - 1 {
		    break;
		}
	    },
	    '<' => {
		if guard_loc.1 - 1 < 0 {
		    break;
		}
	    },
	    _ => println!("ureachable"),
	}
    }

    for line in map.iter() {
	println!("{:?}", line);
    }

    let mut count = 0;
    for line in map.iter() {
	for c in line.iter() {
	    if *c == 'X' {
		count += 1;
	    }
	}
    }
    println!("count: {}", count + 1);
}

View original on lemmy.ca
adventofcode·Advent of Codebykionite231

part 2 of day 5 of adventofcode solution in Rust

use std::fs;
use std::collections::HashMap;

fn reorder_pages<'a>(rules_hash_map: HashMap<&str, Vec<&str>>, page_numbers: &'a str) -> Vec<&'a str>{
    let mut tmp = page_numbers.split(",").collect::<Vec<&str>>();
    for i in 0..tmp.len()-1 {
        for j in i+1..tmp.len() {
            match rules_hash_map.get(&tmp[i]) {
                Some(vec) => {
                    if !vec.contains(&tmp[j]) {
			if let Some(v2) = rules_hash_map.get(&tmp[j]) {
			    if v2.contains(&tmp[i]) {
				// swap two elements
				let t = tmp[i];
				tmp[i] = tmp[j];
				tmp[j] = t;
			    }
			}

                    }
                }
                None => {
		    if let Some(v2) = rules_hash_map.get(&tmp[j]) {
			if v2.contains(&tmp[i]) {
			    // swap two elements
			    let t = tmp[i];
			    tmp[i] = tmp[j];
			    tmp[j] = t;
			}
		    }
                }
            }
        }
    }
    return tmp;
}

fn main() {
    let contents = fs::read_to_string("input.txt")
        .expect("Should have been able to read the file");
    let parts = contents.split("\n\n").collect::<Vec<&str>>();
    let rules = parts[0];
    let page_numbers = parts[1];
    let mut rules_hash_map: HashMap<&str, Vec<&str>> = HashMap::new();

    for rule in rules.split("\n") {
        let tmp = rule.split("|").collect::<Vec<&str>>();
        rules_hash_map.entry(tmp[0]).and_modify(|vec| vec.push(tmp[1])).or_insert(vec![tmp[1]]);
    }

    let mut answer = 0;
    for page_numbers_line in page_numbers.split("\n").collect::<Vec<&str>>() {
        if page_numbers_line.len() == 0 {
            break;
        }
	let none_reordered_pages = page_numbers_line.split(",").collect::<Vec<&str>>();
        let reordered_pages = reorder_pages(rules_hash_map.clone(), page_numbers_line);
	let doesnt_matching = none_reordered_pages.iter().zip(&reordered_pages).filter(|&(a, b)| a != b).count();
	if doesnt_matching > 0 {
	    //println!("reorder_pages: {:?}", reordered_pages);
	   // println!("number of doesn't match: {:?}", doesnt_matching);
	    answer += reordered_pages[reordered_pages.len() / 2].parse::<i32>().unwrap();
	}


    }

    println!("answer: {answer}");
}

View original on lemmy.ca
adventofcode·Advent of Codebykionite231

Solution of part 1 of day 5 of adventofcode (In Rust)

use std::fs;
use std::collections::HashMap;

fn count_correct(rules_hash_map: HashMap<&str, Vec<&str>>, page_numbers: &str) -> bool{
        let tmp = page_numbers.split(",").collect::<Vec<&str>>();
        for i in 0..tmp.len()-1 {
            for j in i+1..tmp.len() {
                match rules_hash_map.get(&tmp[i]) {
                    Some(vec) => {
                        if !vec.contains(&tmp[j]) {
                            return false;
                        }
                    }
                    None => {
                        return false;
                    }
                }
            }
        }
    

    return true;
}

fn main() {
    let contents = fs::read_to_string("input.txt")
        .expect("Should have been able to read the file");
    let parts = contents.split("\n\n").collect::<Vec<&str>>();
    let rules = parts[0];
    let page_numbers = parts[1];
    let mut rules_hash_map: HashMap<&str, Vec<&str>> = HashMap::new();

    for rule in rules.split("\n") {
        let tmp = rule.split("|").collect::<Vec<&str>>();
        rules_hash_map.entry(tmp[0]).and_modify(|vec| vec.push(tmp[1])).or_insert(vec![tmp[1]]);
    }

    let mut count = 0;
    let mut answer = 0;
    for page_numbers_line in page_numbers.split("\n").collect::<Vec<&str>>() {
        if page_numbers_line.len() == 0 {
            break;
        }
        let ok = count_correct(rules_hash_map.clone(), page_numbers_line);
        if ok {
            let tmp = page_numbers_line.split(",").collect::<Vec<&str>>();
            answer += tmp[tmp.len()/2].parse::<i32>().expect("parsing error");
            count += 1;
        }
    }

    println!("true_count: {count}");
    println!("answer: {answer}");
}

any suggestions would be appreciated :)

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=89465c1ac30be37cf136f09d9708108dOpen linkView original on lemmy.ca
adventofcode·Advent of Codebyisti115

2024 / DAY 01 - Solutions

Feel free to share your solutions or browse others' for inspiration! Please tag your comments with the language you solved in to make it easier to search for specific languages in case we happen to get more comments than expected. 😀 I really hope that we can create some discussion here to liven up this community!

View original on lemmy.world
adventofcode·Advent of Codebyisti115

Has there ever been a problem that involved numbers other than integers?

In preparation for this year's event I started to create a utility library and realized that I might not even need to care about decimal, or even fractional numbers, as I don't remember ever encountering them while solving a problem so far. Does anyone have any examples for problems which required using floating point calculations? Is it maybe even explicitly stated that they are not needed? (I remember that Google Code Jam had some statistical problems where the solution didn't have to be exact, just within an acceptable error margin, but that isn't likely to happen here, right?)

View original on lemmy.world
adventofcode·Advent of Codebymykl

Nadvent of Code - 2022 Day 25

As a warmup for this year's Advent of Code, I'm re-reading and posting my solutions to last year's challenges. You can read, run and edit today's solution by following the post link.

Today was the final challenge for the year, and as usual was quite simple and had only one part. This involved parsing and process numbers written in what I learned was called "balanced base five" notation.

Thanks for following along, now we just need to wait a few days to see what this year holds!

https://dartpad.dev/?id=004680836fce05e69a8be7e05b68cf3cOpen linkView original on lemmy.world
adventofcode·Advent of Codebymykl

Nadvent of Code - 2022 Day 24

As a warmup for this year's Advent of Code, I'm re-reading and posting my solutions to last year's challenges. You can read, run and edit today's solution by following the post link.

Today had us running round a maze with moving obstacles. Treating time as a dimension allowed me to build a graph and find the shortest path. Part 2 just required doing this three times. This took me closer than I like to a full second runtime, but not close enough to make me re-think my solution.

https://dartpad.dev/?id=0673f9bfd8af2158050f0e55ba75451bOpen linkView original on lemmy.world
adventofcode·Advent of Codebymykl

Nadvent of Code - 2022 Day 23

As a warmup for this year's Advent of Code, I'm re-reading and posting my solutions to last year's challenges. You can read, run and edit today's solution by following the post link.

Today was a kinda variant of Conway's Game of Life: we had to move elves around according to a set of rules while avoiding collisions and observe the size of the bounding box after 10 rounds. Part 2 asked us to run until the pattern stagnated. Nothing clever in my solution as most of the challenge seemed to be in understanding the rules correctly :-)

https://dartpad.dev/?id=5c5cc4b78c1b541159db97f34a5b389aOpen linkView original on lemmy.world
adventofcode·Advent of Codebymykl

Nadvent of Code - 2022 Day 22

As a warmup for this year's Advent of Code, I'm re-reading and posting my solutions to last year's challenges. You can read, run and edit today's solution by following the post link.

Today started quite easily: build a map and then follow some directions to navigate around it. Part 2? The map is now wrapped around a cube. Oof. I dealt with it by setting up logic for an "ideal" cube layout, and then mapping the provided definition onto that. Oddly, my solution for part2 seems to run faster than part1 despite all the added complexity...

https://dartpad.dev/?id=12713657a02660c09fe3c9e548e7d7e9Open linkView original on lemmy.world