Lesson contents

R — Inventory project with boundary tests

This R inventory function pairs each operation with the quantity at the same position in a second vector. Matching vector lengths keeps every quantity attached to the right event.

A simple example

Trace one stock change

  1. Start with 3 in stock
  2. Do this Take 1 away
  3. Result 2
One subtraction updates the starting count. The project below adds checks for larger changes.
Lesson.R
stock <- 3
stock <- stock - 1
cat(stock)
Output
2
Advertisements

Build an inventory event processor

seq_along handles an empty input safely. The two vectors must have equal lengths so that each operation stays paired with its quantity.

Receive 5, ship 2: 3 in stock. Invalid events: 2 rejected. Receive 4: 7 in stock.
Reconcile a stock ledger

The first delivery brings five units and a shipment takes two. A request to ship nine and an unknown event are both rejected, so stock stays at three. The final delivery adds four and closes the ledger at seven.

Run the example

R 4. Run these commands from the directory containing the example.

Rscript Lesson.R
Lesson.R
process <- function(kind, units) {
  stopifnot(length(kind) == length(units))
  stock <- rejected <- 0
  for (i in seq_along(kind)) {
    n <- units[i]
    if (kind[i] == "in" && n > 0) {
      stock <- stock + n
    } else if (kind[i] == "out" && n > 0 && n <= stock) {
      stock <- stock - n
    } else {
      rejected <- rejected + 1
    }
  }
  c(stock, rejected)
}

result <- process(c("in", "out", "out", "?", "in"), c(5, 2, 9, 1, 4))
stopifnot(all(process(character(), numeric()) == c(0, 0)))
stopifnot(all(process(c("in", "out"), c(2, 2)) == c(0, 0)))
stopifnot(all(result == c(7, 2)))
cat(paste(result, collapse = " "), "\n", sep = "")
Output
7 2

Start with zero units. Receive 5 and ship 2 to leave 3. Reject the shipment of 9 and the unknown event. Finally receive 4. The two output numbers are the ending stock of 7 and the two rejected events.

Buy supplies for the next shift

A breakfast kiosk has 28 cups left, expects 64 orders tomorrow and keeps four spare cups for spills. The supervisor subtracts usable stock from the target and buys sealed sleeves of ten, rounding the order up to a whole sleeve.

Lesson.R
orders <- 64L
spare <- 4L
on_hand <- 28L
shortage <- max(0L, orders + spare - on_hand)
cat((shortage + 9L) %/% 10L, "sleeves")
Output
4 sleeves

The target is 68 cups. After counting the 28 on hand, the kiosk needs 40 more, exactly four sleeves of ten.

Try it yourself

Append a shipment of 7, followed by another shipment of 1.

Check your answer

The first shipment exactly empties stock. The next one is rejected. Update the expected result to 0 units and 3 rejections. Keep the existing checks for the empty event list and exact depletion.

An Introduction to R

Related tags

  • R
  • inventory
  • testing
  • state transitions