Yekong's Blog

A blog about my experiences and thoughts.

Description

Given a number with ‘L’ or ‘R’ characters, you need to calculate how many times the pointer moves to zero after this step

Second question of this day also calculate same things, but the different is you also need to count how many times the pointer passes through zero

The pointer starts at 50, command ‘L’ means move left, ‘R’ means move right

L45 Position after moving is 5

R95 Position after moving is 0

Test case contains number that is bigger than 100

Code

// NOTE: This code is for Day 1 second question

let content = File::open("input")?;
let reader = BufReader::new(content);

let mut dial_num: i64 = 50;
let mut dial_is_0: i64 = 0;

for line in reader.lines() {
    let line = line?;
    let line = line.trim();

    let line = line.split_at(1);
    let command = line.0;
    let mut numbers = line.1.parse::<i64>().unwrap();

    if numbers >= 100 {
        dial_is_0 += numbers / 100;
        numbers %= 100;
    }

    // println!("{} {} {} {}", command, numbers, dial_num, dial_is_0);
    match command {
        "L" => {
            if dial_num > numbers {
                dial_num -= numbers;
            } else if dial_num == numbers {
                dial_num = 0;
                dial_is_0 += 1;
            } else if dial_num == 0 {
                // Prevent count double
                dial_num = 100 - numbers;
            } else {
                dial_num = 100 - (numbers - dial_num);
                if dial_num == 0 {
                    dial_is_0 += 1;
                } else {
                    dial_is_0 += 1;
                }
            }
        }
        "R" => {
            if dial_num + numbers < 100 {
                dial_num += numbers;
            } else if dial_num + numbers == 100 {
                dial_num = 0;
                dial_is_0 += 1;
            } else if dial_num == 0 {
                // Prevent count double
                dial_num = numbers;
            } else {
                dial_num = numbers - (100 - dial_num);
                if dial_num == 0 {
                    dial_is_0 += 1;
                } else {
                    dial_is_0 += 1;
                }
            }
        }
        _ => return Err(Box::new(Err::UnknownMassParsingError)),
    }
}

println!("{}", dial_is_0);