Solution

  1. /// Calculate the differences between elements of `values` offset by `offset`,
  2. /// wrapping around from the end of `values` to the beginning.
  3. ///
  4. /// Element `n` of the result is `values[(n+offset)%len] - values[n]`.
  5. fn offset_differences(offset: usize, values: Vec<i32>) -> Vec<i32> {
  6.     let a = (&values).into_iter();
  7.     let b = (&values).into_iter().cycle().skip(offset);
  8.     a.zip(b).map(|(a, b)| *b - *a).collect()
  9. }
  10. #[test]
  11. fn test_offset_one() {
  12.     assert_eq!(offset_differences(1, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
  13.     assert_eq!(offset_differences(1, vec![1, 3, 5]), vec![2, 2, -4]);
  14.     assert_eq!(offset_differences(1, vec![1, 3]), vec![2, -2]);
  15. }
  16. #[test]
  17. fn test_larger_offsets() {
  18.     assert_eq!(offset_differences(2, vec![1, 3, 5, 7]), vec![4, 4, -4, -4]);
  19.     assert_eq!(offset_differences(3, vec![1, 3, 5, 7]), vec![6, -2, -2, -2]);
  20.     assert_eq!(offset_differences(4, vec![1, 3, 5, 7]), vec![0, 0, 0, 0]);
  21.     assert_eq!(offset_differences(5, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
  22. }
  23. #[test]
  24. fn test_degenerate_cases() {
  25.     assert_eq!(offset_differences(1, vec![0]), vec![0]);
  26.     assert_eq!(offset_differences(1, vec![1]), vec![0]);
  27.     let empty: Vec<i32> = vec![];
  28.     assert_eq!(offset_differences(1, empty), vec![]);
  29. }
  30. fn main() {}