2023-11-29 10:39:24 -05:00
|
|
|
// Copyright 2023 Google LLC
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
#![allow(dead_code)]
|
|
|
|
|
|
|
|
// ANCHOR: solution
|
|
|
|
// ANCHOR: offset_differences
|
2023-12-31 00:15:07 +01:00
|
|
|
/// Calculate the differences between elements of `values` offset by `offset`,
|
|
|
|
/// wrapping around from the end of `values` to the beginning.
|
2023-11-29 10:39:24 -05:00
|
|
|
///
|
|
|
|
/// Element `n` of the result is `values[(n+offset)%len] - values[n]`.
|
2024-10-15 16:14:50 +02:00
|
|
|
fn offset_differences(offset: usize, values: Vec<i32>) -> Vec<i32> {
|
2023-11-29 10:39:24 -05:00
|
|
|
// ANCHOR_END: offset_differences
|
2024-12-16 12:22:44 -08:00
|
|
|
let a = values.iter();
|
|
|
|
let b = values.iter().cycle().skip(offset);
|
2024-03-06 20:18:31 +00:00
|
|
|
a.zip(b).map(|(a, b)| *b - *a).collect()
|
2023-11-29 10:39:24 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// ANCHOR: unit-tests
|
|
|
|
#[test]
|
|
|
|
fn test_offset_one() {
|
|
|
|
assert_eq!(offset_differences(1, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
|
|
|
|
assert_eq!(offset_differences(1, vec![1, 3, 5]), vec![2, 2, -4]);
|
|
|
|
assert_eq!(offset_differences(1, vec![1, 3]), vec![2, -2]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_larger_offsets() {
|
|
|
|
assert_eq!(offset_differences(2, vec![1, 3, 5, 7]), vec![4, 4, -4, -4]);
|
|
|
|
assert_eq!(offset_differences(3, vec![1, 3, 5, 7]), vec![6, -2, -2, -2]);
|
|
|
|
assert_eq!(offset_differences(4, vec![1, 3, 5, 7]), vec![0, 0, 0, 0]);
|
|
|
|
assert_eq!(offset_differences(5, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_degenerate_cases() {
|
|
|
|
assert_eq!(offset_differences(1, vec![0]), vec![0]);
|
|
|
|
assert_eq!(offset_differences(1, vec![1]), vec![0]);
|
|
|
|
let empty: Vec<i32> = vec![];
|
|
|
|
assert_eq!(offset_differences(1, empty), vec![]);
|
|
|
|
}
|
|
|
|
// ANCHOR_END: unit-tests
|