Tuesday, November 22, 2011

LWJGL, full screen and Win7 issue...

Summary:
I couldn't get full screen mode to work. The spaceinvaders demo app (provided right in the LWJGL download) would just silently crash straight back to Eclipse. There was no error output at all. It turns out Direct3D doesn't work well with Vista/Win7. And there's a simple VM argument to turn it off, "-Dsun.java2d.d3d=false". 


Details:
Ah, the joys of computer configuration complexity. It ensures I spend lots of time on damn near useless tangents. After a nice time burn like this, I so can see why developing for only one specific platform can be quite desirable. Anywho...

So, in my quest towards writing a space invaders clone in Scala, I decided to first get the space invaders Java application supplied as a demo in the main LWJGL download's demo folder. I was able to get all the .java files copied into the proper path. And then was happy when it worked first time with almost no editing. I did go and clean up several warnings that were shown by the compiler.

And then I decided to try and turn on full screen mode (as opposed to the windowed mode that was the default). The application would clearly start, appear to get close to running (full screen of black would appear) and then it just sat there until I clicked with the mouse. Then it would crash right back to Eclipse with no error output whatsoever. Quite frustrating.

After spending several hours slowly going through the code placing copious amounts of System.out.println() statements and lots of try{...} catch (Throwable t) {t.printStackTrace()}, I finally narrowed the intermittent failures down to a line in LWJGL itself, Display.sync(60). I have the LWJGL source attached so I can examine the related source code easily.

After examining the code for sync() and then evaluating whether I wanted to go to the trouble of making the LWJGL source editable, I decided to stop and see if I could Google and see if anyone else was having the issue. It only took 5 minutes using the starting search terms of "LWJGL full screen crash" to discover a possible answer on a forum message thread (related StackOverflow topic). For Vista/Win7, I must pass a VM argument of "-Dsun.java2d.d3d=false" to turn off Direct3D. Of course, as soon as I did that, everything sprang up and worked like a charm.

Lesson Learned:
Google with simplest set of key words as soon as possible. It might save a whole bunch of time attempting to isolate an intermittent issue.

Sunday, November 6, 2011

I'm back from my gaming hiatus...

I've been away enjoying my personal time. I have not done anything related to coding other than my standard JavaEE stuff at work. I've kept studying all the Scala blogs and have been following the Scala tag on StackOverflow and CodeReview sites. I've continued to want to dive right in and just start coding. It is so obvious to me that I would find designing and writing code very enjoyable in Scala. And I am slowly finding it more and more laborious to produce all the boilerplate necessary when I coding in Java, even with the assistance of code completion and code generation tools in Eclipse.

As I am returning to creating time to play directly with Scala again, I am not finding myself all that motivated to continue on the Life project. I don't want to code a little and then blog alot. It just feels too much like doing Java boilerplate; a huge amount of writing with a very small portion that actually does the interesting work. So, for now I am postponing my Scala Life project. I will very likely return to it.

I am finding myself interested in playing around with Scala and creating a simple retro style video game (from the early 80s); Asteroids, Space Invaders, PacMan Missile Command, Defender, etc. These are the games I initially reproduced when I started learning to program on the TI99/4a 30 years ago. And I don't care that there are hundreds of variations of these games. I am not writing it to be consumed by anyone else. I am writing it to feel the delight of achievement, the thrill of viceral learning, the joy of being playful yet inquisitive while minimize the occurrences of and duration of breakdowns, frustrations (configuration challenges, deployment errors, etc.) and technical challenges.

I have spent about 8 hours researching how to go about writing an OpenGL game using Scala. I looked at a number of possible game engines. And it turns out there is an interesting project called LWJGL (LightWeight Java Game Library) which ties together all sorts of C++/C libraries and APIs such that Java programs can utilize them. And anything Java can utilize, Scala can also. So, I am going to do a Scala + LWJGL project. And for now, I am planning to write a very simple version of Space Invaders. Whoohoo!

Wednesday, July 27, 2011

Odersky talk (16 minutes) at OSCON...

Typesafe and Martin Odersky are working very hard on the parallel and concurrency problems. And all in Scala. This talk is so exciting as it shows how wide and deep they are approaching the problem. And how Scala's unique OO + FP approach to software engineering is ideal for this problem domain.

Sunday, July 24, 2011

Project Euler - Problem 002 - Learning to think the Scala way...

This post continues my journey to learn Scala by using the problems off of the web-site projecteuler.com (descriped in my original post here: http://fromjavatoscala.blogspot.com/2011/05/project-euler-problem-001-learning-to.html)

Problem Statement - 002:


Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.



Visualization/Examples:
  1. Natural numbers in Fibonacci series not exceeding 100 with a multiple of 2
    1. Numbers not exceeding 100 = 1 2 3 ... 98 99 100
    2. Fibonacci Series = 1 2 3 5 8 13 21 34 55 89
    3. Multiples of 2 = 1 2 3 5 8 13 21 34 55 89
    4. Sum = 2 + 8 + 34 = 44


Mathematical Notation:
TBD

Test Cases:

  1. floor = (0 and 1 as 1), ceiling = 100, multiple = 2 , answer = 2 + 8 + 34 = 44 (produced by hand)
  2. floor = (0 and 1 as 1), ceiling = 4000000, multiple = 2, answer = ? (produce from code)

Code Implementation Approaches:
The first and most intuitive approach for me at this time is to go one by one for each two-number sum starting from floor (0 and 1) to ceiling (100) and test a number for whether it is divisible by 2. If so, add it to a total I am keeping. And when the loop is finished, I will have my answer. Here's the small Scala Object class I created to perform the work:

object Problem002 extends App {
  //http://projecteuler.net/index.php?section=problems&id=2
  override def main(args : Array[String]) : Unit = {
    javaWithoutSemicolons
  }
  def javaWithoutSemicolons : Unit = {
    var first = 0   //floor
    var second = 1  //floor
    val ceiling = 100
    val multiple = 2
    var sum = 0
    var next = 0
    while (second <= ceiling) {
      next = first + second
      first = second
      second = next
      if (first % multiple == 0)
        sum = sum + first
    }
    Console.println("javaWithoutSemicolons.sum=" + sum)
  }
}

Just like for problem 1, this code looks almost identical to the Java code I would write, essentially Java without semicolons. Note the presence of the "var"s which is a strong indication I am using the "imperative" approach again (as contrasted with the "functional" approach) to composing a solution.

The next step, again like last time, is to "refactor" this code to move towards the functional paradigm. Let's start by creating a function which returns a list of Fibonacci numbers less than a passed in value. And then use our now familiar filter and sum to obtain our value.

def headedTowardsFunctional : Unit = {
  def fibList (ceiling: Int, floor: Int = -1): List[Int] = {
    var values = List[Int]()
    var first = 0
    if (first > floor)
      values = first :: values
    var second = 1
    var next = 0
    while (second <= ceiling) {
      next = first + second
      first = second
      if (first > floor)
        values = first :: values
      second = next
    }
    values.reverse
  }
  val ceiling = 100
  val multiple = 2
  val fibs = fibList(ceiling)
  val fibsFilter = fibs.filter(n => (n % multiple == 0))
  val sum = fibsFilter.sum
  Console.println("headedTowardsFunctional.sum=" + sum)
}

I have successfully removed all the vars from the main method. However, there are still several in my fibList function. There are a number of approaches possible here. The first that comes to mind is to collect a list of all the numbers in the series which fit in an Int. While it sounds huge, it isn't. There are less than a fifty (47 to be precise). Because the series is exponential in nature, not linear, the entire thing fits in a tiny list.

So, here's a version which separates the production of the whole series up to the highest value an Int can hold. And then that list is easily handled with a for comprehension.

def functional1 : Unit = {
  val fibsAll = {
    var fibs = 0 :: List()
    var current = fibs.head
    var next = 1
    var continue = true
    while (continue) {
      current = fibs.head
      fibs = next :: fibs
      continue = ((0.0 + next + current) <= Int.MaxValue)
      if (continue)
        next = next + current
    }
    fibs.reverse
  }
  def fibList (ceiling: Int, floor: Int = -1): List[Int] = {
    val values =
      for (i <- fibsAll if ((i > floor) && (i < ceiling))) yield i
    values.reverse
  }
  val ceiling = 100
  val multiple = 2
  val fibs = fibList(ceiling)
  val fibsFilter = fibs.filter(n => (n % multiple == 0))
  val sum = fibsFilter.sum
  Console.println("functional1.sum=" + sum)
}

And it is just a very simple step from there to take this fully functional (excluding the function used by fibAll). And while we're at it, let's move the ceiling and multiple constants into being root method parameters:

def functional2(ceiling: Int, multiple: Int) : Unit = {
  val fibsAll = {
    //generate all 47 for an Int
    var fibs = 0 :: List()
    var current = fibs.head
    var next = 1
    var continue = true
    while (continue) {
      current = fibs.head
      fibs = next :: fibs
      continue = ((0.0 + next + current) <= Int.MaxValue)
      if (continue)
        next = next + current
    }
    fibs.reverse
  }
  def fibList (ceiling: Int, floor: Int = -1): List[Int] = {
    val values =
      for (i <- fibsAll if ((i > floor) && (i < ceiling))) yield i
    values.reverse
  }
  val sum = fibList(ceiling).filter(n => (n % multiple == 0)).sum
  Console.println("functional2.sum=" + sum)
}

I don't particularly like the function I have created for fibsAll. It "smells" imperative with it's ample var-ness. How might I go about making it better, more in the Scala style? I've googled other implementations of Fibonacci in Scala, but all are fixated on producing the sum for n elements (and several are incorrect in that they seem to skip the first two root elements (0, 1) starting with (1, 2) instead. The correct sequence starts as [0, 1, 1, 2, 3, 5...] and not [1, 2, 3, 5...]. Even the projecteuler.com Problem 2 states the beginning of the sequence incorrectly at [1, 2, 3...].

After posting my current implementation of fibAll to CodeReview (like StackOverflow, but more specifically for code reviews) and going several comment cycles with Leonardo Lucena there, I finally have a much better solution for for implementing fibsAll. Here it is:

def functional3(ceiling: Int, multiple: Int) : Unit = {
  def fibs(a: Int = 0, b: Int = 1): Stream[Int] = Stream.cons(a, fibs(b, a + b))
  val fibsAll = fibs().takeWhile(n => (n > -1)).toList
  def fibsList (ceiling: Int, floor: Int = -1): List[Int] = {
    for (i <- fibsAll if ((i > floor) && (i < ceiling))) yield i
  }
  val sum = fibsList(ceiling).filter(n => (n % multiple == 0)).sum
  Console.println("functional3.sum=" + sum)
}

So what is the fibs function doing? And what is Stream.cons? And while it's recursive, it's not able to be optimized using the @tailrec annotation. The fibs function is simulating an infinite series, in this case based on Fibonacci. Stream is an object that enables temporary state (via recursion) for a function. It behaves similar to a List, but waits to evaluate the passed function until it is required to do so which in this case does not happen until the takeWhile call when assigning the val fibsAll. As to the inability to do the @tailrec optimization; the actual depth required by this series is relatively shallow at 47. However, if the takeWhile had been replaced with a take(1000) or the like, the function would likely abort with a stack overflow. At this time, I don't exactly know how to approach refactoring the function so as to remain consistent with the functional/recursive approach and enable the @tailrec annotation.

So, this we are at the most functional we can be at this time. Now, for the inevitable - change...

Requirements change (keeping it real):
Or said a slightly different way, slightly changing and expanding the original problem so as to explore code design, refactoring and performance. Using the same basic model in the original problem, find the answer for the following set of problems:

  1. floor = 0, ceiling = 100, multiple 2
  2. floor = 0, ceiling = 4000000, multiple 2
  3. floor = 0, ceiling = 4000000, multiple 3
  4. floor = 0, ceiling = 4000000, multiples 2, 3, 5, 7
  5. floor = 100, ceiling = 4000000, multiple 2


Code Refactoring (fancy way of saying "adapting"):
While I was developing the solution pathway above, I did so with an eye towards the likelyhood that the requirements might change (or in this case, expand). Hence, my placing the floor in the fibsList function. Given this new set of problems, we are most of the way there. We just need to adjust for a set of multiples, as opposed to a single one. And since we already solved that in Problem 1, we just have to graft the solution there into this code. Here's what it looks like:

def functional4(ceiling: Int, multiples: List[Int]) : Unit = {
  def fibs(a: Int = 0, b: Int = 1): Stream[Int] = Stream.cons(a, fibs(b, a + b))
  val fibsAll = fibs().takeWhile(n => (n > -1)).toList
  def fibsList (ceiling: Int, floor: Int = -1): List[Int] = {
    for (i <- fibsAll if ((i > floor) && (i < ceiling))) yield i
  }
  val sum = fibsList(ceiling).filter(n => {multiples.exists(x => (n % x) == 0)}).sum
  Console.println("functional4.sum=" + sum)
}

It's very pleasing to be able to pluck out and reuse part of what we learned from Problem 1. And, we're done! On to Problem 3...soon. {smirk}

Sunday, May 22, 2011

Project Euler - Problem 001 - Learning to think the Scala way...

I stumbled across an interesting web-site called ProjectEuler. The Wiki page gives a very good overview of the site.

I realized it would be a very interesting way for me to learn Scala syntax in a low risk and fun environment, small puzzles. Additionally, my son has expressed an interest in learning how to program. I figured this might be a great way to get him started, too. I will get back to the Scala-life series again, I promise.

My intention is to show the exact text of the problem from the web-site. Then, I would go through the process of taking the word problem and "visualizing" it; draw and possibly even animate it. Once the problem is visual, then I would then talk about possible solution approaches centering on declarative, imperative and functional. And then finally, I will transform it into both mathematical notation and Scala code.

So, let's jump right in. This post may be subjected to some frequent edit/update cycles after being published as I find my way to the right balance in working through designing this.

Problem Statement - 001:


If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.


Find the sum of all the multiples of 3 or 5 below 1000.



Visualization/Examples:
  1. numbers below 10 with multiples of 3 or 5
    1. Natural numbers below 10 = 1 2 3 4 5 6 7 8 9
    2. Multiples of 3 = 1 2 3 4 5 6 7 8 9
    3. Multiples of 5 = 1 2 3 4 5 6 7 8 9
    4. Multiples only = 3 5 6 9
    5. Sum = 3 + 5 + 6 + 9 = 23
  2. numbers below 20 with multiples of 3 or 5
    1. Natural numbers below 20 = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    2. Multiples of 3 = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
    3. Multiples of 5 = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
    4. Multiples only = 3 5 6 9 10 12 15 18
    5. Sum = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18= 78


Mathematical Notation:
TBD

Test Cases:

  1. floor = 1, ceiling = 10, multiples = 3 and 5, answer = 3 + 5 + 6 + 9 = 23 (provided in problem statement)
  2. floor = 1, ceiling = 20, multiples = 3 and 5, answer = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 = 78 (produced by hand)
  3. floor = 1, ceiling = 1000, multiples = 3 and 5, answer = ? (produce from code)

Code Implementation Approaches:
The first and most intuitive approach for me at this time is to go one by one for each number from floor (1) to ceiling (10) and test a number for whether it is divisible by 3 or divisible by 5. If so, add it to a total I am keeping. And when the loop is finished, I will have my answer. Here's the small Scala Object class I created to perform the work:

object Problem001 extends App {
  //http://projecteuler.net/index.php?section=problems&id=1
  override def main(args : Array[String]) : Unit = {
    javaWithoutSemicolons
  }
  def javaWithoutSemicolons : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    var sum = 0
    for (i <- floor until ceiling)
      if ((i % multiple3 == 0) || (i % multiple5 == 0))
        sum = sum + i
    Console.println("javaWithoutSemicolons.sum=" + sum);
  }
}

This code looks almost identical to the Java code I would write, essentially Java without semicolons. Note the presence of the "var" for "sum". This is referred to as the "imperative" approach (as contrasted with the "functional" approach) to composing a solution. So, how might one go about moving this towards the more functional approach which is gently promoted by advanced Scala developers (and not so gently by functional programmers who have recently, if not reluctantly, adopted Scala)? We find a way to ensure everything remains "immutable"; i.e. there are no "var" entities defined. Additionally, we don't explicitly loop, but leave that to the internal implementations of appropriate classes and functions. Here's an updated version of a Scala class Problem001 with the new method "headedTowardsFunctional" demonstrating a version of the code moved substantially closer towards the functional goal:

object Problem001 extends App {
  //http://projecteuler.net/index.php?section=problems&id=1
  override def main(args : Array[String]) : Unit = {
    javaWithoutSemicolons
    headedTowardsFunctional
  }
  def javaWithoutSemicolons : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    var sum = 0
    for (i <- floor until ceiling)
      if ((i % multiple3 == 0) || (i % multiple5 == 0))
        sum = sum + i
    Console.println("javaWithoutSemicolons.sum=" + sum);
  }
  def headedTowardsFunctional : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    val numberRange = floor until ceiling
    val validMembers = numberRange.filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)})
    val sum = validMembers.sum
    Console.println("headedTowardsFunctional.sum=" + sum);
  }
}

In this new method, everything from "numberRange" down is actually a function. As such, we can can use function chaining to reduce the last four lines of code down to one. Here's a new method "mostlyFunctional" with this simplification:

def mostlyFunctional : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    Console.println("mostlyFunctional.sum=" + (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum)
  }

Now, to find out the answer to the ProjectEuler problem, I will leave you to figure out how to run this code in either Scala's REPL and/or in your favorite IDE with a Scala plug-in. For those of you who are brand new to programming period, here's a link to a separate page where I take you step-by-step through the process of getting set up so you can get started. And now for a "real world" surprise, a requirements change...

Requirements change (keeping it real):
Or said a slightly different way, slightly changing and expanding the original problem so as to explore code design, refactoring and performance. Using the same basic model in the original problem, find the answer for the following set of problems:

  1. floor = 1, ceiling = 1000, multiples 2 and 5
  2. floor = 1, ceiling = 10000, multiples 3, 7 and 10
  3. floor = 100, ceiling = 1100, multiples 3 and 5
  4. floor = 1, ceiling = 1000, multiples 2 through 10
  5. floor = 1, ceiling = 1000000, multiples 2, 3, 5, 7 and 11


Code Refactoring (fancy way of saying "adapting"):
So, how might we go about arranging the code so as to more optimally handle these problems while exploiting other features of Scala. And maybe even adding some more function programming?

The very first and most obvious refactoring is to move the variable definitions out of the body of the function and into the method definition. Luckily, Scala makes this both simple to do and even simpler to use. Here's the first pass at doing so.

mostlyFunctionalWithParameters(1, 10, 3, 5)
...
  def mostlyFunctionalWithParameters(floor: Int, ceiling: Int, multiple3: Int, multiple5: Int) : Unit = {
    Console.println("mostlyFunctionalWithParameters.sum=" + (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum)
  }

And it is more functional design to remove the side-effects, of which Console.println() is in this case. The result of this change looks like this:

Console.println("functionalWithParameters.sum=" + functionalWithParameters(1, 10, 3, 5))
...
  def functionalWithParameters(floor: Int, ceiling: Int, multiple3: Int, multiple5: Int) : Int = {
    (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum
  }

Most of the time, the value for floor is going to 1. So, wouldn't it be nice to be able to provide a default so it doesn't have to be supplied unless it's different. Here's how that looks:

Console.println("functionalWithParametersDefaultFloor.sum=" + functionalWithParametersDefaultFloor(10, 3, 5))
...
  def functionalWithParametersDefaultFloor(ceiling: Int, multiple3: Int, multiple5: Int, floor: Int = 1) : Int = {
    (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum
  }

Optional parameters (any for which a default is provided) must appear at the end of the method's list of parameters. This enables the client to specify by name or position all the required parameters and then selectively specify the optional parameters by name.

So, we now have a pure functional method. However, we are still only allowing for two multiples to be specified. And two of our new problems identify more than two multiples. So, we must re-arrange things so as to enable any number of multiples to be passed in. Scala's simplest and most preferred way to do this is with a List. Rather than try to explain it, here's the code that initially implements it.

Console.println("functionalWithParameters2Multiples.sum=" + functionalWithParameters2Multiples(10, List(3, 5)))
...
    def functionalWithParameters2Multiples(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    (floor until ceiling).filter(n => {(n % multiples.head == 0) || (n % multiples.tail.head == 0)}).sum
  }

So, the method's signature (parameter specification) is now allowing n multiples. We must now figure out how to check against all of the entries in "multiples" to see if the modulo is 0. The first number that returns a modulo of 0 means we need to indicate the number is valid to be added to the sum. The most obvious way to change this is to create a function which takes the current number as a parameter and then returns true if any entry in the multiples list can be evenly divided by it. That looks something like this.

Console.println("functionalWithParametersNMultiples.sum=" + functionalWithParametersNMultiples(10, List(3, 5)))
...
  def functionalWithParametersNMultiples(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    def isMultiple(n: Int) : Boolean = {
      var result = false
      var list = multiples
      while (!result && (list != Nil)) {
        result = (n % list.head == 0)
        list = list.tail
      }
      result
    }
    (floor until ceiling).filter(n => {isMultiple(n)}).sum
  }

I like the fact that Scala allowed me to create a helper function within the method that needed it. And notice how the helper function had access to the method's parameters. I didn't have to pass it the "multiples" parameter. It was already in scope for my function.

Now, the "isMultiple" function is still of the imperative style (note there are two variables defined as var). So, what's required to convert this function to be much more of the "functional style"? Not relying upon the vars. And from what I can tell, not being an experienced functional programmer myself, it will tend in the direction of being recursive, i.e. a method that calls itself. If that confuses you, don't worry, it does me too. And for me, it's also an ingrained big NO-NO! For stack based languages (which Java is), it's problematic to use recursion as a stack overflow is so easy to bumble into. However, Scala is not Java and so one is encouraged to find the functional recursive way to resolve a method like "isMultiple". Here's my first bash at it:

Console.println("functional.sum=" + functional(10, List(3, 5)))
...
  def functional(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    def isMultiple(n: Int) : Boolean = {
      def isMultipleA(list: List[Int]) : Boolean = {
        if (list == Nil)
          false
        else
          if (n % list.head == 0)
            true
          else
            isMultipleA(list.tail)
      }
      isMultipleA(multiples)
    }
    (floor until ceiling).filter(n => {isMultiple(n)}).sum
  }

And there you have it. Moving all the way from the original hard coded "Java without Semicolons" original to the fully functional conclusion. A full version of the final Scala Object class is just beyond the "Extra Bonus Thinking Credit" section.

UPDATE 2011/Jul/16 - 14:21 CDT:
While I was happy with being able to write the recursive loop above when implementing isMultiple(), I was annoyed as it still had a imperative feel to it. The Scala collection library offers numerous ways to solve this kind of problem. And I am just new enough to Scala, it seemed a better way to solve it was just outside my reach of understanding (partly my intuition has not developed around the collections and partly because the Scala syntax is still pretty distracting to me with all the "optional" aspects). However, my mind kept drifting back to this particular aspect of this solution and I continued to be irritated by it.

So, today I decided to try and scratch the itch. I wanted to see if there was some way to write a Scala one-liner for this. There is for the original problem (you can see it above in the mostlyFunctional() implementation - instead of defining the constants above, just place the literals into the 5th line which does all the processing). However, I wanted a one-liner for my "extended requirements" version.

I quickly stumbled upon the "exists()" method in the collections library on List. That seemed to be the right method to use. Now, how to get the two collection library methods, "filter" and "exists" to work together in a single line. I got the right solution the first time. However, I had to take a couple stabs at it as I kept getting the syntax incorrect. Man, am I looking forward to having all the syntax occur as automatic and intuitive to me. It's SO distracting right now.

Anyway, here's the solution where the recursive isMultiple() has been replaced with the exists() method:

Console.println("functional.sum=" + functional(10, List(3, 5)))
...
  def functional2(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    (floor until ceiling).filter(n => {multiples.exists(x => (n % x) == 0)}).sum
  }

I am very excited about Scala and leveraging it's collections library. It's freaking AWESOME!


Extra Bonus Thinking Credit:
For extra bonus credit, there is a solution that is O(1) for this particular problem. Care to see if you can figure it out?

All Code Collected in Once Place (from above):

object Problem001 extends App {
  //http://projecteuler.net/index.php?section=problems&id=1
  override def main(args : Array[String]) : Unit = {
    javaWithoutSemicolons
    headedTowardsFunctional
    mostlyFunctional
    mostlyFunctionalWithParameters(1, 10, 3, 5)
    Console.println("functionalWithParameters.sum=" + functionalWithParameters(1, 10, 3, 5))
    Console.println("functionalWithParametersDefaultFloor.sum=" + functionalWithParametersDefaultFloor(10, 3, 5))
    Console.println("functionalWithParameters2Multiples.sum=" + functionalWithParameters2Multiples(10, List(3, 5)))
    Console.println("functionalWithParametersNMultiples.sum=" + functionalWithParametersNMultiples(10, List(3, 5)))
    Console.println("functional.sum=" + functional(10, List(3, 5)))
  }
  def javaWithoutSemicolons : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    var sum = 0
    for (i <- floor until ceiling)
      if ((i % multiple3 == 0) || (i % multiple5 == 0))
        sum = sum + i
    Console.println("javaWithoutSemicolons.sum=" + sum)
  }
  def headedTowardsFunctional : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    val numberRange = floor until ceiling
    val validMembers = numberRange.filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)})
    val sum = validMembers.sum
    Console.println("headedTowardsFunctional.sum=" + sum)
  }
  def mostlyFunctional : Unit = {
    val floor = 1
    val ceiling = 10
    val multiple3 = 3
    val multiple5 = 5
    Console.println("mostlyFunctional.sum=" + (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum)
  }
  def mostlyFunctionalWithParameters(floor: Int, ceiling: Int, multiple3: Int, multiple5: Int) : Unit = {
    Console.println("mostlyFunctional.sum=" + (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum)
  }
  def functionalWithParameters(floor: Int, ceiling: Int, multiple3: Int, multiple5: Int) : Int = {
    (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum
  }
  def functionalWithParametersDefaultFloor(ceiling: Int, multiple3: Int, multiple5: Int, floor: Int = 1) : Int = {
    (floor until ceiling).filter(n => {(n % multiple3 == 0) || (n % multiple5 == 0)}).sum
  }
  def functionalWithParameters2Multiples(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    (floor until ceiling).filter(n => {(n % multiples.head == 0) || (n % multiples.tail.head == 0)}).sum
  }
  def functionalWithParametersNMultiples(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    def isMultiple(n: Int) : Boolean = {
      var result = false
      var list = multiples
      while (!result && (list != Nil)) {
        result = (n % list.head == 0)
        list = list.tail
      }
      result
    }
    (floor until ceiling).filter(n => {isMultiple(n)}).sum
  }
  def functional(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    def isMultiple(n: Int) : Boolean = {
      def isMultipleA(list: List[Int]) : Boolean = {
        if (list == Nil)
          false
        else
          if (n % list.head == 0)
            true
          else
            isMultipleA(list.tail)
      }
      isMultipleA(multiples)
    }
    (floor until ceiling).filter(n => {isMultiple(n)}).sum
  }
  def functional2(ceiling: Int, multiples: List[Int], floor: Int = 1) : Int = {
    (floor until ceiling).filter(n => {multiples.exists(x => (n % x) == 0)}).sum
  }
}

Wednesday, May 4, 2011

Portal 2 distraction (and other excuses for no posts here in awhile)...

I have yet to write the first pass of the Scala version of Life modeled on the Java version from the previous post. Partly it's because work has become quite overwhelming recently. Partly it's because I know once I start writing Scala, I am going to dread and resist writing much more Java. And then finally, it's because Portal 2 came out and I am spending tons of time playing it.

I will return to the Scala Life thread and continue. In the meantime, I found a link which I thought might be very useful to those who do Java and want to see practical uses for Scala. This Wiki is great at presenting some code in Java and then presenting the Scala code pointing out why it's a desirable improvement. Enjoy!

Saturday, March 26, 2011

Objectifying Java's Life...

This is the second post in the series which started with "Scala Comes to Life".

As much as I want to jump right to the Scala version of the Java code, I must wait. The Java code needs to be "cleaned up" at least to the point where it's similarity to the Scala code can be detected. And that's going to be a bit challenging as I have little motivation to want to write even more Java code. Alas, it must be done.

So, what needs to be done and in what order? The overall objective (for now) is to refactor the Java code towards the values of OO design, performance, configuration, multi-threading, etc.. This means the design needs to incorporate default immutability to easily enable parallel processing (later).

Frame.java:
In the current version of the code, there are references to boolean[][] content everywhere. This is a problem as arrays in Java are immutable (Sidenote: I sure wish Scala had decided to implement immutable arrays...sure could have save a tonnage of time for code needing to transition from Java to Scala). And if we are going to have default immutability, we need to change that implementation. This exposes that there are actually two problems; A) we have to figure out how to move to immutability and B) an implementation detail has "escaped" encapsulation. So, it appears we have our first strong candidate for a class.

So, we will create the class Frame and it's sole goal is to generate immutability around boolean[][] content. Here is a first pass at the new class in attempt to make it immutable (contain and control access to the array):

package com.blogspot.fromjavatoscala.life.java;

public class Frame {
  private boolean[][] content;
  
  public Frame(boolean [][] content) {
    this.content = content;
  }
  
  public boolean[][] getContent() {
    return this.content;
  }
}

This is a good start as there is no mutator/setter which moves us towards the goal of immutability. However, the accessor/getter is returning the internal array which is a leak in the immutability contract. Why? Any client who called getContent() can then make changes to the array returned and those changes will occur to the original object encapsulated array at this.content.

So, we must change the accessor/getter to return a copy of the array. This is called a defensive copy. The client might not and even probably won't change the contents of the array. However, that's not sufficient if one is needing the level of guaranteed immutibility, especially in a multi-threaded environment. So, the getContent() method now looks like this:

public boolean[][] getContent() {
    return this.content.clone(); //defensive copy
  }

Looks good, right? Well, while it is better, there's still a mutability leak. Can you find it? If you look closely, you will see that content is an array of arrays. While we are now defensively copying the over-all array, we are not also copying the sub-arrays. So, any modifications made to those sub-arrays by an untoward client would leak through to our object. Annoying subtlety, huh?

So, now the code just to return a defensive array just got a bit heavier; i.e. let's add some boilerplate to the boilerplate accessor/getter:

public boolean[][] getContent() {
    boolean[][] result = new boolean[this.content.length][]; //defensive copy
    for (int i = 0, count = result.length; i < count; ++i) {
      result[i] = this.content[i].clone(); //defensive copy
    }
    return result;
  }

Now, we need to also make sure that when the object is created, it is valid. This is also known as checking the invariants in terms of Design By Contract. To do this, we need to verify that the value passed in is valid. After verifying it exists (is not null and has a length greater than 0), we need to verify that it is uniform (all of the sub-arrays have the same length). So, let's add some more boilerplate, this time to the constructor, shall we?:

public Frame(boolean [][] content) {
    if (!(content != null)) {
      throw new NullPointerException("content must not be null");
    }
    if (!(content.length > 0)) {
      throw new IllegalArgumentException("content.length must be greater than 0");
    }
    if (!(content[0] != null)) {
      throw new IllegalArgumentException("content[0] must not be null");
    }
    if (!(content[0].length > 0)) {
      throw new IllegalArgumentException("content[0].length must be greater than 0");
    }
    for (int i = 1, count = content.length; i < count; ++i) {
      if (!(content[i].length == content[0].length)) {
        throw new IllegalArgumentException
            (   "content[" + i + "].length [" + content[i].length
              + "] must be equal to content[0].length [" + content[0].length + "]"
            );
      }
    }
    this.content = content;
  }

We're done, right? Nope! There's one more mutability leak staring us right in the face. Again, can you see it? I didn't initially, either. It's subtle, but it's the final line in constructor above. We are just assigning the reference. That means the caller can still mutate the reference changing our object's state. So, just like we had to defensively copy the accessor/getter, we now have to defensively copy the passed in array. And it's even a bit more difficult than that. Do we copy and THEN check the contents? Or do we check the contents and then copy? If we do the former, we lower (but don't eliminate) our risk profile that the caller will modify it during our copy operation. If we do the latter, it's possible for the caller to modify it into an invalid state right AFTER we have run our validation checks and just BEFORE we make the copy.

Ugh! I feel some more boilerplate coming on. Are arrays really worth this much trouble to get the simple behaviors we need? Rather than clutter the constructor with all the code for a safer (but still not perfectly safe) deep copy of the array, here's a utility method:

private boolean[][] deepCopy(boolean[][] content) {
    boolean[][] result = null;
    if (content != null) {
      synchronized(content) { //do our best to make this as multi-threaded friendly as possible
        result = new boolean[content.length][];
        for (int i = 0, count = content.length; i < count; ++ i) {
          if (content[i] != null)
          {
            synchronized(content[i]) {
              result[i] = content[i].clone();
            }
          }
        }
      }
    }
    return result;
  }

And now we have to modify the constructor so that it is using the copy as opposed to the original provided by the content parameter. Here's what that looks like:

public Frame(boolean [][] content) {
    boolean[][] threadSafeCopy = deepCopy(content);
    if (!(threadSafeCopy != null)) {
      throw new NullPointerException("content must not be null");
    }
    if (!(threadSafeCopy.length > 0)) {
      throw new IllegalArgumentException("content.length must be greater than 0");
    }
    if (!(threadSafeCopy[0] != null)) {
      throw new IllegalArgumentException("content[0] must not be null");
    }
    if (!(threadSafeCopy[0].length > 0)) {
      throw new IllegalArgumentException("content[0].length must be greater than 0");
    }
    for (int i = 1, count = threadSafeCopy.length; i < count; ++i) {
      if (!(threadSafeCopy[i].length == threadSafeCopy[0].length)) {
        throw new IllegalArgumentException
            (   "content[" + i + "].length [" + threadSafeCopy[i].length
              + "] must be equal to content[0].length [" + threadSafeCopy[0].length + "]"
            );
      }
    }
    this.content = threadSafeCopy;
  }

And that completes our creating the basic immutable class for Frame. We can now safely assert that once an instance of Frame has been constructed, like an instance of String, it will remain unchanged for the duration of it's existence. Here's the final version of Frame.java:

package com.blogspot.fromjavatoscala.life.java;

public class Frame {
  private boolean[][] content;
  
  public Frame(boolean [][] content) {
    boolean[][] threadSafeCopy = deepCopy(content);
    if (!(threadSafeCopy != null)) {
      throw new NullPointerException("content must not be null");
    }
    if (!(threadSafeCopy.length > 0)) {
      throw new IllegalArgumentException("content.length must be greater than 0");
    }
    if (!(threadSafeCopy[0] != null)) {
      throw new IllegalArgumentException("content[0] must not be null");
    }
    if (!(threadSafeCopy[0].length > 0)) {
      throw new IllegalArgumentException("content[0].length must be greater than 0");
    }
    for (int i = 1, count = threadSafeCopy.length; i < count; ++i) {
      if (!(threadSafeCopy[i].length == threadSafeCopy[0].length)) {
        throw new IllegalArgumentException
            (   "content[" + i + "].length [" + threadSafeCopy[i].length
              + "] must be equal to content[0].length [" + threadSafeCopy[0].length + "]"
            );
      }
    }
    this.content = threadSafeCopy;
  }
  
  private boolean[][] deepCopy(boolean[][] content) {
    boolean[][] result = null;
    if (content != null) {
      synchronized(content) { //do our best to make this as multi-threaded friendly as possible
        result = new boolean[content.length][];
        for (int i = 0, count = content.length; i < count; ++ i) {
          if (content[i] != null)
          {
            synchronized(content[i]) {
              result[i] = content[i].clone();
            }
          }
        }
      }
    }
    return result;
  }
  
  public boolean[][] getContent() {
    boolean[][] result = new boolean[this.content.length][]; //defensive copy
    for (int i = 0, count = result.length; i < count; ++i) {
      result[i] = this.content[i].clone(); //defensive copy
    }
    return result;
  }
}

Whew! For such a simple notion conceptually, the amount of boilerplate overhead got pretty high very quickly, huh? Onward ho!

FrameFactory.java:
Next up, we need to produce instances of Frame. There are two basic events where a Frame needs to be created; A) establishing an initial state and B) deriving a state from the state of an existing frame (i.e. applying the rules). A typical way to approach this design problem is to use the Factory pattern. A factory is used to control all the instantiations of a class (or set of classes). So, we will create a class called FrameFactory. It will have several methods correlating to these two basic events. Here's the first pass (for the very observant, I will cover the unaddressed Frame.next() method shortly):

package com.blogspot.fromjavatoscala.life.java;

import java.util.Random;

public class FrameFactory {
  public static Frame first(boolean[][] content) {
    return new Frame(content);
  }
  
  public static Frame firstRandom(int width, int height) {
    return firstRandom(width, height, null);
  }
  
  public static Frame firstRandom(int width, int height, Random random) {
    return first(generateRandomContent(width, height, random));
  }
  
  public static Frame next(Frame current) {
    if (!(current != null)) {
      throw new NullPointerException("current must not be null");
    }
    return current.next();
  }
  
  private static boolean[][] generateRandomContent(int width, int height, Random random) {
    if (!(width > 0)) {
      throw new IllegalArgumentException("width must be greater than 0");
    }
    if (!(height > 0)) {
      throw new IllegalArgumentException("width must be greater than 0");
    }
    Random randomToUse = (random != null) ? random : new Random();
    boolean[][] result = new boolean[height][];
    for (int y = 0, yCount = result.length; y < yCount; ++y) {
      result[y] = new boolean[width];
      for (int x = 0, xCount = result[y].length; x < xCount; ++x) {
        result[y][x] = randomToUse.nextBoolean();
      }
    }

    return result;
  }
}


Frame.java - next():
The last touch is to update the class Frame with the next() method, copying and adapting the implementation from FrameVersion1. The full class with the new content looks like this:

package com.blogspot.fromjavatoscala.life.java;

public class Frame {
  private static final int[][] NEIGHBOR_OFFSETS = //{x, y} pairs
      new int[][] {   {-1, -1}, {0, -1}, {1, -1}
                    , {-1,  0},          {1,  0}
                    , {-1,  1}, {0,  1}, {1,  1}
                  };
  
  private boolean[][] content;
  
  public Frame(boolean [][] content) {
    boolean[][] threadSafeCopy = deepCopy(content);
    if (!(threadSafeCopy != null)) {
      throw new NullPointerException("content must not be null");
    }
    if (!(threadSafeCopy.length > 0)) {
      throw new IllegalArgumentException("content.length must be greater than 0");
    }
    if (!(threadSafeCopy[0] != null)) {
      throw new IllegalArgumentException("content[0] must not be null");
    }
    if (!(threadSafeCopy[0].length > 0)) {
      throw new IllegalArgumentException("content[0].length must be greater than 0");
    }
    for (int i = 1, count = threadSafeCopy.length; i < count; ++i) {
      if (!(threadSafeCopy[i].length == threadSafeCopy[0].length)) {
        throw new IllegalArgumentException
            (   "content[" + i + "].length [" + threadSafeCopy[i].length
              + "] must be equal to content[0].length [" + threadSafeCopy[0].length + "]"
            );
      }
    }
    this.content = threadSafeCopy;
  }
  
  private boolean[][] deepCopy(boolean[][] content) {
    boolean[][] result = null;
    if (content != null) {
      synchronized(content) { //do our best to make this as multi-threaded friendly as possible
        result = new boolean[content.length][];
        for (int i = 0, count = content.length; i < count; ++ i) {
          if (content[i] != null)
          {
            synchronized(content[i]) {
              result[i] = content[i].clone();
            }
          }
        }
      }
    }
    return result;
  }
  
  public Frame next() {
    boolean[][] result = new boolean[this.content.length][this.content[0].length];
    //iterate through rows
    for (int y = 0, yCount = this.content.length; y < yCount; ++y) {
      //iterate through columns of particular row
      for (int x = 0, xCount = this.content.length; x < xCount; ++x) {
        result[y][x] = calcState(x, y);
      }
    }
    
    return new Frame(result);
  }
  
  private boolean calcState(int x, int y) {
    boolean result = false;
    
    int neighborsAliveCount = 0;
    for (int i = 0, count = NEIGHBOR_OFFSETS.length; (i < count); ++i) {
      int[] offset = NEIGHBOR_OFFSETS[i];
      if (isAlive(x + offset[0], y + offset[1])) {
        ++neighborsAliveCount;
      }
    }
    boolean self = this.content[y][x];
    if (self && (neighborsAliveCount < 2)) {
      result = false; //live cell dies from aloneness (too few live neighbors)
    } else if (    self 
                && ((neighborsAliveCount == 2) || (neighborsAliveCount == 3))
              ) {
      result = true; //live cell lives (sufficient live neighbors)
    } else if (self && (neighborsAliveCount > 3)) {
      result = false; //live cell dies from overcrowding (too many live neighbors)
    } else if ((!self) && (neighborsAliveCount == 3)) {
      result = true;  //dead cell births (precisely enough neighbors)
    }
    
    return result;
  }
  
  private boolean isAlive(int x, int y) {
    boolean result = false;
    
    if (    (y >= 0) && (y < this.content.length)
         && (x >= 0) && (x < this.content[y].length)
       ) {
      result = this.content[y][x];
    }
    
    return result;
  }

  public boolean[][] getContent() {
    boolean[][] result = new boolean[this.content.length][]; //defensive copy
    for (int i = 0, count = result.length; i < count; ++i) {
      result[i] = this.content[i].clone(); //defensive copy
    }
    return result;
  }
}


Main.java:
The last step is to update the Main class to now refer to our new FrameFactory. The edits here ought to be obvious (and if not, you can observe them in bitbucket.org/Mercurial SCM in the Eclipse workspace):

package com.blogspot.fromjavatoscala.life.java;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

  public static void main(String[] args) {
    List<String> frames = new ArrayList<String>();
    Frame frame = FrameFactory.firstRandom(25, 25, new Random(0));
    String output = displayFrame(frame.getContent());
    frames.add(output);
    printOutput(0, output);
    boolean finished = false;
    int i = 0;
    while (!finished) {
      frame = frame.next();
      output = displayFrame(frame.getContent());
      finished = frames.contains(output);
      if (!finished) {
        frames.add(output);
        printOutput(i + 1, output);
      }
      ++i;
    }
  }
  private static void printOutput(int tick, String output)
  {
    System.out.println("Tick #" + tick);
    System.out.println(output);
  }
  
  private static String displayFrame(boolean[][] content) {
    String result = "";
    
    for (int y = 0, yCount = content.length; y < yCount; ++y) {
      for (int x = 0, xCount = content.length; x < xCount; ++x) {
        result += (content[y][x] ? "#" : " ");
      }
      result += "\n";
    }
    
    return result;
  }
}

And that's all she wrote. Try it out. The execution results are identical to those of the previous post. The code refactoring to get the Java code closer to an "ideal" state resulted in an almost doubling of the lines of code. This seems pretty consistent with my overall Java coding experience.

The code is located on bitbucket.org/Mercurial SCM as an Eclipse workspace. Don't hesitate to play with it. And I am open to any and all feedback.

What's Next:
My next post ought to be my first post to feature Scala code. I am so looking forward to it while I am simultaneously dreading it. My anticipation comes from the expressive power I can already feel Scala offers (ex: immutability by default). My dread comes from the fear that I will lose my motivation to code in Java ever again. And after 15 years and hundreds of thousands of lines of code with my dearest coding friend, it will be a bittersweet moment to see it begin to fade into my past.

Monday, March 7, 2011

Scala comes to life...

Each time I decide to jump into a new language, I try to find some small simple problem domains within which I can learn to stretch my new wings. It occurred to me the other day that it has been quite some time since I played with Conway's Life Simulation (introduced in "Scientific American" by Martin Gardner in 1970). There are numerous examples life simulators all over the web. And one of my favorite books of all time, "Games of Life: Explorations in Ecology, Evolution and Behaviour" by Karl Sigmund explores it quite liberally and enjoyably.

So, I decided that the quickest way for me to "get going" in Scala was to generate a simple and small version of Life in Java. And then directly convert the class from Java to Scala, treating Scala as "Java without the semicolons". Said more specifically, use Java's imperative style the starting point, a basic clump of digital clay, so-to-speak. And then, over time (and multiple blog entries) I will slowly mold the clay clump into something more useful and interesting.

As a simple recap (which is a copy and paste from the Wiki link - go there to see actual gif animations of the simulation in action), here is the basic domain requirements of Life:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations.
So, my first step is to imagine how I would approach this in Java. My goal is to write a small amount of Java code that achieves this goal. However, it will be quite annoying to have to include all the overhead of having to render the resulting animation. So my very first pass at this problem is to just get the simple rule set working on a relatively simple Java class. The resulting two files are below (and not even very well named). I intend to use github or something equivalent in the future am using bitbucket.org/Mercurial SCM so the code can be viewed in its more natural habitat. However, github was not quite worth the overhead for this first post (which took WAY longer to complete than shows in this resulting "initial" post).

Additionally, while the Java code functions, it is a LONG way from ideal in many ways (OO design, performance, configuration, multi-threading, etc.). However, I figured that it would be more interesting (and fun) if this series showed the evolution of the Java code towards what is considered ideal and just how much boilerplate that ends up requiring. This will create a great basis from which to compare the Scala code, which I hope (and will only be able to do so until I have actually written the Scala code) will be quite a bit shorter with substantially less (if any) boilerplate required.

I am just glad to finally have this post completed. Java code's below. And, the code as an Eclipse workspace is located in a bitbucket.org/Mercurial SCM repository.

Sidenote: What a FREAKING challenge to get code displayed in a blog web page entry. ARGH! Of the +20 hours I spent on this post, +10 of them was chasing all sorts of tangents attempting to figure out how to get the 120 lines of Java code displayed with some semblance of acceptable syntax highlighting. It was worth trying to figure it out, though. I really like the results. And now I get to use it in all future posts, pretty simply, too. If you are interested, here's a link to the solution I eventually found (and an awesome helper).

File 1 of 2: FrameVersion1.java (NOT ideal code - super simple first pass)


package com.blogspot.fromjavatoscala.life.java;

public class FrameVersion1 {
  public static final int[][] NEIGHBOR_OFFSETS = //{x, y} pairs
    new int[][] {
                    {-1, -1}, {0, -1}, {1, -1}
                  , {-1,  0},          {1,  0}
                  , {-1,  1}, {0,  1}, {1,  1}
                };
  
  public static boolean[][] next(boolean [][] content) {
    boolean[][] result = new boolean[content.length][content[0].length];
    //iterate through rows
    for (int y = 0, yCount = content.length; y < yCount; ++y) {
      //iterate through columns of particular row
      for (int x = 0, xCount = content.length; x < xCount; ++x) {
        result[y][x] = calcState(content, x, y);
      }
    }
    
    return result;
  }
  
  private static boolean calcState(boolean [][] content, int x, int y) {
    boolean result = false;
    
    int neighborsAliveCount = 0;
    for (int i = 0, count = NEIGHBOR_OFFSETS.length; (i < count); ++i) {
      int[] offset = NEIGHBOR_OFFSETS[i];
      if (isAlive(content, x + offset[0], y + offset[1])) {
        ++neighborsAliveCount;
      }
    }
    boolean self = content[y][x];
    if (self && (neighborsAliveCount < 2)) {
      result = false; //live cell dies from aloneness (too few live neighbors)
    } else if (    self 
                && ((neighborsAliveCount == 2) || (neighborsAliveCount == 3))
              ) {
      result = true; //live cell lives (sufficient live neighbors)
    } else if (self && (neighborsAliveCount > 3)) {
      result = false; //live cell dies from overcrowding (too many live neighbors)
    } else if ((!self) && (neighborsAliveCount == 3)) {
      result = true;  //dead cell births (precisely enough neighbors)
    }
    
    return result;
  }
  
  private static boolean isAlive(boolean [][] content, int x, int y) {
    boolean result = false;
    
    if (    (y >= 0) && (y < content.length)
         && (x >= 0) && (x < content[y].length)
       ) {
      result = content[y][x];
    }
    
    return result;
  }
}




File 2 of 2: Main.java (NOT ideal code - super simple first pass)

package com.blogspot.fromjavatoscala.life.java;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

  public static void main(String[] args) {
    List<String> frames = new ArrayList<String>();
    boolean[][] content = generateInitialContent();
    String output = displayFrame(content);
    frames.add(output);
    printOutput(0, output);
    boolean finished = false;
    int i = 0;
    while (!finished) {
      content = FrameVersion1.next(content);
      output = displayFrame(content);
      finished = frames.contains(output);
      if (!finished) {
        frames.add(output);
        printOutput(i + 1, output);
      }
      ++i;
    }
  }
  private static void printOutput(int tick, String output) {
    System.out.println("Tick #" + tick);
    System.out.println(output);
  }
  
  private static boolean[][] generateInitialContent() {
    boolean [][] result = new boolean[25][25];
    
    //results in 121 frames before repeating
    Random random = new Random(0); 
    for (int y = 0, yCount = result.length; y < yCount; ++y) {
      for (int x = 0, xCount = result.length; x < xCount; ++x) {
        result[y][x] = random.nextBoolean();
      }
    }
    
    return result;
  }
  
  private static String displayFrame(boolean[][] content) {
    String result = "";
    
    for (int y = 0, yCount = content.length; y < yCount; ++y) {
      for (int x = 0, xCount = content.length; x < xCount; ++x) {
        result += (content[y][x] ? "#" : " ");
      }
      result += "\n";
    }
    
    return result;
  }
}

Saturday, February 12, 2011

Impact of maturing distinctions (or how the need for increasingly rich information generates software engineering challenges)...

One of the things that I have noticed over my years as a software engineer as been the process of capturing some particular set of "requirements" and constituting them as rules in a software system I end up building. And then over time, the need for the system to be able to respond to subtle increases in information distinctions exposes software adaptation blocks; i.e. software design fragility. And my response has been to try to design defensively around these areas. The end result is that not accounting for distinctions early can generate changes that hit the core system design and ripple throughout the resulting complex system. And accounting for the more refined distinctions too early can prematurely make the system too complex increasing risks to the system's continued useful existence.

Rather than talk in abstractions, here's a more concrete example of the process of a particular data point in a system "growing" to need higher degrees of details in the information.

Let's use the notion of something nice and nebulous, hunger. The requirement is to include some value to indicate whether an instances of a digital organism has it's hungry signal turned on. In Java, this would be represented as a boolean, as in some field of a class:

private boolean hungry;

After we've been working on the overall system for awhile (possibly already released a version of it to the public/production/some-irreversible-external-thing), we discover that we need a bit more information. Rather than track hunger. We are really tracking the degree of motivation to seek food based on a set of discrete values; HIGH, MODERATE and LOW.

Obviously, this trinary of discrete values won't fit in our boolean. This means we have to change from boolean to something else. Thanks to our looking ahead, we can see there may be additional discrete values added in the future (imagine something like WEE_BIT_PECKISH or EXPLOSIVELY_BLOATED), so we just make the value an int (or an Enumeration which is a more effectively adaptive way to essentially use the equivalent of an int). And using constants, we now represent the trinary. So, we enhanced the ability for the variable to represent information from 1 bit (boolean) to 2 bits (trinary) and with the ability to more easily expand in the future to as much as 32 bits. It would now look something like this:


public enum HungerLevel{
    HIGH
  , MODERATE
  , LOW
}
private HungerLevel hungerLevel;


Again, the system has been "published" when the next requirement comes in. There is a need to be able to capture hunger more specifically, as a decimal number (pretend that hunger is now being discerned by testing for the presence/absence of specific neurochemicals). So, we need to move to a continuous value, or scalar.

private double hungerDegree;

And a short time later, there is a new discovery. It turns out that the human brain has two separate modules for reflecting the individual's hunger state. One indicates that the person is needing to eat to elevate blood sugar. And the other indicates the person is sated as enough fat has been detected to have been ingested. So, now TWO scalars are needed. And yes, this why you can feel very full after a huge turkey day dinner and still crave more pumpkin pie.


private double satiety; //affected by recent fat level intake
private double bloodsugar; //affected by recent insulin spike and drop-off 


Additionally, it turns out these values shift independently over time. So, we need to add a third variable, time, and capture the two scalars for each time unit.

private double[][] digestiveHormonalState = new double[][] {{s1, b1}, {s2, b2}, {s3, b3}};

So, we have moved from a boolean to a discrete to a scalar to a pair of scalars to a time based array of pairs of scalars as the system requirements adapted. This plays havoc with most software APIs. However, this model is strongly reflective of the real world problems facing a software engineer as a system is attempting to be designed, built and maintained over time.

There's no huge insight here. I just found this pattern to occur repeatedly in human meaning systems outside of software engineering. And I found the pattern interesting enough to share. And I am looking for ways to be able to capture meaning adaptations (i.e. enhanced distinctions) while minimizing the overall impact they have to systems built upon them.

Saturday, February 5, 2011

Attumi (email Batch D) - A Java-like Language with default immutability

This is the fifth in a series of 5 posts:

This is the final post showing the self-email-chain I wrote in response to my creative brainstorm started in 2010/November regarding my designing a "What's next?" language to follow Java.

Here is the fourth and final batch notes, mostly unedited:

<BATCH_D>
  1. make sure that interfaces provide extendable/configurable factories for implementations based on general performance requirements (as opposed to encoding them in a particular implementation strategy available at the time the code was written) - this will enable better and deeper implementations to be written, thereby elevating the available performance without code recompiles - it will also allow better self-tracking resources which can replace their implementations with better strategies through accumulated metrics (perhaps with secondary thread "watchers" who keep the metrics costs away from the primary code pathway)
  2. facilitate collections code mapping to support a SQL query style syntax (should work very efficiently with immutable object trees) - thought based on this FLOSS extension for Java: http://josql.sourceforge.net/index.html
  3. vastly reduce the cost of composition to reduce the desire to use inheritance - consider having a class able to implement an interface and also specify the internal reference to a class to which all non-reimplemented methods will be forwarded (UnassignedReferenceException thrown if method forwarding attempted and instance has not assigned the internal reference)
  4. move equals() and hasCode() out of Object and into an interface - logically groups the functionality so that if one is reimplemented, so is the other - do not implement at Object...do like Eiffel and have as independent implementation which can be specialized/extended via inheritance or interface/composition
  5. consider adding Iterable interface by which is optimized for use in for() loops
  6. provide tuples (temporary grouping of values without methods without having to formally define a class, i.e. a temporary struct) for both arguments into a method (like Java's varargs) and as a return value - should minimize amount of boilerplate "temp" code required to implement simple composition and re-implementation classes and methods
  7. default to NotNullable for all declarations and require Null be explicitly requested/defined
  8. default to methods NOT being overridable (must explicitly identify method as being overridden)
  9. can allow decendants to extend (don't have to make final) immutable classes as the immutable guarantee holds
  10. when determining requirements for collection type, use these characteristics: A) identity duplicates allowed (==), B) value duplicates allowed (.equals), C) value similarity allowed (Comparator), D) iterator ordered (Comparable.compareTo()), E) immutibility, F) degree in which to favor speed (of specific operations) versus space (weak and/or lazily instantiated context) - use a builder with these parameters to return appropriate implementation to specific interface - enable plug-in replacements at Builder itself (for replacement implementations)
  11. in specialized file for enhancing execution optimization logic, allow alternative lower level optimization (perhaps even assembly) where the context of the assumptions outlining the use of the alternative code would be asserted and it would only call the alternative if the assumptions were true
  12. consider all potential sources of side-effect randomness and attempt to eliminate to allow perfect deterministic models to be written without accidental side-effects (ex: Java HashSet/HashMap.keySet() and the multi-threaded GC interaction resulting from the default implementation of hashcode being an interpretation of the instance's memory location - use in thread Random)
  13. Research Google's Go as a possible influencer on direction of design : http://golang.org/doc/go_faq.html
  14. Good Java concurrency subtlety article (influence how operators are grouped - increase domain of atomicity - or explicitly disallow the syntax - i.e. assume immutable and multi-threaded throughout the entire language - create "safe zones for mutation" and for "thread communication"): http://www.ibm.com/developerworks/java/library/j-concurrencybugpatterns/index.html
  15. Nice coverage of using inheritance in OO versus delgates in functional languages (need to facilitate both) using Clojure: http://www.ibm.com/developerworks/java/library/j-clojure-protocols/index.html
</BATCH_D>

As I said with batches A, B and C, depending upon interest, I will consider diving into some/all of these and exploring my thoughts and reasoning.

Attumi (email Batch C) - A Java-like Language with default immutability...

This is the fourth in a series of 5 posts:

This is the next post showing the self-email-chain I wrote in response to my  creative brainstorm started in 2010/November regarding my designing a "What's next?" language to follow Java. 

Here is the third batch (of four) notes, mostly unedited:

<BATCH_C>
  1. define notion of an init-once, read many method (for lazy initialization) to clear overhead of check for initialization every time method called
  2. default of transparency (everything is public) and hidden state must be specifically called out
  3. check out http://fantom.org/ for their approach to multi-threading (i.e. actor based with immutability)
  4. allow passing parameter by name (while ensuring no speed gain/loss for using name as opposed to position - use stubbed API call point to map name to position
  5. allow defaulting of unpassed parameters - when combined with parameter by name, vastly reduces boilerplate code for implementing class constructors
  6. allow struct/tuple (multi-value) return instance so return from function can be multi-dimensional without formalization of class definition (temp class which will likely reify into real class later)
  7. consider removing null entirely (force the meaning of empty, or undefined)
  8. mature versions of modules, packages, access along with something like partial classes (develop requirements for information hiding versus deployment versus security) 
  9. promote aspect oriented programming (useful for logging/transactional separated from functional code) - consider it being useful for debugging (and during debugging, allow aspects to be explicitly skippable)
  10. consider defining a "test" characteristic that when a class is defined as a test, it can have access to more private parts of a package/module so as to allow for exhaustive testing without impacting the design by forcing the package/module to expose things to the world just so testing can be complete
  11. facilitate immutable pathing to enable soft/weak reference implementation - lazy instantiation pathway can be marked with degree of expense in regenerating so that how that reference is stored (more local to CPU all the way to some form of swapped network based storage) enabling a continuously changing set of options for memory locality - also enables regions to cycle through heating up (come closer to CPU) and then cooling down (push closer to network storage)
</BATCH_C>

As I said with batches A and B, depending upon interest, I will consider diving into some/all of these and exploring my thoughts and reasoning.

Friday, February 4, 2011

Attumi (email Batch B) - A Java-like Language with default immutability

This is the third in a series of 5 posts:

My last post, ...(email Batch A), explained the creative brainstorm started in 2010/November regarding my designing a "What's next?" language to follow Java. And I shared the first email covering my first batch of self-directed notes for exploring the things I would want to consider incorporating into a design.


Here is the second batch (of four) notes, mostly unedited:

<BATCH_B>
  1. consider use of transactional memory model to handle concurrency (as opposed to lock based model), push distributed (Erlang-like) model into separate/library/framework
  2. Source occurs as a named resource (name spaces are merely dot separated identifiers) and stored as ASTs (expressed both in platform independent binary as well as well formed Schema defined XML file) as opposed to the currently more common text file - enables ability to have text representation be human language independent (i.e can be represented in English, Chinese, etc.), allows personalized layout and indentation (avoiding entirely issues around syntax formatting flame-wars) and enables source to reside in a file, set of folders/files, different kinds of DB, over network streamed from undefined data source conforming to API (ex: Web-dav)
  3. when defining reference, possible states {once-at-definition, *once-post-definition*, many} X {*no-null*, nullable} where * is default
  4. when defining class, possible states {*immutable*, mutable} X {*not-derivable*, derivable} where * is default
  5. enforce immutable by requiring all references be to immutables, i.e. if class is immutable, the semantics are guaranteed to be immutable all the way down through any references chains (will enforce acyclic graph, i.e. child cannot contain reference to parent or parent's parent, etc.) - must use external supplemental data structure to facilitate traversing child to parent relationships
  6. execution start-up will pass "main()" a map of key/value pairs - which will be able to be represented as a simple property file/stream, XML file/stream, etc. will be completely generified to make code not care how the execution started and obtained the initial values
  7. design ability for an immutable data structure to lazily fill in state without requiring all state to be completed in definition by the time the constructor terminates (may be challenging to prove from a code path perspective, if not careful)
</BATCH_B>

As I said with batch A, Depending upon interest, I will consider diving into some/all of these and exploring my thoughts and reasoning.

Attumi (email Batch A) - A Java-like Language with default immutability

This is the second in a series of 5 posts:

Early last November (not December like I said in my "Why?" post), I had lots of things rolling around in my head about what to do "next" after Java. I wanted to complete my board game rules model in Java. I toyed with doing the UI. I was just not at all attracted to the tonnage of boilerplate required to do a Java UI with any tool. And I was already getting sick of Java boilerplate anyway even with all the help from the numerous tools Eclipse provides.

And it looked like Objective-C was just going to be tons more boilerplate, only I had to also learn and become competent in Objective-C and the IOS libraries, first. Not at all attractive, either. I had immersed myself in the C#/.NET books and was actually looking forward to some change and some new things (like LINQ, real properties, etc.) which put C# significantly less long in the tooth as Java (I know, I know, it's coming in Java 7, or 8...or whenever the hell Oracle says it will...eff Oracle).

I didn't plan the thought avalanche. I never do. They come to me completely unbidden. I already have several programming projects and business I wanted to start. And I had at least two business completely unrelated to technology (use, but are not driven by) I was playing with building. My creative juices were flowing in those other areas. And then on the way to work during my commute, it hit me like a lightening bolt in the form of a question...

"What if I was to modify Java until it's default state aligned with my primary use case pathways? What if I made Java immutable by default, and then made mutability a pain to get to and if used?"

What if being mutable had to be defined as "the unsafe side-effecting dangerous malicious memory leaked thread-deadlocking code is here" via copious annotations assisting the compiler (which would complain vociferously if the code writer were to forget the slightest "thar be dragon har" indications)? And that was just the start. Once I had the seed idea to take Java and shift it about until it suited me, I could then make it mean the removal of lots of boilerplate, re-prioritize things that mattered, rip out legacy crap (like raw collections) and then like. It was like a fantastic thought experiment all in my own private programmer's fairy-land.

I then began to privately email myself. Anytime I was coding on any project, home or work, I would just jot down some thoughts around the "pain point" and solution like notions that would come to me. That way, I would just continuously have the stream of thoughts and be able to adapt and play with them as needed. It was so much fun. I could now sit back and just enjoy writing Java code while my brain solved both the current coding problems the "Java" way and another part of my brain was off playing with how it really should work. And the modifications were all the way from very low level implementation efficiencies to very high level pattern extractions/abstractions.

So, what did those thoughts look like? Well, I was going to do tons of clean up on my notes and make them all spiffy. However, I would rather do more fun things like read more about Scala, and code in Scala, and make suggestions/requests to the Scala team around things that burped up for me during the last three months. I made all these notes before venturing out to start researching existing JVM alternatives. I had not investigated a single JVM language until AFTER I wrote all these notes. So, in a way, it was quite pleasant to have a strong sense of what I wanted before I actually took the leap and started researching other languages which might fill the bill. Besides, it's not my style. I like problem solving, even problems that have already been solved. It's why I love to play Go. It's why I do Sudoku, it's why I dig little puzzle games like Osmos and Chime.

Here is the first batch (of four) notes, mostly unedited:
<BATCH_A>
Consider an OO language design where immutability was the default:
  1. immutability assumed unless otherwise explicitly called out and specified (use marker interface mutable in similar way abstract is used on abstract classes)
  2. reduce security issues via content changing unexpectedly in deeper structures
  3. create basic method parameter checks (i.e. simplified preconditions for null, ranged values, size, etc. - most all the pre-conditions typically used to validate basic parameters to a constructor)
  4. use builders to have mutable content until ready to build immutable instance (like StringBuilder for strings, include ArrayBuilder for arrays)
  5. all "primatives" are formal Objects and optimized internally for performance value (including arrays)
  6. add option execution suggestion plan to help structure CPU and memory layout for optimally executing
    • can allow array of Integer to be grouped internally into a memory block of ints[] which are then accessed via pointer arithmetic
    • enables faster iterators where boundary checks can be disabled
    • separates the code abstraction definition (i.e. design) from the actual instruction and memory layout generation (i.e. implementation)
  7. optimized relationship with Collections library (allowing for internal implementation to eliminate unnecessary boundary checks)
  8. consider partial construction and lazy instantiation of additional immutable state as important (so as to only engage in CPU and memory for the execution pathways actually used)
  9. ensure only an immutable instance may be passed from one thread to another (reduces memory coordination/collaboration/optimization issues substantially)
  10. an immutable object is state whereas a mutable object has state
  11. when designing Collection builders, ensure specification of requirements (i.e. read heavy, write heavy, etc.) which then interprets and selects implementation (i.e. ArrayList for lots of random access reading, LinkedList for lots of insertion and sequential traversing)
  12. within implementation of actual compiled code, consider a reference to be more than just a memory pointer, but an actual object representing data
    • for an array of Integer, it could be type, count, size of single entry, pointer to start of a memory block
    • for a specific instance of Integer in the array, it could be type, container reference (above), index (and if immutable, the operation for this fetch only has to occur once to the locality needed to operate on it)
  13. Review Java and Eiffel design for other possible ways to add semantics
    </BATCH_A>

    And that was the first brain-storm. Depending upon interest, I will consider diving into some/all of these and exploring my thoughts and reasoning. If there's no interest (and mine wanes such that I don't bring it up on the Scala mailing lists), it will just dissipate into the Internet ethers. I'm just glad to have had those thoughts pass through my head, get dumped out and can let them go. {smirk}