Hi,
This might be more of a math problem, but since I need to solve in Go, I hope someone could help me out here.
Say you have a sorted slice (of any length)
mySlice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}
you know want to split it into smaller slices, as evenly as possible, which each sub-slice not exceeding a given length.
Slicing a slice is rather easy to do with:
func slicing(s []int, n int) [][]int {
var res [][]int
for {
if len(s) == 0 {
break
}
if len(s) < n {
n = len(s)
}
res = append(res, s[0:n])
s = s[n:]
}
return res
}
However this implies that you know already what would be the value on n
so that the lengths of the sub-slice are as evenly as possible.
Just to take make an example if I do
slicing(mySlice, 4)
the result of slicing
is [[1 2 3 4] [5 6 7 8] [9 10 11 12] [13 14 15 16] [17 18 19 20] [21]]
which would not be correct, since we have 5 slice of length 4 and 1 slice of length 1, while the “more even” slicing should be [[1 2 3 4] [5 6 7 8] [9 10 11 12] [13 14 15] [16 17 18] [19 20 21]]
(4+4+4+3+3+3)
Again, for
slicing(mySlice, 8)
you get [[1 2 3 4 5 6 7 8] [9 10 11 12 13 14 15 16] [17 18 19 20 21]]
, while the “more even” result would be [[1 2 3 4 5 6 7] [8 9 10 11 12 13 14] [15 16 17 18 19 20 21]]
(7+7+7)
for
slicing(mySlice, 6)
[[1 2 3 4 5 6] [7 8 9 10 11 12] [13 14 15 16 17 18] [19 20 21]]
→ [[1 2 3 4 5 6] [7 8 9 10 11] [12 13 14 15 16] [17 18 19 20 21]]
(6+5+5+5)
Any suggestion?