Last active
May 18, 2018 18:53
-
-
Save primaryobjects/d5ac04229ad83f3f55453a43284d36e5 to your computer and use it in GitHub Desktop.
[2018-05-14] Challenge #361 [Easy] Tally Program https://www.reddit.com/r/dailyprogrammer/comments/8jcffg/20180514_challenge_361_easy_tally_program/ Demo at http://rextester.com/WTF21439
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tally and print the scores for each input. | |
sapply(inputs, function(input) { | |
scores <- format(tally(input)) | |
print(paste(scores, collapse=', ')) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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