Skip to content

Latest commit

 

History

History
66 lines (54 loc) · 1.53 KB

File metadata and controls

66 lines (54 loc) · 1.53 KB

858. Mirror Reflection

There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.

The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.

Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.)

Example 1:

Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.

Note:

  1. 1 <= p <= 1000
  2. 0 <= q <= p

Solutions (Ruby)

1. Mathematical

# @param {Integer} p
# @param {Integer} q
# @return {Integer}
def mirror_reflection(p, q)
    a, b = p, q

    while b != 0
        a, b = b, a % b
    end

    if p / a % 2 == 0
        return 2
    elsif q / a % 2 == 0
        return 0
    else
        return 1
    end
end

Solutions (Rust)

1. Mathematical

impl Solution {
    pub fn mirror_reflection(p: i32, q: i32) -> i32 {
        let mut a = p;
        let mut b = q;

        while b != 0 {
            let tmp = b;
            b = a % b;
            a = tmp;
        }

        match (p / a % 2, q / a % 2) {
            (0, _) => 2,
            (1, 0) => 0,
            (_, _) => 1,
        }
    }
}