-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2367: Number of Arithmetic Triplets
- Loading branch information
Showing
3 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
src/problem_2367_number_of_arithmetic_triplets/iterative.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |