Guest User

Untitled

a guest
May 23rd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. inputs <- c('dbbaCEDbdAacCEAadcB', 'EbAAdbBEaBaaBBdAccbeebaec')
  2.  
  3. tally <- function(input) {
  4. letters <- unlist(strsplit(input, ''))
  5. hash <- new.env()
  6.  
  7. # Tally scores.
  8. sapply(letters, function(letter) {
  9. # If the letter is not uppercase it's a score. Otherwise, it's a loss.
  10. score <- ifelse(gregexpr("[A-Z]", letter) < 1, 1, -1)
  11.  
  12. letter <- tolower(letter)
  13. hash[[letter]] <- ifelse(is.null(hash[[letter]]), score, hash[[letter]] + score)
  14. })
  15.  
  16. # Get score values.
  17. scores <- c()
  18. keys <- ls(hash)
  19. scores <- t(sapply(keys, function(key) {
  20. c(scores, c(key, hash[[key]]))
  21. }))
  22. colnames(scores) <- c('player', 'score')
  23. scores <- as.data.frame(scores)
  24. scores$score <- as.numeric(as.character(scores$score))
  25.  
  26. # Sort the scores.
  27. scores[order(scores$score, decreasing=T),]
  28. }
  29.  
  30. format <- function(scores) {
  31. str <- sapply(1:nrow(scores), function(i) {
  32. row <- scores[i,]
  33. paste0(row$player, ':', row$score)
  34. })
  35.  
  36. str
  37. }
Add Comment
Please, Sign In to add comment