Skip to content

Instantly share code, notes, and snippets.

@noahlz
Created February 5, 2021 04:05
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 noahlz/9cf49053ccbed44351ba2d7f52c73679 to your computer and use it in GitHub Desktop.
Save noahlz/9cf49053ccbed44351ba2d7f52c73679 to your computer and use it in GitHub Desktop.
/**
* non-performant solution to https://twitter.com/Al_Grigor/status/1357028887209902088
* scala> partitionCount("aaaabbbcca")
* res0: List[(Char, Int)] = List((a,4), (b,3), (c,2), (a,1))
* PS see "stringly" for a better solution in clojure.
* Is there a scala equivalent to this? Feel free to comment.
* (->> (partition-by identity s) (map frequencies) seq))
*/
def partitionCount(s: String): List[(Char, Int)] = {
s.toList.foldLeft(List.empty[(Char, Int)]) { (agg, c) =>
agg.headOption.fold {
(c, 1) :: Nil
} { case (firstC, n) =>
if (c == firstC) {
(c, n + 1) :: agg.tail
}
else {
(c, 1) :: agg
}
}
}.reverse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment