Guest User

Untitled

a guest
Jul 21st, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. trait SliceExt<T> {
  2. fn split_by<F>(&self, pred: F) -> (&[T], &[T])
  3. where
  4. F: FnMut(&T) -> bool;
  5. }
  6.  
  7. impl<T> SliceExt<T> for [T] {
  8. fn split_by<F>(&self, mut pred: F) -> (&[T], &[T])
  9. where
  10. F: FnMut(&T) -> bool,
  11. {
  12. let p = self
  13. .iter()
  14. .enumerate()
  15. .find(|&(_, val)| !pred(val))
  16. .map(|(pos, _)| pos)
  17. .unwrap_or_else(|| self.len());
  18.  
  19. self.split_at(p)
  20. }
  21. }
  22.  
  23. #[test]
  24. fn test_split_by() {
  25. assert!([].split_by(|x: &i32| *x < 10) == (&[], &[]));
  26. assert!([1].split_by(|&x| x < 10) == (&[1], &[]));
  27. assert!([1, 11].split_by(|&x| x < 10) == (&[1], &[11]));
  28. assert!([1, 2, 10, 11].split_by(|&x| x < 10) == (&[1, 2], &[10, 11]));
  29. assert!([11].split_by(|&x| x < 10) == (&[], &[11]));
  30. }
  31.  
  32. fn check_bst(v: &[u32]) -> bool {
  33. if v.len() < 2 {
  34. return true;
  35. }
  36.  
  37. let first = v[0];
  38. let (left, right) = &v[1..].split_by(|&val| val <= first);
  39.  
  40. if right.iter().any(|&x| x < first) {
  41. return false;
  42. }
  43.  
  44. check_bst(left) && check_bst(right)
  45. }
  46.  
  47. fn main() {
  48. assert!(check_bst(&[]));
  49. assert!(check_bst(&[3]));
  50. assert!(check_bst(&[3, 1, 2]));
  51. assert!(check_bst(&[3, 2, 1, 4]));
  52. assert!(check_bst(&[3, 4]));
  53. assert!(!check_bst(&[3, 4, 1, 2]));
  54. }
Add Comment
Please, Sign In to add comment