// 093: Windows and Chunks
fn main() {
let v = vec![1, 2, 3, 4, 5];
// windows (overlapping)
let wins: Vec<&[i32]> = v.windows(3).collect();
println!("windows(3): {:?}", wins);
// chunks (non-overlapping)
let chs: Vec<&[i32]> = v.chunks(2).collect();
println!("chunks(2): {:?}", chs);
}
#[cfg(test)]
mod tests {
#[test]
fn test_windows() {
let v = vec![1, 2, 3, 4, 5];
let w: Vec<&[i32]> = v.windows(3).collect();
assert_eq!(w, vec![&[1,2,3][..], &[2,3,4][..], &[3,4,5][..]]);
}
#[test]
fn test_windows_2() {
let v = vec![1, 2, 3];
let w: Vec<&[i32]> = v.windows(2).collect();
assert_eq!(w, vec![&[1,2][..], &[2,3][..]]);
}
#[test]
fn test_chunks() {
let v = vec![1, 2, 3, 4, 5];
let c: Vec<&[i32]> = v.chunks(2).collect();
assert_eq!(c, vec![&[1,2][..], &[3,4][..], &[5][..]]);
}
#[test]
fn test_chunks_exact() {
let v = vec![1, 2, 3, 4, 5, 6];
let c: Vec<&[i32]> = v.chunks(3).collect();
assert_eq!(c, vec![&[1,2,3][..], &[4,5,6][..]]);
}
}
(* 093: Windows and Chunks *)
let windows n lst =
let rec aux acc = function
| [] -> List.rev acc
| _ :: rest as l ->
let window = List.filteri (fun i _ -> i < n) l in
if List.length window = n then aux (window :: acc) rest
else List.rev acc
in
aux [] lst
let chunks n lst =
let rec aux acc current count = function
| [] -> List.rev (if current = [] then acc else List.rev current :: acc)
| x :: xs ->
if count = n then aux (List.rev current :: acc) [x] 1 xs
else aux acc (x :: current) (count + 1) xs
in
aux [] [] 0 lst
(* Tests *)
let () =
assert (windows 3 [1;2;3;4;5] = [[1;2;3];[2;3;4];[3;4;5]]);
assert (windows 2 [1;2;3] = [[1;2];[2;3]]);
assert (chunks 2 [1;2;3;4;5] = [[1;2];[3;4];[5]]);
assert (chunks 3 [1;2;3;4;5;6] = [[1;2;3];[4;5;6]]);
Printf.printf "โ All tests passed\n"