//! 266. Striding with step_by()
//!
//! `step_by(n)` yields every nth element โ the first, then skips n-1, and so on.
fn main() {
let thirds: Vec<usize> = (0..10).step_by(3).collect();
println!("Every 3rd (0..10): {:?}", thirds);
let mult5: Vec<i32> = (0..=50).step_by(5).collect();
println!("Multiples of 5: {:?}", mult5);
let signal = [1.0f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
let downsampled: Vec<f64> = signal.iter().copied().step_by(2).collect();
println!("Downsampled: {:?}", downsampled);
let s = "abcdefgh";
let every_other: String = s.chars().step_by(2).collect();
println!("Every other char: {}", every_other);
// Infinite sequence striding
let odd_positions: Vec<u64> = (1u64..).step_by(2).take(5).collect();
println!("Odd positions: {:?}", odd_positions);
}
#[cfg(test)]
mod tests {
#[test]
fn test_step_by_3() {
let result: Vec<usize> = (0..10).step_by(3).collect();
assert_eq!(result, vec![0, 3, 6, 9]);
}
#[test]
fn test_step_by_2() {
let result: Vec<i32> = [1, 2, 3, 4, 5].iter().copied().step_by(2).collect();
assert_eq!(result, vec![1, 3, 5]);
}
#[test]
fn test_step_by_1_identity() {
let result: Vec<i32> = (1..=4).step_by(1).collect();
assert_eq!(result, vec![1, 2, 3, 4]);
}
#[test]
fn test_step_by_multiples() {
let result: Vec<i32> = (0..=20).step_by(5).collect();
assert_eq!(result, vec![0, 5, 10, 15, 20]);
}
}
(* 266. Striding with step_by() - OCaml *)
let step_by n lst = List.filteri (fun i _ -> i mod n = 0) lst
let () =
let nums = List.init 10 Fun.id in
let thirds = step_by 3 nums in
Printf.printf "Every 3rd: %s\n"
(String.concat ", " (List.map string_of_int thirds));
let mult_5 = step_by 5 (List.init 51 Fun.id) in
Printf.printf "Multiples of 5: %s\n"
(String.concat ", " (List.map string_of_int mult_5));
let s = "abcdefgh" in
let chars = List.init (String.length s) (fun i -> s.[i]) in
let every_other = step_by 2 chars in
Printf.printf "Every other char: %s\n"
(String.concat "" (List.map (String.make 1) every_other))