Walk a sequence and count occurrences of each value in a map. Classic "get current count, add one, write back" loop.

Algorithm

Canonical input c("fig", "apple", "fig", "pear", "apple", "fig") produces the final map {fig: 3, apple: 2, pear: 1}.

Basic Implementation

basic.R
words <- c("fig", "apple", "fig", "pear", "apple", "fig")
counts <- list()
order <- character(0)
i <- 1
while (i <= length(words)) {
	word <- words[i]
	if (is.null(counts[[word]])) {
		order[length(order) + 1] <- word
		counts[[word]] <- 1
	} else {
		prev <- counts[[word]]
		counts[[word]] <- prev + 1
	}
	i <- i + 1
}
cat("{", sep = "")
j <- 1
while (j <= length(order)) {
	if (j > 1) {
		cat(", ", sep = "")
	}
	key <- order[j]
	cat(key, ": ", counts[[key]], sep = "")
	j <- j + 1
}
cat("}\n", sep = "")

Complexity

  • Time: O(n) average with R named lists (hash-backed for string keys in modern R).
  • Space: O(k) where k is the number of distinct keys.

Implementation notes

  • R: counts <- list() is the idiomatic named list; the is.null(counts[[word]]) predicate plus an explicit assignment keeps the lesson on the read-or-default path without hiding it behind a tryCatch default. R does have table(words) and tabulate(match(...)), but both call into C and would hide the per-step running count the lesson is teaching.
  • The auxiliary order buffer makes the first-seen order explicit so the final printout does not lean on named-list insertion order as a load-bearing contract.
  • The replay renders the map as a list of key/value rows in first-seen order and animates the count increment on each frame.
get-or-default A first-time `word` triggers the "default" branch: append to `order` and set `counts[[word]] <- 1`. A repeat read-modify-writes `counts[[word]] <- prev + 1`.
first-seen order Keys are tracked in `order` (a plain character vector) to keep the printout deterministic; R's named-list iteration order is preserved by insertion, but the lesson keeps an explicit `order` vector for parity with the language-neutral spec.