Friday, December 27, 2013

Day 2 -- Simple Sorts in CoffeeScript

This is the second workout. If, like me, you are new to Node.Js and CoffeeScript, yesterday and today may be a bit of a challenge. In my warmup for today, I started to modularize my simple unit tests. This required me to learn about the Node.Js "require" function. This page - http://openmymind.net/2012/2/3/Node-Require-and-Exports/ - helped me understand how to do this.

My code from yesterday: https://github.com/HackerWorkout/HackerWOD/tree/master/WOD/Day1

Today's workout

Recommended Setup

Language: CoffeeScript 
Tools: Node.js (to make CoffeeScript work in a console window)

Warmup 

A) Improve your simple unit test so that it works as a module.


UnitTest = require "./UnitTest.Core.Js"

B) Add a timer to your unit test so you can measure how long it takes to run.

C) Write a function to reverse a string using an array


ReverseEasy = (str) -> str.split("").reverse().join ""
 
UnitTest.Test "Reverse test", () -> 
    tst = "This is a forward string."
    UnitTest.Assert.Equal(ReverseEasy(tst), Reverse(tst))

Exercise

Write a function BubbleSort (http://en.wikipedia.org/wiki/Bubble_sortand SelectionSort (http://en.wikipedia.org/wiki/Selection_sort) and see which is faster for 10,000 random numbers.

Starter code


Rnd10k = () ->
    (Math.random() for num in [1..10000])
 
CheckSorted = (arr) ->
    n = 0
    end = arr.length - 1
    while (end > n + 1)
        if (arr[n] > arr[n+1]) then throw "Array is not sorted."
        n++
 
UnitTest.Test "Unsorted is unsorted", () -> UnitTest.Assert.Exception () -> CheckSorted(Rnd10k())
 
UnitTest.Test "Bubble Sort test", () -> 
    CheckSorted BubbleSort Rnd10k()
 
UnitTest.Test "Selection Sort test", () -> 
    CheckSorted SelectionSort Rnd10k()

Happy Hacking

No comments:

Post a Comment