Skip to content

Instantly share code, notes, and snippets.

@JulianBirch
Last active March 20, 2021 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JulianBirch/9b55f626b24ae85fd53427358efc9d93 to your computer and use it in GitHub Desktop.
Save JulianBirch/9b55f626b24ae85fd53427358efc9d93 to your computer and use it in GitHub Desktop.
// Broken version
use std::convert::TryInto;
impl Solution {
pub fn find_smallest_interval<T, F>(elements : &Vec<T>, predicate : F)
-> Option<(usize, usize)>
where F : Fn(&T, &T) -> bool {
let mut minLength = elements.len();
let mut result = None;
for i in 0..elements.len() {
let start = &elements[i];
let mut j = i;
let mut length = j - i;
while (j < elements.len() && length < minLength) {
// Why does indexing not return an Option?
// println!("i {i} j {j} sum {sum}", i=i, j=j, sum=end-start);
if (predicate(start, &elements[j])) {
minLength = length;
result = Some((i, j));
}
j += 1;
length += 1;
}
}
return result;
}
pub fn min_subarray(nums: Vec<i32>, p: i32) -> i32 {
let fullLength = nums.len();
let mut xs = nums.into_iter();
// Honestly I don't really understand the next two lines, I grabbed them
// off the internet
let vsx = std::iter::successors(Some(0), |acc| xs.next().map(|n| (n + *acc).rem_euclid(p)));
let numSum = vsx.collect::<Vec<_>>();
let valueToRemove = *numSum.last().unwrap_or(&0);
if (valueToRemove == 0) {
return 0;
}
// Black magic here
// println!("List {:?}", numSum);
// println!("Sum {0} Seeking {1}", numSum.last().unwrap_or(&0), valueToRemove);
let test
= |&x, &y| (valueToRemove == x - y || valueToRemove == x - y + p);
let interval = Self::find_smallest_interval(&numSum, test);
let length = interval
.and_then(|(x, y)| (x - y).try_into().ok())
.unwrap_or(-1);
return if length == fullLength {-1} else {length};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment