Albuquerque Scala Study Group Funtime Homework and Solutions
Filed Under: Scala StreamsStreamsNPRPuzzleStudyScalaStreamChallengePalindromeWill ShortzAlbuquerque Scala Study GroupAlbuquerqueNPR Sunday Puzzle
These were two homework challenges from our Albuquerque Scala Study Group last week. One was an NPR Sunday Puzzle.
Do this in Scala....
- Write down the digits from 2 to 7, in order. Add two mathematical symbols to get an expression equaling 2010. What symbols are these? (Figure it out in Scala)
- 01/02/2010 was a palindrome date and it was awesome! In Scala, figure out the next dates that will be a palindrome, and give me the results in a Stream[Date].
So if I type:
scala > nextPalindromeDates take 5 print
It should get the next 5 palindrome dates from the day that you run it.
Here are my solutions, with help from the group of course:
Write down the digits from 2 to 7, in order. Add two mathematical symbols to get an expression equaling 2010. What symbols are these? (Figure it out in Scala)
object Runner {
def eval(s: String): Int = {
val pattern = "\\d+".r
var nums = ((pattern findAllIn s).toList)
val opPattern = "(\\+|-|\\*|/)".r
var ops = "+" :: ((opPattern findAllIn s).toList)
nums.zip(ops).foldLeft(0) {
(x, y) =>
val num = y._1
val op = y._2
op match {
case "+" => x + num.toInt
case "-" => x - num.toInt
case "*" => x * num.toInt
case "/" => x / num.toInt
}
}
}
def main(args: Array[String]) {
val list = (2 to 7).toList
val operators = "+" :: "*" :: "/" :: "-" :: Nil
(1 to 5).foreach{ x => ((x+1) to 6).foreach{ y =>
operators.foreach { op1 => operators.foreach { op2 =>
if (x != y) {
var formula = (list.slice(0, x) ::: (op1 :: (list.slice(x, y))) ::: (op2 :: (list.takeRight(6 - y)))).mkString
var total = eval(formula)
if (total == 2010) println(formula)
}
}}}}
}
}
This was harder than it seemed and required an eval that can parse out a String like "2000*13+12" and evaluate it. My strategy was to peel all the numbers into a nums var and then peel all the operators using regular expression. I then zipped up the numbers with their corresponding operators and folded them up for the result.
Next, in my main method I have 4 loops one is the loop to determine the first space to separate the numbers. The next loop is to determine where to space the next set of numbers. So for example, given that x = 2 and y = 4:
2 3 4 5 6 7
It would separate the 2nd space and the 4th space giving me:
2 3 [ ] 4 5 [ ] 6 7
It is in these spaces that I will put in operator variants. from the 3rd and 4th loop. op1 and op2 will go through each of the operators and fit them in to determine which of the applicable value will work and give me the result of 2010.
After running this application I get the result:
2345*6/7
The 2nd homework question was: 01/02/2010 was a palindrome date and it was awesome! In Scala, figure out the next dates that will be a palindrome, and give me the results in a Stream[Date].
So if I type:
scala > nextPalindromeDates take 5 print
It should get the next 5 palindrome dates from the day that you run it.
Here is my solution to this puzzle:
object PalindromeDates {
val datesOnlyFormat = new SimpleDateFormat("MMddyyyy")
val dateFormat = new SimpleDateFormat("MM/dd/yyyy")
def isPalindrome(cal:Calendar) = {
val fmt = datesOnlyFormat.format(cal.getTime())
fmt.reverse.toString == fmt
}
def getNextPalindromeDate(cal:Calendar):Stream[Calendar] = {
cal.add(Calendar.DATE, 1)
if (isPalindrome(cal)) Stream.cons(cal, getNextPalindromeDate(cal))
else getNextPalindromeDate(cal)
}
def main(args:Array[String]) {
getNextPalindromeDate(Calendar.getInstance()) take 30 foreach {x=>println(dateFormat.format(x.getTime()))}
}
}
This solution obviously uses recursion with getNextPalindrome date. It goes through each Calendar. If the calendar is a Palindrome date as determined by isPalindrome, then the date is conssed (New Word!) to the stream and recursed again with the calendar. One thing that stuck out like a sore thumb was the mutable Calendar, given that Scala is a functional language and has a strong culture of having just about everything as immutable as possible with no side effects.
The main method for this application is different that the homework I provided just because I wanted cleaner and sexier output. I also gave it 30 instead of 5 to see if it can handle it and it did, and it did so surprisingly fast. Here is the result...
11/02/2011 02/02/2020 12/02/2021 03/02/2030 04/02/2040 05/02/2050 06/02/2060 07/02/2070 08/02/2080 09/02/2090 10/12/2101 01/12/2110 11/12/2111 02/12/2120 12/12/2121 03/12/2130 04/12/2140 05/12/2150 06/12/2160 07/12/2170 08/12/2180 09/12/2190 10/22/2201 01/22/2210 11/22/2211 02/22/2220 12/22/2221 03/22/2230 04/22/2240 05/22/2250
So try out these puzzles on your own and see how well you can do, and try some other solutions. Better yet, form either a Scala User Group or a Scala Study Group in your area and work on it together.
Decorator Pattern In Scala
Filed Under: Design PatternsScalaPatternsDecoratorPatternDecorator Pattern
As part of the Scala Study Group in Albuquerque, we had an assignment to reproduce some of the popular design patterns in Scala. Although the assignment is over, it is worth while to log about it. The following pattern was taken from Groovy Decorator Example.
trait Logger {
def log(message: String) = {
message
}
}
Figure 1: Establishing a trait shared by all Loggers.
object StdLogger extends Logger
Figure 2: Objects are explicit creations of an object. There are no statics in Scala, and for good reason. Reasons that are too many for me to cover here. What this does is create an object called StdLogger. This is merely an implementation of the trait with no added behavior.
class TimeStampingLogger(logger: Logger) extends Logger {
override def log(message: String) = {
val now = Calendar.getInstance
now.getTime.toString + ' ' + logger.log(message)
}
}
Figure 3: The time stamping logger takes a Logger object and decorates with the current time prepended with whatever message is returned from the parent logger.
class UpperLogger(logger: Logger) extends Logger {
override def log(message: String) = {
logger.log(message).toUpperCase
}
}
Figure 4: The UpperLogger will capitalize all letters returned from the parent Logger object.
object DecoratorRunner extends Application {
override def main(args: Array[String]) {
val timeStampingLogger = new TimeStampingLogger(StdLogger)
val upperLogger = new UpperLogger(timeStampingLogger)
println(upperLogger.log(StdLogger.log("Decorator for the Scala Study Group")))
}
}
Figure 5: The application runner itself. I instantiate the TimeStampingLogger and the UpperLogger. Note that I do not instantiate the StdLogger because that already is instantiated because it is an object. I chain them together and produce the needed result.
Pardon the mess, upgraded from Pebble to Custom Seam Blog
Pardon the mess, I have recently upgraded from Pebble to my own custom blog using JBoss Seam. Ability to comment will arrive shortly. Thanks.