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