Skip to content

Commit

Permalink
Add problem 2367: Number of Arithmetic Triplets
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 23, 2024
1 parent 29d869a commit 322b6b1
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1761,6 +1761,7 @@ pub mod problem_2363_merge_similar_items;
pub mod problem_2364_count_number_of_bad_pairs;
pub mod problem_2365_task_scheduler_ii;
pub mod problem_2366_minimum_replacements_to_sort_the_array;
pub mod problem_2367_number_of_arithmetic_triplets;

#[cfg(test)]
mod test_utilities;
38 changes: 38 additions & 0 deletions src/problem_2367_number_of_arithmetic_triplets/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 {
let double_diff = diff + diff;
let mut seen = [false; 201];
let mut result = 0;

for num in nums {
seen[num as u32 as usize] = true;

result += i32::from(
seen.get((num - double_diff) as usize)
.map_or(false, |&first| first && seen[(num - diff) as usize]),
);
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 {
Self::arithmetic_triplets(nums, diff)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2367_number_of_arithmetic_triplets/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [((&[0, 1, 4, 6, 7, 10] as &[_], 3), 2), ((&[4, 5, 6, 7, 8, 9], 2), 2)];

for ((nums, diff), expected) in test_cases {
assert_eq!(S::arithmetic_triplets(nums.to_vec(), diff), expected);
}
}
}

0 comments on commit 322b6b1

Please sign in to comment.