Skip to content

Instantly share code, notes, and snippets.

@WizardOfArc
Last active July 1, 2019 14:33
Show Gist options
  • Select an option

  • Save WizardOfArc/fd8c81c2b4ac35653cc251f19097f8a2 to your computer and use it in GitHub Desktop.

Select an option

Save WizardOfArc/fd8c81c2b4ac35653cc251f19097f8a2 to your computer and use it in GitHub Desktop.
Scala implementation of Source Code Word counter inspired by Fluent C++ ( https://www.fluentcpp.com/2018/10/12/word-counting-cpp-simple-word-counter/ )
import scala.io.Source
import scala.annotation.tailrec
import scala.collection.mutable.{Map -> MMap}
object WordCounter extends App {
if(args.length != 1){
println("Give me a file to investigate")
} else {
val wordList = Source.fromFile(args(0)).getLines
.flatMap(_.split("[()<>''+-=!|/ .,:{}\"]"))
.flatMap(_.split(raw"\\"))
.flatMap(_.split(raw"\["))
.flatMap(_.split(raw"\]"))
.flatMap(_.split(raw"\s"))
.filter(_ != "")
.toList
val padFunc = padOnRight(wordList.map(_.length).max)(_)
val wordCount = collectWords(wordList)
wordCount.toList.sortWith(_._2 > _._2).map{case (k,v) => s"${padFunc(k)} | $v"} foreach println
}
def collectWords(words: List[String]): Map[String, Int] = words.foldLeft(MMap[String, Int]()){
case (accum, h) =>
if(accum.contains(h)){ accum + (h -> (accum(h) + 1)) } else { accum + (h -> 1) }
}.toMap
def padOnRight(width: Int)(word: String): String = (0 to (width - word.length)).foldLeft(word)((a: String, _: Int) => a + " ")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment