Drill

ProblemsGo › warmup

Break a list into fixed-size pieces

mediumwarmupArraysGo

A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.

chunkList(values: list<int>, perChunk: int) → list<list<int>>

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func chunkList(values []int, perChunk int) [][]int {
	
}

Worked examples

CallResult
chunkList([]int{1, 2, 3, 4, 5}, 2)[][]int{[]int{1, 2}, []int{3, 4}, []int{5}}
chunkList([]int{1, 2, 3, 4}, 2)[][]int{[]int{1, 2}, []int{3, 4}}
chunkList([]int{1}, 5)[][]int{[]int{1}}
chunkList([]int{}, 2)[][]int{}

Hint

Step the index forward by the chunk size and slice, rather than pushing one item at a time.

Reference solution in Go
func chunkList(values []int, perChunk int) [][]int {
	result := [][]int{}
	if perChunk <= 0 {
		return result
	}
	for i := 0; i < len(values); i += perChunk {
		j := i + perChunk
		if j > len(values) {
			j = len(values)
		}
		result = append(result, append([]int{}, values[i:j]...))
	}
	return result
}

The same problem in another language

More warmup problems in Go