Most Recent Blog

King's View of the Battle

 Open GL model of a chess board.

March 26, 2011

GoLang - Insertion Sort Implimentaion w/ google go

This article will discuss a simple insertion sort algorithm in golang (google go).
See ALL golang interest postings   |  Insertion Sort By Language Java Scala Go Python Perl

Overview of the Insertion Sort Algorithm
Insertion sort is one of the most natural wayTs of sorting a collection of comparable items.  The reason it is one of the most natural ways is because it is the way most people will sort physical items.   For example each year (about this time) I will sort all 12 of my previous years phone bills, gas bills, etc...  The algorithm used to sort them is to place the first one in stack.  Then the second one is compared to the first one to see if it goes in front of or behind the first one.  The third one is then compared to each if the two sorted items to determine where it fits in.  This procedure continues until all 12 bills are in the pile.  Once all 12 bills are in the pile it is sorted. I happen to sort form oldest to newest, my spouse does it the other way newest to oldest.

Applying this concept to a collection of objects in a computer is fundamentally the same.  The algorithm dictates that one will iterate over a collection of elements in an unsorted list 1 at a time, and place that item into it's correct location in a sorted list.

If the collection of objects to sort is n, insertion sort will take at most $O(n^2)$ operations to perform the sort, it will take on average $\frac{1}{2} O(n^2) = O(n^2)$, and in the best case senario will take $O(n)$ operations.


Questions:  


1.  What would be the initial characteristics of a list that took the worst case order $O(n^2)$ to sort?
2.  What would be the initial characteristics of a list that took the best case order $O(n)$ to sort?


About the GoLang Solution:
Inline comments have been added to the code to discuss some of the syntax and code structure.
If you have a question about the solution (or feel it should be improved) please leave a comment.  All comments are moderated and posted with your name/Identification so please be professional and straight forward.
GoLang Solution:

package main

/*------------------------------------------------------------------------------
  Copyright (c) 2011 ecocrypt.com

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the spe\]cific language governing permissions and
  limitations under the License.
-----------------------------------------------------------------------------*/
import fmt "fmt"  
import "container/list" 
import "rand"

//  The main entry point.
func main() {
    // create a list of integers randomly ordered.
    var  randomOrderedList = createRandomUnsortedList() 

    //  Perform the insertion sort.
    //  return a new sorted list.
    var sortedList = insertionSort(randomOrderedList)


    //  display the list to standard out.
    displayListToStandardOut(sortedList) 

}


//  private function takes unsortedList, returns sortedList
func insertionSort(unsortedList *list.List) (sortedList *list.List){
    sortedList = list.New()
    for e :=unsortedList.Front();e!=nil; e=e.Next() {
        var found = 0
        for s := sortedList.Front();s!=nil;s=s.Next(){
            if(e.Value.(int)>s.Value.(int)){
                found=1
                sortedList.InsertBefore(e.Value,s)
                s=sortedList.Back()
            }
        }
        if(found==0){
            sortedList.PushBack(e.Value)
        }
    }
    return sortedList
}


//  private method displays the lList to standard out.
func displayListToStandardOut(lList *list.List) {
    counter := 0
    for y :=lList.Front();y!=nil; y=y.Next() {
        counter += 1
        fmt.Printf("%d -> %d\n",counter,y.Value)
    }
}

// private method returns lList
func createRandomUnsortedList() (lList *list.List) {
    //  Create a New Random Generator from a Random Source
    //  with a seed of 10.
        var r = rand.New(rand.NewSource(10))

    //  create a list of random integers.
    lList = list.New()
    for i :=0; i<15; i=i + 1 {
        lList.PushFront(r.Int())
    }
    return lList
}
Answers: 1.  The best case senario would be order: $O(n)$ 2.  The worst case senario would be order: $O(n^{2})$golang postings

March 22, 2011

Scala - Insertion Sort Implementation

This article will discuss a simple insertion sort algorithm in Scala.
See ALL Scala postings   |  Insertion Sort By Language Java Scala Go Python Perl

Overview of the Insertion Sort Algorithm
Insertion sort is one of the most natural ways of sorting a collection of comparable items.  The reason it is one of the most natural ways is because it is the way most people will sort physical items.   For example each year (about this time) I will sort all 12 of my previous years phone bills, gas bills, etc...  The algorithm used to sort them is to place the first one in stack.  Then the second one is compared to the first one to see if it goes in front of or behind the first one.  The third one is then compared to each if the two sorted items to determine where it fits in.  This procedure continues until all 12 bills are in the pile.  Once all 12 bills are in the pile it is sorted. I happen to sort form oldest to newest, my spouse does it the other way newest to oldest.

Applying this concept to a collection of objects in a computer is fundamentally the same.  The algorithm dictates that one will iterate over a collection of elements in an unsorted list 1 at a time, and place that item into it's correct location in a sorted list.

If the collection of objects to sort is n, insertion sort will take at most $O(n^2)$ operations to perform the sort, it will take on average $\frac{1}{2} O(n^2) = O(n^2)$, and in the best case senario will take $O(n)$ operations.


Questions:  


1.  What would be the initial characteristics of a list that took the worst case order $O(n^2)$ to sort?
2.  What would be the initial characteristics of a list that took the best case order $O(n)$ to sort?


About the Scala Solution:
Inline comments have been added to the code to discuss some of the syntax and code structure.
If you have a question about the solution (or feel it should be improved) please leave a comment.  All comments are moderated and posted with your name/Identification so please be professional and straight forward.
Scala Solution:

package com.ecocrypt.scala.helloworld.com.ecocrypt.scala.algorithms.sort

import java.util.LinkedList

/*------------------------------------------------------------------------------
  Copyright (c) 2011 ecocrypt.com

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the spe\]cific language governing permissions and
  limitations under the License.
-----------------------------------------------------------------------------*/

object InsertionSort {
    var flag = 0
    var counter = 0


    def sort(unsortedList: List[Int]): LinkedList[Int] = {
        // Start with an empty LinkedList.
        // as items are added to the list, they will be
        // placed in sorted order.
        var sorted = new LinkedList[Int]()

        // Iterate over the unsorted list one Item at a time.
        for (currentItem <- unsortedList) {
            flag = 0
            counter = 0;

            //------------------------------------------------------------------------------------
            //  Scala allows us to define helper functions with scope inside of other functions.
            //        this creates some very interesting closure situation.
            //        More on this in later code samples
            //------------------------------------------------------------------------------------
            def checkRecordToRightAndInsertIfLocationFound(itemRightOfCurrentPostion: Int): Int = {
                if (itemRightOfCurrentPostion > currentItem) {
                    // flag is a var defined in an enclosed scope.
                    flag = 1
                    if (counter < 0) {
                        sorted.addFirst(currentItem)
                    } else {
                        sorted.add(counter, currentItem);
                    }
                }
                //  this is the return val of this method.
                flag
            }


            do {
                if (counter == sorted.size) {
                    sorted.addLast(currentItem)
                    flag = 1
                } else {
                    var itemRightOfCurrentPostion = sorted.get(counter)
                    flag = checkRecordToRightAndInsertIfLocationFound(itemRightOfCurrentPostion)
                }
                counter = counter + 1
            } while (flag == 0)
        }
        return sorted
    }
}

//  Here we use an application to serve as the entry point.
object EntryPointForInsertionSortExample extends Application {
    val randomOrderedList = List.fill(10)(scala.util.Random.nextInt(1000))
    println("unsorted List : " + randomOrderedList)
    val sortedList = InsertionSort.sort(randomOrderedList)
    println("sorted List : " + sortedList)
}


Answers:
1.  The best case senario would be order: $O(n)$
2.  The worst case senario would be order: $O(n^{2})$

March 16, 2011

Java - Insertion Sort Implementation and discussion.

This article will discuss a simple insertion sort algorithm in Java.
See ALL Java Postings   |  Insertion Sort By Language Java Scala Go Python Perl


Discussion of Insertion Sort
Insertion sort is one of the most natural ways of sorting a collection of comparable items.  The reason it is one of the most natural ways is because it is the way most people will sort physical items.   For example each year (about this time) I will sort all 12 of my previous years phone bills, gas bills, etc...  The algorithm used to sort them is to place the first one in stack.  Then the second one is compared to the first one to see if it goes in front of or behind the first one.  The third one is then compared to each if the two sorted items to determine where it fits in.  This procedure continues until all 12 bills are in the pile.  Once all 12 bills are in the pile it is sorted. I happen to sort form oldest to newest, my spouse does it the other way newest to oldest.

Applying this concept to a collection of objects in a computer is fundamentally the same.  The algorithm dictates that one will iterate over a collection of elements in an unsorted list 1 at a time, and place that item into it's correct location in a sorted list.

If the collection of objects to sort is n, insertion sort will take at most $O(n^2)$ operations to perform the sort, it will take on average $\frac{1}{2} O(n^2) = O(n^2)$, and in the best case senario will take $O(n)$ operations.


Questions:  


1.  What would be the initial characteristics of a list that took the worst case order $O(n^2)$ to sort?
2.  What would be the initial characteristics of a list that took the best case order $O(n)$ to sort?




Java Solution:

/*------------------------------------------------------------------------------
   Copyright (c) 2011 ecocrypt.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 -----------------------------------------------------------------------------*/
package insertionsort;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class InsertionSortAlgorithm<type extends Comparable> {
    Collection<type> unsortedCollection;

    public InsertionSortAlgorithm(){
        unsortedCollection = new ArrayList<type>();
    }

    public InsertionSortAlgorithm(Collection<type> sourceCollection){
        unsortedCollection = new ArrayList<type>(sourceCollection);
    }
    public void add(Type element){
        unsortedCollection.add(element);
    }
    public Collection<type> getUnsortedCollection(){
        return unsortedCollection;
    }

    public List<type> sortWithInsertionSort(){
        LinkedList<type> sortedList = new LinkedList<type>();
        for (Type nextObject : unsortedCollection) {
            sortedList = placeInSortedList(sortedList,nextObject);
        }
        return sortedList;
    }

    private LinkedList<type> placeInSortedList(LinkedList<type> sortedList, Type nextObject){
        int insertionIndex = 0;
        for (Type object : sortedList) {
            if(nextObject.compareTo(object)>0){
                break;
            }
            ++insertionIndex;
        }
        sortedList.add(insertionIndex, nextObject);
        return sortedList;
    }
}

Answers:
1.  The best case senario would be order: $O(n)$
2.  The worst case senario would be order: $O(n^{2})$

March 13, 2011

Scala - Hello World

Scala's Hello World can be either similar to Java's, or simpler depending on how the problem is approached.  This article will approach the problem from both the Java style as well as the much more pure functional style.  Remember that Scala is a highly expressive functional language.  The second form of the hello world program will show this feature much more clearly.

Step 1: Create a Scala source file
Scala does not have the same restrictions on source file naming that Java has.  Therefore, you can give the Scala source file pretty much any name you like, so long as it ends in .scala.  The fist form of Hello World looks as:
__________________________________________________________________________________

object HelloWorld {
    def main(args: Array[String]) {
      println("Hello in scala from ecocrypt.blogspot.com")
    }
  }
__________________________________________________________________________________
Step 2: Compile the Scala Source
At a command prompt, type the scala compiler command:

prompt %
prompt % scalac HelloWorld.scala
prompt %
prompt % scalac HelloWorld.scala

The result of this will be to produce an output file called HelloWorld.class, this class file is a byte code version of the HelloWorld.scala source file.  This class file is identical to a Java class file, but has Scala class references embedded in it.  

Step 3: Running HelloWorld
At the command prompt, type:
prompt %
prompt % scala HelloWorld
Hello in scala from ecocrypt.blogspot.com
prompt %
prompt % scala HelloWorld
Hello in scala from ecocrypt.blogspot.com

Congratulate yourself!  You have successfully installed the Scala compiler and execution environment, created a simple scala source file compiled it to byte code, and run it inside of the Scala/Java Virtual Machine.

The exact same thing could be accomplished using a scala Application.  The source code for a Scala application based solution would look as:
__________________________________________________________________________________
object HelloWorld2 extends Application {
  println("Hello world in scala from ecocrypt.blogspot.com")
}
__________________________________________________________________________________



C++ - Hello World

C++'s Hello World is similar to Go's (golang), but there are some differences.  The similarity is that both C++ and Go create a file that is executed natively on the platform it is compiled to.  Also both C++ and Go follow a procedure of compile then link.  The main differences, for the Hello World program, are in the expressiveness and the syntax.  Writing hello world in C++ requires the following steps:

Step 1: Create a C++ source file
The source file for Hello World thus looks like the following:
__________________________________________________________________________________


#include <iostream>
using namespace std;

int main(int argc, const char** argv){
cout<<"Hello World in C++ from ecocrypt.blogspot.com"<<endl;
return 0;
}
__________________________________________________________________________________

Save this to any file name you like, but typically, you will have to have a .cpp extension on the end of the file name.  A good name to choose for this example would be helloworld.cpp.

Step 2: Compile the C++ Source
At a command prompt, type the c++ compiler-linker command:
prompt % c++ HelloWorld.cpp

This will typically do a 2 step process of compiling and linking.  Therefore no intermediate object files will be created.  The result of this will be to produce an output file called a.out, or a.exe. 

Step 3: Running HelloWorld
At the command prompt, type:
prompt % a.out      (or a.exe on windows)
Hello World in C++ from ecocrypt.blogspot.com

Congratulate yourself!  You have successfully installed a C++ compiler, and created a simple hello world executable.

Perl - Hello World

Writing hello world in perl is almost to simple to justify a post, however there are some caveats and for completeness of this group of posts, it will be included.
Step 1 Install Perl (5.x)
Once installed, make sure that you can access the perl executable.  If perl is not in the path, you will need to add it.

Step 2 Create a Perl Source file
______________________Source File____________________________
#!/opt/perl
print ("Hello World in Perl from ecocrypt.blogspot.com")
______________________End Source____________________________
save the source to a file called helloworld.pl  (or any other name of your choice)

Step 3 Tell Perl to execute the input file
prompt % perl helloworld.pl
Hello World in Perl from ecocrypt.blogspot.com

Congratulate yourself! You have successfully installed perl, create a perl source file, and executed it.

Java - Hello World

Java's Hello World is simpler than Go's (golang), but not as simple as Python's.  Also like python the output is quite portable from platform to platform.  Writing hello world in Java requires the following steps:

Step 1: Create a Java source file
There are actually quite a few caveats to this step alone because Java as some requirements that make it more restrictive  than any other language in this blog.  In Java, there everything is an "Object" and thus extends from java.lang.Object.  Therefore, you will have to create a full class definition even though we will not be instantiating any classes.  The source file for Hello World thus looks like the following:
__________________________________________________________________________________

public class HelloWorld extends java.lang.Object {
    public static void main(String args[]){
        System.out.println("Hello World in Java from ecocrypt.blogspot.com");
    }
}
__________________________________________________________________________________

There is another caveat in Java the class HelloWord must be stored in a file called HelloWorld.java. Picking another name will cause a compiler error.

Step 2: Compile the Java Source
At a command prompt, type the java compiler command:
prompt % javac HelloWorld.java

The result of this will be to produce an output file called HelloWorld.class, this class file is a byte code version of the HelloWorld.java source file.  Unlike golang, where the output of the linker can be directly executed, the java class file is not executable.  However, a java executable program and load the HelloWorld.class file, and execute the instructions.

Step 3: Running HelloWorld
At the command prompt, type:
prompt % java HelloWorld
Hello World in Java from ecocrypt.blogspot.com

Congratulate yourself!  You have successfully installed the JDK, created a simple java source file compiled it to byte code, and run it inside of the Java Virtual Machine.

March 11, 2011

Go Lang - Hello World

Starting a new language the first example is always Hello World.  Getting going with go-lang is only slightly different.  As of this writing, the current state of 'go-lang' is that you have to build the compiler first, and then write compile and run Hello World.  On UNIX/Linux you can do that pretty easily based on the instructions maintained on the golang.org website.  On windows the GOMINGW  seems to be maintaining good binary compatible version of go built with the mingw compiler collection on windows.

Step 1 Set your environment variables:

E.G. On my windows box I set:
set GOROOT=C:\golang\go
set GOOS=windows
set GOARCH=386
  (look in $GOROOT/pkg for applicable architecture and OS Options)


Step 2 Create a source file in the go language (a go source file):
Use a text editor or write a golang source file:
Sample Hello World GO Language source file:
________________________SOURCE FILE________________________________________


package main

import fmt "fmt"  // Package implementing formatted I/O.


func main() {

      fmt.Printf("Hello, world; from go to ecocrypt.blogspot.com \n")
}

________________________END SOURCE_________________________________________


Save this file to helloworld.go or any filename of your choice.

Step 3  Compile
prompt % 8g helloworld.go

Step 4 Link
prompt % 8l helloworld.go

Step 5 Run the newly created executable:
prompt % 8.out
Hello, world; from go to ecocrypt.blogspot.com

Congratulate Yourself!  You have created and run Hello World in Go.
You should now have a Go compiler successfully installed on your computer.


SOME COMMON ERRORS:
Using the wrong executable to compile go source:
prompt %  8c.exe helloworld.go

helloworld.go:1 not a function
helloworld.go:1 syntax error, last name: main

     This Error is caused because you are trying to compile a go source file with a c compiler.  8c is a c compiler embedded in the go distribution package.


Using the wrong architecture or os settings:
prompt % 8g.exe helloworld.go

helloworld.go:3: can't find import: fmt

Make sure you have set the go environment variables correctly:
Determining the GOOS, and GOARCH can be tricky, you will have to look in:
$GOROOT/pkg/
and there will be a directory of format $GOOS_$ARCH

E.G. On my windows box I set:

set GOROOT=C:\golang\go
set GOOS=windows
set GOARCH=386


March 9, 2011

Python - Hello World

Writing hello world in python is almost to simple to justify a post, however there are some caveats and for completeness of this group of posts, it will be included.

Step 1 Install Python 3.2 
Once installed, make sure that you can access the python executable.  If python is not in the path, you will need to add it.


Step 2 Create a Python Source file
______________________Source File____________________________
#!/opt/python
print ("Hello World in Python from ecocrypt.blogspot.com")
______________________End Source____________________________
save the source to a file called helloworld.py  (or any other name of your choice)


Step 3 Tell the Python Interrupter to execute the instructions in the file
prompt % python helloworld.py
Hello World in Python from ecocrypt.blogspot.com


This entire exercise could have been done from within the python interrupter.  To start the interpretor simply type 'python' at the command prompt this will give you a python interpretor prompt:


>>>
>>>print ("hello world in python from ecocyrpt.blogspot.com")
hello world in python from ecocyrpt.blogspot.com
>>>
type quit() to leave the interpretor


SOME COMMON ERRORS:
Using the wrong Python Syntax for version 3.2.

>>> print "Hello World"
  File "<stdin>", line 1
    print "Hello World"
                      ^
SyntaxError: invalid syntax
>>>

There were some syntax changes between python 2.7 and 3.2.
This fails because the print method is not enclosed in braces().
Try >>> print ("Hello World")