Created
February 5, 2021 04:05
-
-
Save noahlz/9cf49053ccbed44351ba2d7f52c73679 to your computer and use it in GitHub Desktop.
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
/** | |
* 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