Skip to content

Commit

Permalink
Add problem 1871: Jump Game VII
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed May 1, 2024
1 parent b780f2b commit 00fbe40
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 @@ -1392,6 +1392,7 @@ pub mod problem_1865_finding_pairs_with_a_certain_sum;
pub mod problem_1866_number_of_ways_to_rearrange_sticks_with_k_sticks_visible;
pub mod problem_1869_longer_contiguous_segments_of_ones_than_zeros;
pub mod problem_1870_minimum_speed_to_arrive_on_time;
pub mod problem_1871_jump_game_vii;
pub mod problem_1876_substrings_of_size_three_with_distinct_characters;
pub mod problem_1877_minimize_maximum_pair_sum_in_array;
pub mod problem_1880_check_if_word_equals_summation_of_two_words;
Expand Down
18 changes: 18 additions & 0 deletions src/problem_1871_jump_game_vii/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod sliding_window;

pub trait Solution {
fn can_reach(s: String, min_jump: i32, max_jump: i32) -> bool;
}

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

pub fn run<S: Solution>() {
let test_cases = [(("011010", 2, 3), true), (("01101110", 2, 3), false)];

for ((s, min_jump, max_jump), expected) in test_cases {
assert_eq!(S::can_reach(s.to_string(), min_jump, max_jump), expected);
}
}
}
49 changes: 49 additions & 0 deletions src/problem_1871_jump_game_vii/sliding_window.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
pub struct Solution;

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

use std::cell::Cell;

impl Solution {
pub fn can_reach(s: String, min_jump: i32, max_jump: i32) -> bool {
let mut s = s.into_bytes();
let min_jump = min_jump as u32 as usize;
let max_jump = max_jump as u32 as usize;

s[1..min_jump].fill(b'1');

let mut count = 0;

for &c in &s[..=max_jump - min_jump] {
count += u32::from(b'1' - c);
}

let s = Cell::from_mut(s.as_mut_slice()).as_slice_of_cells();

for ((old, new), target) in s.iter().zip(&s[max_jump - min_jump + 1..]).zip(&s[max_jump + 1..]) {
count = count.wrapping_add(i32::from(old.get().wrapping_sub(new.get()) as i8) as u32);

if target.get() == b'0' {
target.set(b'1' - u8::from(count != 0));
}
}

s.last().unwrap().get() == b'0'
}
}

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

impl super::Solution for Solution {
fn can_reach(s: String, min_jump: i32, max_jump: i32) -> bool {
Self::can_reach(s, min_jump, max_jump)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 00fbe40

Please sign in to comment.