Skip to content

Commit

Permalink
Add problem 1866: Number of Ways to Rearrange Sticks With K Sticks Vi…
Browse files Browse the repository at this point in the history
…sible
  • Loading branch information
EFanZh committed Apr 29, 2024
1 parent 2ef00c7 commit 51296a2
Show file tree
Hide file tree
Showing 3 changed files with 65 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 @@ -1389,6 +1389,7 @@ pub mod problem_1862_sum_of_floored_pairs;
pub mod problem_1863_sum_of_all_subset_xor_totals;
pub mod problem_1864_minimum_number_of_swaps_to_make_the_binary_string_alternating;
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_1876_substrings_of_size_three_with_distinct_characters;
pub mod problem_1877_minimize_maximum_pair_sum_in_array;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
pub struct Solution;

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

impl Solution {
pub fn rearrange_sticks(n: i32, k: i32) -> i32 {
const MODULUS: u64 = 1_000_000_007;

let n = n as u32;
let k = k as u32;
let mut cache = vec![0_u64; k as _].into_boxed_slice();

*cache.last_mut().unwrap() = 1;

let (first, rest) = cache.split_first_mut().unwrap();

for x in 1..u64::from(n) {
let mut target = &mut *first;

for next in &mut *rest {
*target = (x * *target + *next) % MODULUS;
target = next;
}

*target = (x * *target) % MODULUS;
}

cache[0] as _
}
}

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

impl super::Solution for Solution {
fn rearrange_sticks(n: i32, k: i32) -> i32 {
Self::rearrange_sticks(n, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn rearrange_sticks(n: i32, k: i32) -> i32;
}

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

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

for ((n, k), expected) in test_cases {
assert_eq!(S::rearrange_sticks(n, k), expected);
}
}
}

0 comments on commit 51296a2

Please sign in to comment.