簡単 0件解決済み 正答率0%

Split a List Into Chunks

Cut a list into consecutive groups of a fixed size, with a shorter last group if needed.

このチャレンジで学べること

  • Step through a list in fixed-size jumps
  • Take slices that may be shorter at the end
  • Group data for paging or batch processing

問題

翻訳を表示

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.

制約

0 ≤ number of values ≤ 10,000

1 ≤ size ≤ 10,000

例

例 1
入力:
size = 3
values = [1, 2, 3, 4, 5, 6, 7]

期待される出力:
expected = [
    [1, 2, 3],
    [4, 5, 6],
    [7]
]
入力:
long long size = 3;
std::vector<long long> values = {1, 2, 3, 4, 5, 6, 7};

期待される出力:
std::vector<std::vector<long long>> expected = {
    {1, 2, 3},
    {4, 5, 6},
    {7}
};
入力:
long size = 3;
long[] values = new long[] {1, 2, 3, 4, 5, 6, 7};

期待される出力:
long[][] expected = new long[][] {
    new long[] {1, 2, 3},
    new long[] {4, 5, 6},
    new long[] {7}
};

解説

Groups of 3: [1, 2, 3] and [4, 5, 6], and the leftover 7 forms a last, shorter chunk.

例 2
入力:
size = 5
values = [8, 9]

期待される出力:
expected = [
    [8, 9]
]
入力:
long long size = 5;
std::vector<long long> values = {8, 9};

期待される出力:
std::vector<std::vector<long long>> expected = {
    {8, 9}
};
入力:
long size = 5;
long[] values = new long[] {8, 9};

期待される出力:
long[][] expected = new long[][] {
    new long[] {8, 9}
};

解説

The size is larger than the list, so everything fits in one chunk: [[8, 9]].

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Start positions are 0, size, 2·size, and so on.

ヒント 2

Take a slice from each start position up to start + size.

ヒント 3

The last slice may be shorter, and an empty list gives no chunks at all.

目安の計算量

O(n) time, O(n) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。