From 2bf902b161e91e8e95bdc0ac9ad61bbd22300826 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 6 Jun 2023 10:42:37 +0200 Subject: [PATCH] =?UTF-8?q?problems(rs):=20add=20=E2=80=9C1502.=20Can=20Ma?= =?UTF-8?q?ke=20Arithmetic=20Progression=20From=20Sequence=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...ke-arithmetic-progression-from-sequence.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 problems/rs/can-make-arithmetic-progression-from-sequence.rs diff --git a/problems/rs/can-make-arithmetic-progression-from-sequence.rs b/problems/rs/can-make-arithmetic-progression-from-sequence.rs new file mode 100644 index 0000000..208fe7f --- /dev/null +++ b/problems/rs/can-make-arithmetic-progression-from-sequence.rs @@ -0,0 +1,31 @@ +struct Solution {} +impl Solution { + pub fn can_make_arithmetic_progression(mut arr: Vec) -> bool { + arr.sort(); + let diffs: Vec = arr.windows(2).map(|pair| pair[1] - pair[0]).collect(); + diffs.windows(2).all(|pair| pair[0] == pair[1]) + } +} + +fn main() {} + +#[cfg(test)] +mod tests { + use super::*; + + // Input: arr = [3,5,1] + // Output: true + // Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. + #[test] + fn example_1() { + assert!(Solution::can_make_arithmetic_progression(vec![3, 5, 1])); + } + + // Input: arr = [1,2,4] + // Output: false + // Explanation: There is no way to reorder the elements to obtain an arithmetic progression. + #[test] + fn example_2() { + assert!(!Solution::can_make_arithmetic_progression(vec![2, 4, 1])); + } +}