Skip to content

Commit

Permalink
Add a few Codility solutions in Rust
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuamegnauth54 committed May 17, 2024
1 parent 9620bb5 commit aa9b38a
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Rust/jobspls/src/codility.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod binary_gap;
pub mod rotate_slice;
pub mod smallest_pos_int;
44 changes: 44 additions & 0 deletions Rust/jobspls/src/codility/binary_gap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::{cmp, fmt};

use num::Integer;

pub fn binary_gap<I>(num: I) -> usize
where
I: Integer + fmt::Binary,
{
let binary = format!("{num:b}");
binary
.chars()
.fold((0, 0), |(current, min), ch| {
if ch == '1' {
(0, cmp::max(current, min))
} else {
assert_eq!(ch, '0');
(current + 1, min)
}
})
.1
}

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

#[test]
fn zero_case_binary_gap() {
let gap = binary_gap(0);
assert_eq!(0, gap);
}

#[test]
fn gaps_to_end() {
let gap = binary_gap(9);
assert_eq!(2, gap);
}

#[test]
fn i32_max_gap() {
let gap = binary_gap(i32::MAX);
assert_eq!(0, gap);
}
}
46 changes: 46 additions & 0 deletions Rust/jobspls/src/codility/rotate_slice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
pub fn rotate_slice<'slice, T: Clone>(
slice: &'slice [T],
by: usize,
) -> impl Iterator<Item = T> + 'slice {
slice
.iter()
.cloned()
.cycle()
.skip(slice.len().abs_diff(by) % slice.len())
.take(slice.len())
}

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

#[test]
fn simple_shift_works() {
let slice = [4, 9, 11, 6];

let actual = rotate_slice(&slice, 1);
let expected = [6, 4, 9, 11];

assert!(actual.eq(expected));
}

#[test]
fn zero_shift_works() {
let slice = [6, 7, 8, 9];

let actual = rotate_slice(&slice, 0);
let expected = slice;

assert!(actual.eq(expected));
}

#[test]
fn over_shift_works() {
let slice = [3, 4, 5, 6];

let actual = rotate_slice(&slice, 6);
let expected = [5, 6, 3, 4];

assert!(actual.eq(expected));
}
}
14 changes: 14 additions & 0 deletions Rust/jobspls/src/codility/smallest_pos_int.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use std::{collections::BTreeSet, iter};

use num::{CheckedAdd, FromPrimitive, Integer};

pub fn smallest_pos_int<I>(haystack: &[I]) -> Option<I>
where
I: Integer + CheckedAdd + FromPrimitive + Copy,
{
let hayset = BTreeSet::from_iter(haystack.iter().copied());
iter::successors(I::from_u8(1), |next| {
next.checked_add(&I::from_u8(1).unwrap())
})
.find(|val| !hayset.contains(val))
}
1 change: 1 addition & 0 deletions Rust/jobspls/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod codility;
pub mod neet;
pub mod search;

0 comments on commit aa9b38a

Please sign in to comment.