#C5576. Stream Processing

    ID: 49240 Type: Default 1000ms 256MiB

Stream Processing

Stream Processing

You are required to implement a custom Stream structure that simulates lazy evaluation by processing elements sequentially. The stream is initialized from an iterable (either a list of integers or a string). Your stream should support the following operations:

  • take n: Remove the next n elements from the stream and print them in order. If there are fewer than n elements, output all remaining elements (if none remain, print an empty line).
  • map: Transform each element in the stream. Two mapping operations are supported:
    • map square (for integer streams) — replace each integer x with \(x^2\).
    • map ord (for string streams) — replace each character with its ASCII code.
  • filter even: Filter the stream so that only even numbers remain. (Note: when using map ord on a string, the stream becomes integers.)
  • reduce add X: Reduce (fold) the stream by summing up its elements starting with the integer X as the initial value, and print the result.

The operations map and filter modify the stream by applying the transformation to all remaining elements (they do not produce immediate output). The take and reduce operations produce outputs. All inputs will be provided via standard input and outputs should be written to standard output.

inputFormat

The input begins with a line that is either int or string, denoting the stream type.

If the type is int, the second line contains a sequence of integers separated by a single space. If the type is string, the second line contains a single string (with no spaces).

The third line contains an integer Q representing the number of commands. The following Q lines each contain a command. The possible commands are:

  • take n — take the next n elements from the stream and output them separated by a space.
  • map square — replace each element x by \(x^2\) (only applicable for integer streams).
  • map ord — replace each character in a string by its ASCII code (transforms the stream into integers).
  • filter even — filter the stream to keep only even numbers.
  • reduce add X — compute the sum of all remaining elements starting with integer X as the initial value, and output the result.

outputFormat

For each command that produces an output (take and reduce), print the resulting output on a new line. For a take command, output the taken elements separated by a single space (if no element is taken, print an empty line). For a reduce command, output the resulting integer value.

## sample
int
1 2 3 4 5
3
take 3
take 3
take 3
1 2 3

4 5

</p>