Skip to content

Instantly share code, notes, and snippets.

@maasg
Created June 29, 2013 22:54
Show Gist options
  • Save maasg/5893027 to your computer and use it in GitHub Desktop.
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
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)
}
@maasg
Copy link
Author

maasg commented Aug 18, 2013

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