slightly better chunks

This commit is contained in:
Niko Abeler 2022-11-25 20:11:55 +01:00
parent 2ceb9a413f
commit 6e99a71fde
1 changed files with 16 additions and 3 deletions

View File

@ -3,11 +3,18 @@ use std::ops::Range;
pub fn gen_chunks(n: usize, chunks: usize) -> Vec<Range<usize>> {
let mut borders = vec![];
let chunk_size = n / chunks;
let mut remainder = n % chunks;
let mut start = 0;
for _ in 0..chunks {
let end = start + chunk_size;
borders.push(start..end);
start = end;
if remainder > 0 {
remainder -= 1;
borders.push(start..end + 1);
start = end + 1;
} else {
borders.push(start..end);
start = end;
}
}
// Change the last chunk to include the remainder
let size = borders.len();
@ -22,7 +29,7 @@ mod test {
#[test]
fn test_gen_chunks() {
let borders = gen_chunks(10, 3);
assert_eq!(borders, vec![(0..3), (3..6), (6..10)]);
assert_eq!(borders, vec![(0..4), (4..7), (7..10)]);
}
#[test]
@ -36,4 +43,10 @@ mod test {
let borders = gen_chunks(10, 1);
assert_eq!(borders, vec![(0..10)]);
}
#[test]
fn test_gen_chunks4() {
let borders = gen_chunks(11, 3);
assert_eq!(borders, vec![(0..4), (4..8), (8..11)]);
}
}