this post was submitted on 31 Dec 2024
2 points (100.0% liked)

Advent of Code

295 readers
1 users here now

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

https://adventofcode.com

founded 2 years ago
MODERATORS
 
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}");
}

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here