Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active May 18, 2018 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/d5ac04229ad83f3f55453a43284d36e5 to your computer and use it in GitHub Desktop.
Save primaryobjects/d5ac04229ad83f3f55453a43284d36e5 to your computer and use it in GitHub Desktop.
inputs <- c('dbbaCEDbdAacCEAadcB', 'EbAAdbBEaBaaBBdAccbeebaec')
tally <- function(input) {
letters <- unlist(strsplit(input, ''))
hash <- new.env()
# Tally scores.
sapply(letters, function(letter) {
# If the letter is not uppercase it's a score. Otherwise, it's a loss.
score <- ifelse(gregexpr("[A-Z]", letter) < 1, 1, -1)
letter <- tolower(letter)
hash[[letter]] <- ifelse(is.null(hash[[letter]]), score, hash[[letter]] + score)
})
# Get score values.
scores <- c()
keys <- ls(hash)
scores <- t(sapply(keys, function(key) {
c(scores, c(key, hash[[key]]))
}))
colnames(scores) <- c('player', 'score')
scores <- as.data.frame(scores)
scores$score <- as.numeric(as.character(scores$score))
# Sort the scores.
scores[order(scores$score, decreasing=T),]
}
format <- function(scores) {
str <- sapply(1:nrow(scores), function(i) {
row <- scores[i,]
paste0(row$player, ':', row$score)
})
str
}
# Tally and print the scores for each input.
sapply(inputs, function(input) {
scores <- format(tally(input))
print(paste(scores, collapse=', '))
})
"b:2, d:2, a:1, c:0, e:-2"
"c:3, d:2, a:1, e:1, b:0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment