Skip to content

Commit

Permalink
Add problem 0278: First Bad Version
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed May 12, 2024
1 parent 9051ace commit e46195b
Show file tree
Hide file tree
Showing 3 changed files with 68 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 @@ -277,6 +277,7 @@ pub mod problem_0260_single_number_iii;
pub mod problem_0268_missing_number;
pub mod problem_0274_h_index;
pub mod problem_0275_h_index_ii;
pub mod problem_0278_first_bad_version;
pub mod problem_0283_move_zeroes;
pub mod problem_0290_word_pattern;
pub mod problem_0299_bulls_and_cows;
Expand Down
44 changes: 44 additions & 0 deletions src/problem_0278_first_bad_version/binary_search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use super::Solution as _;

pub struct Solution {
bad: i32,
}

impl Solution {
pub fn first_bad_version(&self, n: i32) -> i32 {
let mut left = 1;
let mut right = n;
while left < right {
let mid = (right - left) / 2 + left;
if self.isBadVersion(mid) {
right = mid;
} else {
left = mid + 1;
}
}
right
}
}

impl super::Solution for Solution {
fn new(bad: i32) -> Self {
Self { bad }
}

#[allow(non_snake_case)] // Expected.
fn isBadVersion(&self, version: i32) -> bool {
version >= self.bad
}

fn first_bad_version(&self, n: i32) -> i32 {
self.first_bad_version(n)
}
}

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

pub trait Solution {
fn new(bad: i32) -> Self;

#[allow(non_snake_case)] // Expected.
fn isBadVersion(&self, version: i32) -> bool;

fn first_bad_version(&self, n: i32) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [((5, 4), 4), ((1, 1), 1)];

for ((n, bad), expected) in test_cases {
assert_eq!(S::new(bad).first_bad_version(n), expected);
}
}
}

0 comments on commit e46195b

Please sign in to comment.