Tuesday, April 20, 2010

The "binary search" script

For some reason, it could not get pasted there.

import util.Random
val toFind = args(0).toInt
val r = new Random()
val a = (for (i<- 1 to 100) yield r.nextInt(100)).toList.sort(_<_).toArray
def binsearch(x:Int, a:Array[Int],first:Int, last:Int):Int = {
    if (last-first<=1) {
        if (a(first)==x) return first
        else if (a(last)==x) return last
        else return -1} else {
            val mid = (last+first)/2
            if (a(mid)>=x) return binsearch(x, a, first, mid)
                else return binsearch(x, a, mid, last)
        }
        }
for (el<-0 to 99) println(el+":"+a(el))
val res = binsearch(toFind, a, 0,99)
println ("res="+res)

Tuesday, April 6, 2010

Some innocent fun with Scala and Swing

Preamble: For the coming codefest organized by devnology (Dutch programming community) everybody was supposed to write some tetris-like application in the language of their choice. After some painful speculations in which of the existing languages I can appear less ignorant than I am, I have decided to use this as a pretext for learning how Swing framework works, and to remember (a.k.a. learn once more) some Scala that I have tried to learn for a while.

I ended up installing Scala 2.8 (because the swing representation in Scala 2.7 is very inconsistent and you can't get away from mixing in quite some amounts of java code, which makes is less interesting) and NetBeans (because I wanted some context help as looking into scarce 2.8 docs now and then makes the whole task compatible with trying to read "The Woman in White" in the original language armed only with the course of "technical English" - I did that very long time ago, it proved to be my real starting point on the way to more or less decent knowledge of this human language, but it's not that story).

In short: it was doable (may be I'll add the details later), took me several days to hack something together, and provided a funny discovery.

In my MainFrame object I have the following code:
def doStart = {
  matrix.StartGame
  timer = new Timer
  timer.scheduleAtFixedRate (new TimerTask {
   def run() = {
   matrix.NextStep
   mypanel.repaint()
   }
  }, 0, 1000)
}
def doStop = {
  timer.cancel()
  matrix.inGame = false
}
def DoShift(a:Move) = {matrix.shiftElem(a);mypanel.repaint}
reactions += {
case KeyPressed(src, key, mod, value) =>
 {
 key match {  case Key.Right => DoShift(RIGHT)
  case Key.Left => DoShift(LEFT)
  case Key.Space => DoShift(DROP)
  case Key.Enter => DoShift(FLIP)
  case Key.Up => DoShift(ROTATELEFT)
  case Key.Down => DoShift(ROTATERIGHT)
  case Key.S => if(matrix.inGame) doStop else doStart
  }
 }
}
 The fun fact: omitting the curly braces in DoShift method made the reactions to the key strokes something like 10 times slower on my machine (Ubuntu 9.10 with 2 GB RAM and NetBeans running in the background). Why?