Created
June 29, 2013 22:54
-
-
Save maasg/5893027 to your computer and use it in GitHub Desktop.
Scala solution for TopCoder 'SortBooks' exercise: http://community.topcoder.com/stat?c=problem_statement&pm=4557&rd=7996
#LearningScala
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 SortBooks { | |
val lexSeparators = Set("THE","AND","OF") | |
def isABook(s:String): Boolean = { | |
val words = s.split("\\s+") | |
if (words.size > 3) true else { | |
!words.map(_.toUpperCase).toSet.intersect(lexSeparators).isEmpty | |
} | |
} | |
def checkManually(field1:Array[String], field2:Array[String]):Array[Int] = { | |
val bookDef = field1.zip(field2).zipWithIndex | |
val booksToCheck = bookDef.filter({case ((field1,field2),index) => !(isABook(field1) ^ isABook(field2))}) | |
booksToCheck.map({case ((field1,field2),index) => index}).toArray | |
} | |
val fields1 = Array( "J R R Tolkien", "THE Jungle BOOK" ) | |
val fields2 = Array( "THE HOBBIT", "RUDYARD KIPLING" ) | |
checkManually(fields1,fields2) //> res0: Array[Int] = Array(0) | |
} |
I like the more compact form. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice use of xor! You can also leverage the rich API to avoid running through the whole list too many times like this: