Last active
January 5, 2024 12:43
-
-
Save skjalgsm/d566ae109589c694f1ce4d538cd98b16 to your computer and use it in GitHub Desktop.
Advent of code day 1 part1 rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tracing; | |
use std::fs; | |
use miette::Result; | |
use crate::aoc_error; | |
pub fn main() { | |
let contents = fs::read_to_string("2023-day-01-part1") | |
.expect("Should have been able to read the file"); | |
let result = calculate(contents); //55172 | |
match result { | |
Ok(v) => println!("Result is: {v:?}"), | |
Err(e) => println!("Error!: {e:?}") | |
} | |
} | |
#[tracing::instrument] | |
fn calculate(input : String) -> Result<u32, aoc_error::AoCError> { | |
let mut sum = 0; | |
let lines = input.lines(); | |
for line in lines { | |
let mut first = 10; | |
let mut last = 10; | |
let length = line.len(); | |
let chars: Vec<char> = line.chars().collect(); | |
for first_index in 0..chars.len() { | |
if first == 10 { | |
let first_char = chars[first_index]; | |
let first_digit = first_char.to_digit(10); | |
match first_digit { | |
None => {} | |
Some(value) => { | |
first = value; | |
} | |
} | |
} | |
if last == 10 { | |
let last_index = (length - 1) - first_index; | |
let last_char = chars[last_index]; | |
let last_digit = last_char.to_digit(10); | |
match last_digit { | |
None => {} | |
Some(value) => { | |
last = value; | |
} | |
} | |
} | |
} | |
let number = first * 10 + last; | |
sum += number; | |
//dbg!(number); | |
} | |
return Result::<u32, aoc_error::AoCError>::Ok(sum); | |
} | |
#[test] | |
fn it_works() -> Result<()> { | |
let input = "1abc2 //12 | |
pqr3stu8vwx //38 | |
a1b2c3d4e5f //15 | |
treb7uchet"; // 77 | |
assert_eq!(142, calculate(input.to_string())?); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment