diff --git a/src/problem/mod.rs b/src/problem/mod.rs index fcfa8d4..c6d2d93 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -29,4 +29,5 @@ mod p2765_longest_alternating_subarray; mod p2865_beautiful_towers_i; mod p2859_sum_of_values_at_indices_with_k_set_bits; mod p2846_minimum_edge_weight_equilibrium_queries_in_a_tree; -mod p2861_maximum_number_of_alloys; \ No newline at end of file +mod p2861_maximum_number_of_alloys; +mod p365_water_and_jug_problem; \ No newline at end of file diff --git a/src/problem/p365_water_and_jug_problem.rs b/src/problem/p365_water_and_jug_problem.rs new file mode 100644 index 0000000..61cc9b1 --- /dev/null +++ b/src/problem/p365_water_and_jug_problem.rs @@ -0,0 +1,47 @@ +/** + * [365] Water and Jug Problem + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn can_measure_water(jug1_capacity: i32, jug2_capacity: i32, target_capacity: i32) -> bool { + if jug1_capacity + jug2_capacity < target_capacity { + return false; + } + + if jug1_capacity == 0 || jug2_capacity == 0 { + return target_capacity == 0 || jug1_capacity + jug2_capacity == target_capacity; + } + + target_capacity % Solution::gcd(jug1_capacity, jug2_capacity) == 0 + } + + fn gcd(a: i32, b: i32) -> i32 { + let (mut a, mut b) = (a, b); + + while b > 0 { + let t = a % b; + a = b; + b = t; + } + + a + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_365() { + assert!(Solution::can_measure_water(3, 5, 4)); + assert!(!Solution::can_measure_water(2, 6, 5)); + assert!(Solution::can_measure_water(1,2,3)); + } +}