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)
}
@sbocq
Copy link

sbocq commented Aug 10, 2013

Nice use of xor! You can also leverage the rich API to avoid running through the whole list too many times like this:

  def isABook(s:String): Boolean = {
   val words = s.split("\\s+")
   (words.size > 3) ||
    words.find(w => lexSeparators.contains(w.toUpperCase)).isDefined
  }

  def checkManually(field1:Array[String], field2:Array[String]):Array[Int] = 
    field1.zip(field2)
      .zipWithIndex
      .collect({case ((field1,field2),index)
                    if !(isABook(field1) ^ isABook(field2)) => index})
      .toArray

@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