antonio
BAN USER
// Scala version
import scala.io.Source
object UniqueLinesInFiles {
def findUniqueLines(filenames: Seq[String]): Seq[String] = {
filenames.foldLeft(Map.empty[Int, Set[String]])((linesMap, filename) => {
Source.fromFile(filename).getLines.foldLeft(linesMap)((memo, line) => {
memo.get(line.length()) match {
case Some(linesOfLength) => {
/*
This block could also be simplified to just:
memo + (line.length() -> (linesOfLength + line))
*/
if (linesOfLength.contains(line)) {
memo
} else {
memo + (line.length() -> (linesOfLength + line))
}
}
case None => {
memo + (line.length() -> Set(line))
}
}
})
}).foldLeft(Set.empty[String]) { case (memo, (_, lines)) => memo ++ lines }.toSeq
}
}
O(n) algorithm for n shops
- antonio June 26, 2019