Skip to content

Commit 148bc97

Browse files
committed
Add problem 2778: Sum of Squares of Special Elements
1 parent 5ac2e80 commit 148bc97

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1964,6 +1964,7 @@ pub mod problem_2765_longest_alternating_subarray;
19641964
pub mod problem_2766_relocate_marbles;
19651965
pub mod problem_2769_find_the_maximum_achievable_number;
19661966
pub mod problem_2771_longest_non_decreasing_subarray_from_two_arrays;
1967+
pub mod problem_2778_sum_of_squares_of_special_elements;
19671968

19681969
#[cfg(test)]
19691970
mod test_utilities;
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn sum_of_squares(nums: Vec<i32>) -> i32 {
7+
let n = nums.len() as u32;
8+
9+
(1..)
10+
.zip(nums)
11+
.filter(|&(i, _)| n % i == 0)
12+
.map(|(_, num)| num * num)
13+
.sum()
14+
}
15+
}
16+
17+
// ------------------------------------------------------ snip ------------------------------------------------------ //
18+
19+
impl super::Solution for Solution {
20+
fn sum_of_squares(nums: Vec<i32>) -> i32 {
21+
Self::sum_of_squares(nums)
22+
}
23+
}
24+
25+
#[cfg(test)]
26+
mod tests {
27+
#[test]
28+
fn test_solution() {
29+
super::super::tests::run::<super::Solution>();
30+
}
31+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn sum_of_squares(nums: Vec<i32>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(&[1, 2, 3, 4] as &[_], 21), (&[2, 7, 1, 19, 18, 3], 63)];
13+
14+
for (nums, expected) in test_cases {
15+
assert_eq!(S::sum_of_squares(nums.to_vec()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)