Skip to content

Instantly share code, notes, and snippets.

@behrtam
Created May 13, 2017 10:49
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 behrtam/b8e80b15cb69c763857d39877b7b65d9 to your computer and use it in GitHub Desktop.
Save behrtam/b8e80b15cb69c763857d39877b7b65d9 to your computer and use it in GitHub Desktop.
object Challenges {
def mergeStrings(a: String, b: String): String = {
a.zipAll(b, "", "") map { case (m, n) => m.toString + n } mkString
}
def mergeStringsRec(a: String, b: String): String = {
def loop(first: List[Char], second: List[Char]): String =
(first, second) match {
case (x :: xs, y :: ys) => x.toString + y + loop(xs, ys)
case (f, Nil) => f mkString
case (Nil, s) => s mkString
}
loop(a.toList, b.toList)
}
def electionWinner(votes: Array[String]): String = {
val countedVotes = votes.groupBy(identity).mapValues(_.length)
val maxVotes = countedVotes.maxBy(_._2)._2
val allWinner = countedVotes.filter {
case (_, count) => count == maxVotes
}
allWinner.keys.toList.max // select alphabetically last
}
}
import org.scalatest.{FunSuite, Matchers}
class ChallengesTest extends FunSuite with Matchers {
test("merge empty") {
Challenges.mergeStrings("", "") should be("")
}
test("merge equal length") {
Challenges.mergeStrings("aaa", "bbb") should be("ababab")
}
test("merge a string longer") {
Challenges.mergeStrings("abcdedg", "???") should be("a?b?c?dedg")
}
test("merge b string longer") {
Challenges.mergeStrings("HTML", "........") should be("H.T.M.L.....")
}
test("ballot of one") {
val votes = Array("Alice")
Challenges.electionWinner(votes) should be("Alice")
}
test("ballot with clear winner") {
val votes = Array("John", "John", "John", "Bob", "John", "Alice")
Challenges.electionWinner(votes) should be("John")
}
test("ballot with more than one with max votes") {
val votes = Array("Alex",
"Michael",
"Harry",
"Dave",
"Michael",
"Victor",
"Harry",
"Alex",
"Mary",
"Mary")
Challenges.electionWinner(votes) should be("Michael")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment