Last active
December 18, 2015 21:28
-
-
Save maasg/5847203 to your computer and use it in GitHub Desktop.
Solution to TopCoder problem 'WordCompositionGame' http://community.topcoder.com/stat?c=problem_statement&pm=4483&rd=7228
#ScalaPractice
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
object WordCompositionGame { | |
def score(listA:Array[String] , listB:Array[String], listC:Array[String]): String = { | |
// turn those arrays into some useful Sets | |
val a = listA.toSet | |
val b = listB.toSet | |
val c = listC.toSet | |
val all = Set(a,b,c) | |
// calculates the intersection of a,b and c | |
val abc = all.reduceLeft(_.intersect(_)) | |
// calculates the score for a set, given all the sets and | |
// the common elements (that's an optimization as we only need to calculate that once) | |
def scoreSet(set:Set[String],allSets:Set[Set[String]], common:Set[String]):Int = { | |
val targetSet = allSets - set | |
val score2Sets = (for {set1 <- targetSet} yield (set.diff(common)).intersect(set1)) | |
val score2 = score2Sets.foldLeft(0)((count,set) => count + set.size) | |
val score3 = (set diff targetSet.reduce(_.union(_))).size | |
common.size + score2 *2 + score3 * 3 | |
} | |
// A map of a set is a set and will eliminate duplicates. As we want every score, we first turn the set into a list | |
all.toList.map(x=> scoreSet(x,all,abc)).mkString("/") | |
} | |
val a = Array( "cat", "dog", "pig", "mouse" ) | |
val b = Array( "cat", "pig" ) | |
val c = Array( "dog", "cat" ) | |
score(a, b, c) //> res0: String = 8/3/3 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment