#K63067. Closing Inventory Calculation
Closing Inventory Calculation
Closing Inventory Calculation
In this problem, you are given a list of inventory movement records. Each record represents a transaction for an item on a given day. A record consists of the following four fields:
- item_id (string): The identifier of the inventory item.
- quantity (integer): The number of items moved.
- day (integer): The day on which the movement occurred.
- movement_type (string): Either "IN" (for incoming items) or "OUT" (for outgoing items).
Your task is to calculate the closing inventory for each item on every day on which at least one transaction occurred. The closing inventory for an item on a day is defined as the cumulative sum of movements (with "IN" adding and "OUT" subtracting quantities) for that item up to and including that day.
The final result should list all records in ascending order first by day and then by item identifier (in lexicographical order). Each output record should contain:
- The day.
- The item identifier.
- The closing inventory count for that item on that day.
Note: The cumulative inventory for an item is the sum of the changes from the first record of that item up to the current day. Mathematically, if \(\Delta_i\) is the net movement for a day \(i\) (with \(\Delta_i=q_i\) for "IN" and \(\Delta_i=-q_i\) for "OUT"), then the closing inventory at day \(d\) is:
\[ Cumulative(d) = \sum_{i \le d} \Delta_i \]Make sure to process the input from stdin
and write the output to stdout
.
inputFormat
The input is read from stdin
and is formatted as follows:
- The first line contains an integer
N
, the number of movement records. - Each of the next
N
lines contains a record with four fields separated by spaces: item_id
(string)quantity
(integer)day
(integer)movement_type
(string, either "IN" or "OUT")
If N
is 0, there are no transactions and no output should be produced.
outputFormat
The output should be written to stdout
and include one line per record in the final result. Each line should contain three fields separated by a single space:
day
(integer)item_id
(string)closing_inventory_count
(integer)
The output records must be sorted in ascending order by day. If multiple records have the same day, they should be further sorted in lexicographical order by item_id
.
1
ItemA 20 10 IN
10 ItemA 20
</p>