Problema
Splitting data into fixed-size chunks is how programs page results, batch database writes or send data in packets.
Given a list and a chunk size, cut the list into consecutive chunks of exactly size values, in order. The last chunk holds whatever is left and may be shorter.
Implement split_into_chunks(values, size).
Input
values: The list to split.
size: The chunk size.
Output
Return the list of chunks. An empty list gives no chunks.
Vincoli
0 ≤ number of values ≤ 10,000
1 ≤ size ≤ 10,000
Esempi
Input:
size = 3
values = [1, 2, 3, 4, 5, 6, 7]
Output atteso:
expected = [
[1, 2, 3],
[4, 5, 6],
[7]
]
Input:
long long size = 3;
std::vector<long long> values = {1, 2, 3, 4, 5, 6, 7};
Output atteso:
std::vector<std::vector<long long>> expected = {
{1, 2, 3},
{4, 5, 6},
{7}
};
Input:
long size = 3;
long[] values = new long[] {1, 2, 3, 4, 5, 6, 7};
Output atteso:
long[][] expected = new long[][] {
new long[] {1, 2, 3},
new long[] {4, 5, 6},
new long[] {7}
};
Spiegazione
Groups of 3: [1, 2, 3] and [4, 5, 6], and the leftover 7 forms a last, shorter chunk.
Input:
size = 5
values = [8, 9]
Output atteso:
expected = [
[8, 9]
]
Input:
long long size = 5;
std::vector<long long> values = {8, 9};
Output atteso:
std::vector<std::vector<long long>> expected = {
{8, 9}
};
Input:
long size = 5;
long[] values = new long[] {8, 9};
Output atteso:
long[][] expected = new long[][] {
new long[] {8, 9}
};
Spiegazione
The size is larger than the list, so everything fits in one chunk: [[8, 9]].
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Start positions are 0, size, 2·size, and so on.
Suggerimento 2
Take a slice from each start position up to start + size.
Suggerimento 3
The last slice may be shorter, and an empty list gives no chunks at all.
Complessità attesa
O(n) time, O(n) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.