Saturday, October 15, 2011

Project Euler and Scala problem 1

I recently found a Web site called, Project Euler (PE).  Its a site full of problems that are intended to be solved by coding.  As I am also experimenting with Scala, I figured this would be a fun way to keep my skills sharp solving problems while learning the nuances of another language.


What I am finding is very interesting.  First, my 'functional' skills need work.  I'm attempting to solve each problem with no mutable state, but as you will see, my first iteration usually has some sort of mutable state and it takes me a little bit to refactor it.  Part of this is due to the fact that I spend my day job programming in an OO language, part of it is due to learning Scala, but part of it is just that I need more practice in the functional way of thinking.


I am fortunate in that I have two friends who are also interested in PE and who have started working through the problems as well, so we swap notes after we solve the solutions, which further helps understanding.  


I thought I would blog about the problems as I work through them.  The format I have settled on this this:

  1. I will present my first, rough, solution to the problem, along with a brief summary of the PEdocumentation.
  2. I will present a refactored version of the same problem that makes the code much more functional and maintainable.
  3. If the PE documentation reveals a math or programming concept that would improve the code, another version of the algorithm may be posted.
It's my hope that presenting my progress in this fashion is both interesting and revealing for other programmers. I work primarily in Java, so this might also be a good way for Java programmers to see how things translate to Scala.  Of course I am not a Scala expert, so I'm sure there will be lots of comments with room for improvement.  At least, that's my hope.


Here is PE's first problem:

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.
Well, this seems simple enough.  Simply iterate all the numbers to 1000, testing if they are divisible by 3 or 5 along the way.  The first version of my code looks like this:

object Problem1 {


  def main(args: Array[String]): Unit = {  
    var sum = 0;
    for( i <- Iterator.range(0,1000) if i % 3 == 0 || i % 5 == 0) {
      sum += i;
    }
    print(sum);
  }
}


There's nothing inherently wrong with the code above.  Except I have that mutable variable, sum,  in there.  So, what's a more functional way to think about this?  Thanks to the inspiration from my co-worker, Sean, we have a more functional version of the code above:


object Problem1 {
  def main(args: Array[String]): Unit = {
    val count = (1 to 999);
    val sum = (0 /: count)((total, next) =>
      {
        if (next % 3 == 0 || next % 5 == 0) {
          total + next;
        } else {
          total;
        }
      });
    println(sum);
  }
}


In this version, we've made the sum immutable (by using val instead of var), so it can only be assigned once.  We've also used the left-fold operator, \:, to iterate the range.  Finally, we've converted the contents of the for loop to a function block that gets executed on each 'fold'.  This version looks pretty good, but after reviewing the PE docs, we pick up another little math trick.  


Instead of iterating the numbers, we can take the sum of all the multiples of 3, sum of all the multiples of 5 and then subtract all the multiples of 15.  There's also a proof that demonstrates how to find the sum (I won't reprint it here, if you are interested, unlock the problem on the PE site).


The final version of our code looks like:


object Problem1 {
  def main(args: Array[String]): Unit = {
println(sumDivisibleBy(999,3) + sumDivisibleBy(999, 5) - sumDivisibleBy(999, 15));
  }
  
  def sumDivisibleBy(limit:Int, divisor:Int) : Int =  {
val p = limit/divisor;  
divisor * (p*(p+1))/2; 
  }
}


So in the end, we don't iterate the range at all.  This solution would also scale well (what if we wanted to add all the multiples of 3 and five for all numbers under 1 million...)


So there it is. A brief walk through my process on Project Euler problem 1. Let me know what you think.

Sunday, July 17, 2011

GWT JSNI Reference

I've recently had to go through the GWT JSNI interface, and I found the documentation a little lacking.  While the official JSNI page has nice examples and clearly shows how things integrate, it leaves out some reference information that would be helpful.  My guess is that they didn't want to duplicate the JNI reference, but its still a little frustrating to have to look up the type codes in a separate area.  And the type codes aren't exactly intuitive, I mean, who would guess that 'Z' is the representation for boolean?

So, here is a little cheat sheet for those of you looking for the GWT JSNI type codes.  These are, of course, the same codes that can be found in the JNI reference.

Native Type Java Language Type Description Type signature
unsigned char jboolean unsigned 8 bits Z
signed char jbyte signed 8 bits B
unsigned short jchar unsigned 16 bits C
short jshort signed 16 bits S
long jint signed 32 bits I

long long

__int64
jlong signed 64 bits J
float jfloat 32 bits F
double jdouble 64 bits D

Table taken from Wikipedia, 5/7/2011


In addition to the primitive types, any object can be referenced using its fully qualified name like this:

LFully.Qualified.Name;

For example, to access a string, you use:  Ljava.lang.String;

To reference an array of the same type, prepend [ like this:

[Ljava.langString;

So that's my quick cheat sheet.  Here are a couple of additional references that help:

Coding Basics - Javascript Native Interface (JSNI) 

JDK 6 Java Native Interface-related APIs & Developer Guides

Thursday, April 28, 2011

Master of Software Engineering

Finally, I am an MSE. That's, Master of Software Engineering. I just finished presenting my capstone project at Carroll University.

A lot of people don't know what Software Engineering is. Is it related to Development? Is it really an Engineering discipline? I'd like to take this time to talk a little bit about what I think a Software Engineer is.

Let's start with the official definition of 'Software Engineer'. Any search these days starts with Wikipedia, and in fact, Wikipedia has a nice listing for 'Software Engineering', with lots of references. Here is the first paragraph:

Software engineering (SE) is a profession dedicated to designing, implementing, and modifying software so that it is of higher quality, more affordable, maintainable, and faster to build. It is a "systematic approach to the analysis, design, assessment, implementation, test, maintenance and re-engineering of a software by applying engineering to the software".[1] The term software engineering first appeared in the 1968 NATO Software Engineering Conference, and was meant to provoke thought regarding the perceived "software crisis" at the time.[2][3] Since the field is still relatively young compared to its sister fields of engineering, there is still much debate around what software engineering actually is, and if it conforms to the classical definition of engineering.[4] The IEEE Computer Society's Software Engineering Body of Knowledge defines "software engineering" as the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software.[5] It is the application of Engineering to software because it integrates significant mathematics, computer science and practices whose origins are in Engineering.[6]
Wikipedia, Dec 24, 2010

If I were to put that rather lengthy description into my own short words, it would be: Software Engineering is a way to build better software by studying and applying a systematic, disciplined and quantifiable approach to the development process.

You see, to me, the key characteristic is that while Software Engineering includes software development, it really goes beyond just writing code or applications.  It is the study and practice of the processes that will make writing applications better.  Better may not mean faster or cheaper but will always mean higher quality. Although, sometimes, it will mean faster and cheaper, but usually in the long run.  So Software Engineering really expands into all the different tasks surrounding a system - business definition, requirements gathering, analysis, design, testing, and support.  A Software engineer should know about all these phases in the life cycle and should be involved with all of them.

But developing software is not exactly akin to designing a bridge or a car.  There's still a component of craftsmanship or artistry involved with software development. Methodologies can be used to improve estimates, quality, and outcomes, but there is also a large component that is more akin to writing a novel or creating a movie than to building a bridge or designing a car.

It is in that part of the software development process where the art of development presents itself.  Writing software is a creative and abstract task with many different ways to solve a problem.  In some cases, a single, best, solution can be found, but in so many others, there isn't one.  In that regard, some developers are artists, some developers really aren’t, and never will be. The rest of us are aspiring to be one of the great ones. We are competent technicians, writing our works, but not gifted with the ability to produce masterpieces.  Here is where what we learn and the techniques we apply from Software Engineering Study allow us to produce pieces of software that are in fact, solid and elegant.  We won't be writing the next Mona Lisa, but by following proper techniques, using the best practices, studying what works, and applying them consistently and rigorously, we can produce consistent, appealing work with high levels of quality.  If we work hard, people might one day also recognize us as an artist.

Perhaps not a Michelangelo, but maybe a Bob Ross.