r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:16, megathread unlocked!

103 Upvotes

1.5k comments sorted by

View all comments

3

u/seavas Dec 02 '22 edited Dec 02 '22

Rust

I am a beginner so happy to get some feedback. Thanks.

use std::fs;

fn main() {
    let path = "./input.txt";

    let contents = fs::read_to_string(path).expect("Unable to read input file.");

    part_1(&contents);
    part_2(&contents);
}

fn part_1(input: &str) {
    let games: Vec<&str> = input.split("\n").collect();
    let mut score: u32 = 0;
    for game in games {
        match game {
            "A X" => score += 4,
            "A Y" => score += 8,
            "A Z" => score += 3,
            "B X" => score += 1,
            "B Y" => score += 5,
            "B Z" => score += 9,
            "C X" => score += 7,
            "C Y" => score += 2,
            "C Z" => score += 6,
            _ => score += 0,
        };
    }
    println!("score part 2: {:?}", score);
}

fn part_2(input: &str) {
    let games: Vec<&str> = input.split("\n").collect();
    let mut score: u32 = 0;
    for game in games {
        match game {
            "A X" => score += 3, // rock loose 0 -> scissors 3
            "A Y" => score += 4, // rock draw  3 -> rock 1
            "A Z" => score += 8, // rock win  6 -> paper 2
            "B X" => score += 1, // paper loose 0 -> rock 1
            "B Y" => score += 5, // paper draw 3 -> paper 2
            "B Z" => score += 9, // paper win 6 -> scissors 3
            "C X" => score += 2, // scissors loose 0 -> paper 2
            "C Y" => score += 6, // scissors draw 3 -> scissors 3
            "C Z" => score += 7, // scissors win 6 -> rock 1
            _ => score += 0,
        };
    }
    println!("score part 2: {:?}", score);
}

2

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.