Improved logging output

added unfinished alternative for 2022/2
added docs for 2022/2

Signed-off-by: TuDatTr <tuan-dat.tran@tudattr.dev>
main
TuDatTr 2022-12-02 11:51:37 +01:00
parent 8cd8032741
commit 57a95b7c34
8 changed files with 132 additions and 21 deletions

View File

@ -0,0 +1 @@
/input.txt

View File

@ -0,0 +1,34 @@
def calc(u1, u2):
if u1 == u2:
print(f'{chr(u1+ord("A")-1)} {chr(u2+ord("X")-1)} draw')
return u2 + 3
elif u1 == (u2 % 3 - 1):
print(f'{chr(u1+ord("A")-1)} {chr(u2+ord("X")-1)} win')
return u2 + 6
else:
print(f'{chr(u1+ord("A")-1)} {chr(u2+ord("X")-1)} loss')
return u2 + 0
def test_2a(file):
res = []
for l in open(file, 'r').read().split('\n'):
if l:
a, b = l.split()
res.append(calc(*(ord(a) - ord("A") + 1, ord(b) - ord("X") + 1)))
res = sum(res)
print(res)
apprehension = task_2a(file)
assert res == apprehension
def task_2a(file):
numify = lambda a_b: (ord(a_b[0]) - ord("A") + 1, ord(a_b[1]) - ord("X") + 1)
return sum([calc(*numify(l.split())) for l in open(file, 'r').read().split('\n') if l])
def task_2b(file):
raise NotImplementedError
if __name__ == '__main__':
print(task_2a('input.txt'))
# print(task_2b('input.txt'))

View File

@ -0,0 +1,5 @@
Gave up for now, tried to solve the task more or less functionally/mathematically, but it didn't work out.
Related:
- [Calculus on finite weighted graphs](https://en.wikipedia.org/wiki/Calculus_on_finite_weighted_graphs)
- ![notes](whiteboard_notes.jpeg)

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

View File

@ -0,0 +1,14 @@
# Calorie Counting
Implementation of [this task](./task.md). I tried to do it idiomatically, but it quickly turned into a mess when part two was introduced.
<sub>I'm sensing a theme here</sub>
## Usage
`cargo run --release -- --input <Path to file with inputs>`
Alternative
```sh
cargo install --release .
rock_paper_scissors -i <Path to file with inputs>
```

View File

@ -1,4 +1,4 @@
use rock_paper_scissors_lib::{task_1a, task_1b}; use rock_paper_scissors_lib::{task_2a, task_2b};
use clap::Parser; use clap::Parser;
use tracing::debug; use tracing::debug;
@ -11,6 +11,6 @@ pub fn main() {
let args = Cli::parse(); let args = Cli::parse();
debug!("Args: {:?}", args); debug!("Args: {:?}", args);
println!("Result (1a): {}", task_1a(&args.input)); println!("Result (2a): {}", task_2a(&args.input));
println!("Result (1b): {}", task_1b(&args.input)); println!("Result (2b): {}", task_2b(&args.input));
} }

View File

@ -21,20 +21,20 @@ enum GameResult {
impl Choice { impl Choice {
fn win(i: &Choice, other: &Choice) -> GameResult { fn win(i: &Choice, other: &Choice) -> GameResult {
debug!("Get GameResult based on {}, {}", i, other); debug!("Get GameResult based on {}, {}", i, other);
info!("Get GameResult");
match (i, other) { let result = match (i, other) {
(Choice::Rock, Choice::Scissors) => GameResult::Win, (Choice::Rock, Choice::Scissors) => GameResult::Win,
(Choice::Paper, Choice::Rock) => GameResult::Win, (Choice::Paper, Choice::Rock) => GameResult::Win,
(Choice::Scissors, Choice::Paper) => GameResult::Win, (Choice::Scissors, Choice::Paper) => GameResult::Win,
_ if i == other => GameResult::Draw, _ if i == other => GameResult::Draw,
_ => GameResult::Loose _ => GameResult::Loose
} };
info!("GameResult: {}", &result);
result
} }
fn play(&self, other: &Choice) -> u64 { fn play(&self, other: &Choice) -> u64 {
debug!("Get score based on {}, {}", &self, other); debug!("Get score based on {}, {}", &self, other);
info!("Get score");
let hand_value = match self { let hand_value = match self {
Choice::Rock => 1, Choice::Rock => 1,
@ -47,21 +47,25 @@ impl Choice {
GameResult::Draw => 3, GameResult::Draw => 3,
GameResult::Loose => 0, GameResult::Loose => 0,
}; };
hand_value + game_value
let result = hand_value + game_value;
info!("Score: {}", &result);
result
} }
fn cheat(&self, outcome: &GameResult) -> u64 { fn cheat(&self, outcome: &GameResult) -> u64 {
debug!("Get score by cheating based on {}, {}", &self, outcome); debug!("Get score by cheating based on {}, {}", &self, outcome);
info!("Get score by cheating");
let user_choice = Choice::iter().filter(|c| &Choice::win(&c, &self) == outcome).next(); let user_choice = Choice::iter().filter(|c| &Choice::win(&c, &self) == outcome).next();
user_choice.unwrap().play(&self) let result =user_choice.unwrap().play(&self);
info!("Score: {}", result);
result
} }
} }
fn calculate_result_1a(line: &str) -> u64 { fn calculate_result_1a(line: &str) -> u64 {
debug!("Get score for 1a of game {}", line); debug!("Get score for 1a of game {}", line);
info!("Get score for 1a");
let mut input = line.chars(); let mut input = line.chars();
let opponent_choice = match input.next() { let opponent_choice = match input.next() {
@ -79,12 +83,13 @@ fn calculate_result_1a(line: &str) -> u64 {
Some('Z') => Choice::Scissors, Some('Z') => Choice::Scissors,
_ => Choice::Rock, _ => Choice::Rock,
}; };
user_choice.play(&opponent_choice) let result = user_choice.play(&opponent_choice);
info!("Total score (1a): {}", result);
result
} }
fn calculate_result_1b(line: &str) -> u64 { fn calculate_result_1b(line: &str) -> u64 {
debug!("Get score for 1b of game {}", line); debug!("Get score for 1b of game {}", line);
info!("Get score for 1b");
let mut input = line.chars(); let mut input = line.chars();
let opponent_choice = match input.next() { let opponent_choice = match input.next() {
@ -102,15 +107,21 @@ fn calculate_result_1b(line: &str) -> u64 {
Some('Z') => GameResult::Win, Some('Z') => GameResult::Win,
_ => GameResult::Loose, // Error handling, this shouldn't happen _ => GameResult::Loose, // Error handling, this shouldn't happen
}; };
opponent_choice.cheat(&outcome) let result = opponent_choice.cheat(&outcome);
info!("Total score (1b): {}", result);
result
} }
pub fn task_1a(input: &PathBuf) -> u64 { pub fn task_2a(input: &PathBuf) -> u64 {
let content = read_file(input).unwrap(); let content = read_file(input).unwrap();
content.split('\n').map(|l| calculate_result_1a(l)).sum() content.split('\n').map(|l| {
let r = calculate_result_1a(l);
info!("{}", r);
r
}).sum()
} }
pub fn task_1b(input: &PathBuf) -> u64 { pub fn task_2b(input: &PathBuf) -> u64 {
let content = read_file(input).unwrap(); let content = read_file(input).unwrap();
content.split('\n').map(|l| calculate_result_1b(l)).sum() content.split('\n').map(|l| calculate_result_1b(l)).sum()
} }
@ -125,10 +136,10 @@ mod tests {
const CONTENT: &str = "A Y\nB X\nC Z"; const CONTENT: &str = "A Y\nB X\nC Z";
#[test] #[test]
fn test_task_1a() { fn test_task_2a() {
let test_file = PathBuf::from(PATH); let test_file = PathBuf::from(PATH);
create_file(&test_file, CONTENT.to_string()); create_file(&test_file, CONTENT.to_string());
let result = task_1a(&test_file); let result = task_2a(&test_file);
let _ = remove_file(&test_file); let _ = remove_file(&test_file);
let expected = 15u64; let expected = 15u64;
@ -136,10 +147,10 @@ mod tests {
} }
#[test] #[test]
fn test_task_1b() { fn test_task_2b() {
let test_file = PathBuf::from(PATH); let test_file = PathBuf::from(PATH);
create_file(&test_file, CONTENT.to_string()); create_file(&test_file, CONTENT.to_string());
let result = task_1b(&test_file); let result = task_2b(&test_file);
let _ = remove_file(&test_file); let _ = remove_file(&test_file);
let expected = 12u64; let expected = 12u64;

View File

@ -0,0 +1,46 @@
# --- Day 2: Rock Paper Scissors ---
## --- Part One ---
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?**
### --- Part Two ---
The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!"
The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round ends as indicated. The example above now goes like this:
In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also choose Rock. This gives you a score of 1 + 3 = 4.
In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score of 1 + 0 = 1.
In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7.
Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12.
**Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide?**