Tuesday, May 24, 2011

Wrapping up the Sort Project

I think I'm about done with the Sort Project. I got a chance to play with script blocks – the original point of the exercise – as well as set up a test harness that can handle any number of sort techniques and compare them against each other.

I've done some clean-up work on the script:

# cd C:\Users\tdsherer\documents\programming\powershellprog\functional


# Test cases and tests for sorts


# Run necessary scripts:

. .\sortNOTEST.ps1 # loads $isSorted


. .\bubble01.ps1 # loads $bubble01

. .\bubble02.ps1 # loads $bubble02


# Test Cases:


$testCase = 1..5

$testCase[0] = 1,2,3,4,5

$testCase[1] = 1,1,1,1,1

$testCase[2] = 1,2,3,4,3

$testCase[3] = 3,2,3,4,5

$testCase[4] = 3,2,3,4,3

# functions

function runTest ($listToSort, $algorithmToUse, $label)

{

$temp = &{$listToSort}

if (!(&$isSorted (&$algorithmToUse $temp))) {"FAIL: List is sorted: $listToSort"}

$label + ": Number of swaps per compares for $a is " + $global:countSwaps / $global:countCompares

}

# tests


foreach ($a in $testCase)

{

runTest $a $bubble01 '$bubble01'

runTest $a $bubble02 '$bubble02'

' '

}

The runTest function takes a list of different sort techniques – formatted as script blocks assigned to a variable. Both the number of sorts and the test cases used with them can be increased without changing the basic script.

Tomorrow, I'll start laying out what I expect my next project will be: GUI elements in PowerShell.

Monday, May 23, 2011

Finishing the Sort Tests

I remembered how to do a deep copy of an array in PowerShell:


PowerShell: $a = 4,5,6

PowerShell: $a

4

5

6

PowerShell: $a[0]

4

PowerShell: $b = $a

PowerShell: $a[0] = 5

PowerShell: $b

5 == shallow copy

5

6

PowerShell: $b = &{$a}

PowerShell: $b

5

5

6

PowerShell: $a[0] = 9

PowerShell: $b[0]

5 == deep copy

PowerShell:


So, back to my tests:


$testCase = 1..5

$testCase[0] = 1,2,3,4,5

$testCase[1] = 1,1,1,1,1

$testCase[2] = 1,2,3,4,3

$testCase[3] = 3,2,3,4,5

$testCase[4] = 3,2,3,4,3


foreach ($a in $testCase)

{

"Bubble sort 01:"

" "

$temp = &{$a}

if (!(&$isSorted (&$bubble01 $temp))) {"FAIL: List is sorted: $a"}

# "Number of compares for $a is $global:countCompares."

# "Number of swaps for $a is $global:countSwaps."

"Number of swaps per compares for $a is " + $global:countSwaps / $global:countCompares


" "

"Bubble sort 02:"

" "

$temp = &{$a}

if (!(&$isSorted (&$bubble02 $temp))) {"FAIL: List is sorted: $a"}

# "Number of compares for $a is $global:countCompares."

# "Number of swaps for $a is $global:countSwaps."

"Number of swaps per compares for $a is " + $global:countSwaps / $global:countCompares


}


As you can see, I settled on swaps per compares. I'm assuming that the number of swaps necessary to sort a list is the same, no matter how you do it. I don't know if that's true, but I'm assuming. If that's true, then the larger the number (that is, the fewer number of compares), the more efficient the search is.

Bubble sort 01:

Number of swaps per compares for 1 2 3 4 5 is 0

Bubble sort 02:

Number of swaps per compares for 1 2 3 4 5 is 0

Bubble sort 01:

Number of swaps per compares for 1 1 1 1 1 is 0

Bubble sort 02:

Number of swaps per compares for 1 1 1 1 1 is 0

Bubble sort 01:

Number of swaps per compares for 1 2 3 4 3 is 0.05

Bubble sort 02:

Number of swaps per compares for 1 2 3 4 3 is 0.1

Bubble sort 01:

Number of swaps per compares for 3 2 3 4 5 is 0.05

Bubble sort 02:

Number of swaps per compares for 3 2 3 4 5 is 0.1

Bubble sort 01:

Number of swaps per compares for 3 2 3 4 3 is 0.1

Bubble sort 02:

Number of swaps per compares for 3 2 3 4 3 is 0.2


Saturday, May 21, 2011

Evaluating Test Cases for the Sort Function 2

I had to spend twenty minutes stumbling around because I forgot how dot sourcing works. Sigh.

Well, I don't try to keep everything about PowerShell in my head. I look things up and do searches and stuff.

Let's see what I did.

My basic bubble search was very brute force. Since a bubble sort starts by moving the greatest value to the very last position, you don't need to keep checking that position. Bubble sorts usually skip these compares, doing something like the following:

$bubble02 = {

[LT]#

.SYNOPSIS

Does a bubble sort on a provided array.


.DESCRIPTION

Basic bubble sort, runs through the array, skipping the number that was just moved into last position

in previous sweep.

.PARAMETER $sourceArray

The array to be sorted.

#[GT]

param ($sourceArray) # Takes any array - not tested for mixed arrays (strings and ints, for instance

$global:countCompares = 0 # values for testing compares and swaps.

$global:countSwaps = 0

for ($j = 0; $j -lt $sourceArray.length; $j++)

{

for ($i = 0; $i -lt ($sourceArray.length - 1 - $j); $i++) # checks each position against the position to its right

{

$global:countCompares++ # increment compares variable each time two values are compared

if ($sourceArray[$i] -gt $sourceArray[$i+1]) # uses Greater Than.

{

$global:countSwaps++ # increment swaps variable each time two values are swapped.

$temp = $sourceArray[$i] #swap if necessary.

$sourceArray[$i] = $sourceArray[$i+1]

$sourceArray[$i+1] = $temp

}

}

}

return $sourceArray # return array

}

Here's my revised testing:


function setTestCases {

$global:testCase = 1..5

$global:testCase[0] = 1,2,3,4,5

$global:testCase[1] = 1,1,1,1,1

$global:testCase[2] = 1,2,3,4,3

$global:testCase[3] = 3,2,3,4,5

$global:testCase[4] = 3,2,3,4,3

}

setTestCases

"BubbleSort01:"


foreach ($a in $global:testCase)

{

if (!(&$isSorted (&$bubble01 $a))) {"FAIL: List is sorted: $a"}

"Number of compares for $a is $global:countCompares."

"Number of swaps for $a is $global:countSwaps."

}


setTestCases

"BubbleSort02:"

foreach ($a in $global:testCase)

{

if (!(&$isSorted (&$bubble02 $a))) {"FAIL: List is sorted: $a"}

"Number of compares for $a is $global:countCompares."

"Number of swaps for $a is $global:countSwaps."

}


And here's the result:


PowerShell: .\tests

BubbleSort01:

Number of compares for 1 2 3 4 5 is 20.

Number of swaps for 1 2 3 4 5 is 0.

Number of compares for 1 1 1 1 1 is 20.

Number of swaps for 1 1 1 1 1 is 0.

Number of compares for 1 2 3 3 4 is 20.

Number of swaps for 1 2 3 3 4 is 1.

Number of compares for 2 3 3 4 5 is 20.

Number of swaps for 2 3 3 4 5 is 1.

Number of compares for 2 3 3 3 4 is 20.

Number of swaps for 2 3 3 3 4 is 2.

BubbleSort02:

Number of compares for 1 2 3 4 5 is 10.

Number of swaps for 1 2 3 4 5 is 0.

Number of compares for 1 1 1 1 1 is 10.

Number of swaps for 1 1 1 1 1 is 0.

Number of compares for 1 2 3 3 4 is 10.

Number of swaps for 1 2 3 3 4 is 1.

Number of compares for 2 3 3 4 5 is 10.

Number of swaps for 2 3 3 4 5 is 1.

Number of compares for 2 3 3 3 4 is 10.

Number of swaps for 2 3 3 3 4 is 2.


I added a function to reset the test values, but I don't like that. The test does not display the results for the different functions side-by-side.

I tried to re-write it – but I don't know how to get a deep copy of an array.

I'll work on this more next time.

Thursday, May 19, 2011

Evaluating Test Cases for the Sort Function

Evaluating whether a sort function is doing a good job is difficult. First of all, I can't tell what the compiler is going to do with my code. The same or similar high-level code in different languages could be very different in implementation.

Second, different parts of the code take up different amounts of resources. Reading and comparing values takes a certain amount of cycles, swapping takes a certain amount, and so forth.

Still, we should be able to figure out something to say about how much wheel spinning is necessary for each kind of sort.

I'm going to insert 2 count variables:

  • $countCompares01
  • $countSwaps01

These will have to be global variables. This is not part of the functional programming exercise. Since I want to look at how things are working, I don't care if I do it by looking at side-effects.

Here's the body of the bubble sort script block:

param ($sourceArray) # Takes any array - not tested for mixed arrays (strings and ints, for instance

$global:countCompares = 0 # values for testing compares and swaps.

$global:countSwaps = 0

for ($j = 0; $j -lt $sourceArray.length; $j++)

{

for ($i = 0; $i -lt ($sourceArray.length - 1); $i++) # checks each position against the position to its right

{

$global:countCompares++ # increment compares variable each time two values are compared

if ($sourceArray[$i] -gt $sourceArray[$i+1]) # uses Greater Than.

{

$global:countSwaps++ # increment swaps variable each time two values are swapped.

$temp = $sourceArray[$i] #swap if necessary.

$sourceArray[$i] = $sourceArray[$i+1]

$sourceArray[$i+1] = $temp

}

}

}

return $sourceArray # if none fail, then true

Here's the revised tests:

# Test Cases:


$testCase = 1..5

$testCase[0] = 1,2,3,4,5

$testCase[1] = 1,1,1,1,1

$testCase[2] = 1,2,3,4,3

$testCase[3] = 3,2,3,4,5

$testCase[4] = 3,2,3,4,3


foreach ($a in $testCase)

{

if (!(&$isSorted (&$bubble01 $a))) {"FAIL: List is sorted: $a"}

"Number of compares for $a is $global:countCompares."

"Number of swaps for $a is $global:countSwaps."

}

And here's the results:

PowerShell: .\tests

Number of compares for 1 2 3 4 5 is 20.

Number of swaps for 1 2 3 4 5 is 0.

Number of compares for 1 1 1 1 1 is 20.

Number of swaps for 1 1 1 1 1 is 0.

Number of compares for 1 2 3 3 4 is 20.

Number of swaps for 1 2 3 3 4 is 1.

Number of compares for 2 3 3 4 5 is 20.

Number of swaps for 2 3 3 4 5 is 1.

Number of compares for 2 3 3 3 4 is 20.

Number of swaps for 2 3 3 3 4 is 2.


Next, we can start adding more sort functions.

Wednesday, May 18, 2011

Test Cases for the Sort Function

So, I need two more things to finish up from last time:

  • Test cases
  • A way to evaluate test cases.

Let's start with the test cases I did for the isSorted script block:


# Test Cases:


$sorted = 1,2

$sorted[0] = 1,2,3,4,5 #Expected True

$sorted[1] = 1,1,1,1,1 #Expected True


$unsorted = 1,2,3

$unsorted[0] = 1,2,3,4,3 #Expected False

$unsorted[1] = 3,2,3,4,5 #Expected False

$unsorted[2] = 3,2,3,4,3 #Expected False


Sorted and not sorted doesn't matter. The sort function will return a sorted (I assume, if it's working) array. There may be a difference in how easy it is for the sort to happen (rabbits versus turtles), but let's worry about that later.

# Test Cases:


$testCase = 1..5

$testCase[0] = 1,2,3,4,5

$testCase[1] = 1,1,1,1,1

$testCase[2] = 1,2,3,4,3

$testCase[3] = 3,2,3,4,5

$testCase[4] = 3,2,3,4,3


Each of these arrays can be sorted by the script block. To make sure that the thing is working, I could sort each list and compare it to the sorted version of that list.

Or, considering that I've already written a script block that tests whether an array is in the right order, I could use that, as follows:


foreach ($a in $testCase)

{

if (!(&$isSorted (&$bubble01 $a))) {"FAIL: List is sorted: $a"}

}


(I had to play around a little to get the nested invoking right. I tested it by leaving out the ! Symbol to see that it would produce a $true in every case.)

(Using the previously written script block might be suspect from the point of view of testing. After all, it was the basis of the bubble sort code. Still, it was tested and seems to work.)

So, now I have a way of reading test cases in and evaluating that the sort mechanism is working. What this doesn't tell us is how easy the sort is for each test case and how we could compare it to other sort functions.


Tuesday, May 17, 2011

A Bubble Sort Script Block

A couple of years back, I played with sort functions a bit – just the basics. What I wanted to do (and did, in part) was

  • Write a basic bubble sort.
  • Write variations on that sort that were – maybe – less “brute force”.
  • Evaluate whether different kinds of sort functions were better or worse compared to each other.

I could accomplish the first two goals, but I didn't have enough testing under my fingernails to accomplish the third.

But maybe I do now.

I'm going to start by working on my sort functions – building on what I did with the isSorted script block. Here's my basic bubble sort:

$bubble01 = {

(LT)#

.SYNOPSIS

Does a bubble sort on a provided array.


.DESCRIPTION

Basic bubble sort, runs through the array (length) number of times.

.PARAMETER $sourceArray

The array to be sorted.

#(GT)

param ($sourceArray) # Takes any array - not tested for mixed arrays (strings and ints, for instance


for ($j = 0; $j -lt $sourceArray.length; $j++)

{

for ($i = 0; $i -lt ($sourceArray.length - 1); $i++) # checks each position against the position to its right

{

if ($sourceArray[$i] -gt $sourceArray[$i+1]) # uses Greater Than.

{

$temp = $sourceArray[$i] #swap if necessary.

$sourceArray[$i] = $sourceArray[$i+1]

$sourceArray[$i+1] = $temp

}

}

}

return $sourceArray # if none fail, then true

}

To finish this stage of the project, I need two things:


  • Test cases.
  • A way to evaluate test cases.

Monday, May 16, 2011

Finishing the isSorted Script Block

OK, short version: something about invoke-command is passing only the first element of the array into the script block. Not sure why, but the & operator does work. Here's my script block:


$isSorted = {

param ([Int32[]]$a)

#$a

for ($i = 0; $i -lt ($a.length - 2); $i++)

{

if ($a[$i] -gt $a[$i+1])

{

return (1 -eq 0)

}

}

return (1 -eq 1)

}


Since I can't develop without tests, here's my test cases:


$sorted01 = 1,2,3,4,5 #Expected True

$sorted01 = 1,1,1,1,1 #Expected True


$unsorted01 = 1,2,3,4,3 #Expected False

$unsorted02 = 3,2,3,4,5 #Expected False

$unsorted03 = 3,2,3,4,3 #Expected False


I can put these together in an array and use a foreach loop to run all the tests:

$trueTestCases = $sorted01,$sorted02

$falseTestCases = $unsorted01,$unsorted02,$unsorted03



foreach ($a in $trueTestCases)

{

if (!(&$isSorted $a)) {"FAIL: List is sorted: $a"}

}



foreach ($a in $falseTestCases)

{

if (&$isSorted $a) {"FAIL: List is not sorted: $a"}

}

Result:

FAIL: List is not sorted: 1 2 3 4 3

Um, that's bad. The only one that fails is the case where the last two digits are unordered. My for-loop isn't working right.

I don't know where I got the idea that it needed to be ($a.length – 2), but ($a.length – 1) is what it should be.

This script block takes arbitrarily large arrays, but what about empty arrays or single elements?

PowerShell: &$isSorted $aa

True


PowerShell: &$isSorted 1,2

True


PowerShell: &$isSorted 2,1

False

That works – and I don't know why.

If the length of the array is 0 or 1, the for-loop is skipped and the value defaults to true.

An array with length 2 goes through the array once, checking just once.

This is awfully clever. At this point, I'd like to pretend I designed it that way intentionally.


Some cleaning up:

I wrote help for this. As before, it doesn't display as written in a script block. I'm not sure whether I'm doing it wrong or whether it isn't supposed to work. I can, though, turn it into a function and get a display of it that way:

PowerShell: get-help x


NAME

x

SYNOPSIS

Checks wether an array is sorted, such that the second of two elements is greater than

or equal to the first.

SYNTAX

x [[-candidate] (LT)Object(GT)] [(LT)commonparameters(gt)]< p="">

DESCRIPTION

Takes an array of any length and checks for being sorted. An array with 0 or 1 members is

sorted by definition.

The function tests each pair in sequence from left to right (0 to highest index) and returns

$false at the first fail. In principle, it will take longer to check a long, sorted array.


RELATED LINKS


REMARKS

To see the examples, type: "get-help x -examples".

For more information, type: "get-help x -detailed".

For technical information, type: "get-help x -full".


I wrote script comments in the body of the script block.

I tried to make it as easy as possible to add new test cases to the list.

Here's the final script block and test code:



$isSorted = {

(LT)#

.SYNOPSIS

Checks wether an array is sorted, such that the second of two elements is greater than

or equal to the first.


.DESCRIPTION

Takes an array of any length and checks for being sorted. An array with 0 or 1 members is

sorted by definition.

The function tests each pair in sequence from left to right (0 to highest index) and returns

$false at the first fail. In principle, it will take longer to check a long, sorted array.


.PARAMETER $candidate

The array to be tested.

#(GT)

param ($candidate) # Takes any array - not tested for mixed arrays (strings and ints, for instance

for ($i = 0; $i -lt ($candidate.length - 1); $i++) # checks each position against the position to its right

{

if ($candidate[$i] -gt $candidate[$i+1]) # uses Greater Than.

{

return $false # One failure of Greater Than gives a $false result.

}

}

return $true # if none fail, then true

}

(LT)#

&$isSorted $sorted


&$isSorted $unsorted

#(GT)


# Add test cases as needed.


$sorted = 1,2

$sorted[0] = 1,2,3,4,5 #Expected True

$sorted[1] = 1,1,1,1,1 #Expected True


$unsorted = 1,2,3

$unsorted[0] = 1,2,3,4,3 #Expected False

$unsorted[1] = 3,2,3,4,5 #Expected False

$unsorted[2] = 3,2,3,4,3 #Expected False




foreach ($a in $sorted)

{

if (!(&$isSorted $a)) {"FAIL: List is sorted: $a"}

}


foreach ($a in $unsorted)

{

if (&$isSorted $a) {"FAIL: List is not sorted: $a"}

}}

Friday, May 13, 2011

More with Functional Programming

A little project time today. Just play with PowerShell script blocks. Let's do a sort function. Easy enough to do and useful enough.

I'm going to start by doing a sort for integer arrays with five members. I'll generalize later.

First of all, how do you know whether something is sorted?


That took me an incredibly long time – I assumed I could easily write a script block that would do what I wanted. No – it was not taking an array as its argument. I'm still not sure why.

I finally turned it into a function and specified the parameter in the function signature. This works, but I don't know why the alternative (with the param keyword) does not.

function isSorted ([int32[]]$a) {

for ($i = 0; $i -lt 3; $i++)

{

if ($a[$i] -gt $a[$i+1])

{

return (1 -eq 0)

}

}

return (1 -eq 1)

}



isSorted $sorted


isSorted $unsorted


The result of this is:


True

False


Hang on – I'll try to fix the function to take an array of any length. Here's the key line:

for ($i = 0; $i -lt ($a.length - 2); $i++)

OK, that'll do for today.


Housekeeping note:


I may not be able to keep this blog going 5 days a week, as I have been. I'm starting a new contract on Monday and I won't have quite so much time. I'll try to not let it fall by the wayside.

Wednesday, May 11, 2011

Side Project: Functional Programming

There's been a revival in interest in functional programming recently. Languages like Haskel have been getting attention. I wanted to work on some of this and – thanks, again, to PowerShell for being nifty – I can do so directly using PowerShell Script Blocks.

Function programming approaches problems using state-less code and not relying on side effects. Where Object Oriented programming would start by wrapping a state in a class, along with the behaviors that modify the state, functional programming creates functions – in nearly the mathematical sense of the word – that produce the desired behaviors. Because the functions do not rely on side-effects, they work exactly as expected, every time.

I do appreciate the clarity of intent inherent in this statement of the approach. The problem that I'm having is that calculating Fibonacci’s sequence doesn't come in handy for me that often.

There has to be a way I learn something out of all this.

Here's some scripting I did:

# new-alias -name run -value invoke-command


$tick = {

param ($wheelState, $wheelSize = 10)

$wheelState++

if ($wheelState -gt ($wheelSize-1)) { 0 }

else {$wheelState}

}


$a = {

param ($b, $c = 0)


if ($b -gt 0) {

$b--;

$c = run $tick -arg $c


run $a -argument $b,$c

$c

}


}

run $a -arg 22


The first line lets you use “run” instead of “invoke-command” since I like run better. You can only set the alias once per session (maybe I'll add it to my profile later.)

This is the odometer problem that I worked on a couple of months back. It models a wheel that counts from 0 to 9 and returns to 0.

The first script block handles that 0 to 9 stuff. I even set it to take a default value of 10, allowing you to use it for any size wheel.

You know, these are hard to read. I should document them.

[LESSTHAN]#

.SYNOPSIS

Models a wheel in an odometer, including values from 0 to x, default 10.


.DESCRIPTION

Takes a value and the size of this odometer wheel and increases the odometer value

by 1 and returns that value. If the value exceeds the size of the wheel, the value is

reset to 0.

.PARAMETER $wheelState

The current state of the wheel. This value is not validate, so it could be larger than

the size of the wheel or less than 0.

.PARAMETER $wheelSize

Size of the wheel to be ticked. Default is 10 (0 to 9).

#[GREATERTHAN]

I used the PowerShell comment-based help standard. I can't just get the help output from the script block. If you turn it into a function, though, and use “get-help” you get the following:

PowerShell: get-help x


NAME

x

SYNOPSIS

Models a wheel in an odometer, including values from 0 to x, default 10.

SYNTAX

x [[-wheelState] [LESSTHAN]Object[GREATERTHAN]] [[-wheelSize] [LESSTHAN]Object[GREATERTHAN]] [[LESSTHAN]CommonParameters[GREATERTHAN]]

DESCRIPTION

Takes a value and the size of this odometer wheel and increases the odometer value

by 1 and returns that value. If the value exceeds the size of the wheel, the value is

reset to 0.


RELATED LINKS


REMARKS

To see the examples, type: "get-help x -examples".

For more information, type: "get-help x -detailed".

For technical information, type: "get-help x -full".

And the other script block:

PowerShell: get-help x


NAME

x

SYNOPSIS

Increases an odometer wheel by a specified number of ticks.

SYNTAX

x [[-increment] [LESSTHAN]Object[GREATERTHAN]] [[-state] [LESSTHAN]Object[GREATERTHAN]] [[LESSTHAN]CommonParameters[GREATERTHAN]]

DESCRIPTION

Increases an odometer wheel by the specified number of ticks. This version

assumes the default odometer wheel (10).

The default state of the odometer is 0, but it can take any value.


RELATED LINKS


REMARKS

To see the examples, type: "get-help x -examples".

For more information, type: "get-help x -detailed".

For technical information, type: "get-help x -full".

While I was going through this, I realized that not having any validation is – well, I don't like it.

In the case of functional programming, having no validation means that there are no expected outputs for a large number of possible inputs. This is just messy.

This command should cover it:


if ($wheelState -lt 0) { 0 }

If the $wheelstate is larger than the wheel size, the next line of script will make it 0 anyway. This makes 0 the default for all unknown inputs.

Here's my new script:

# new-alias -name run -value invoke-command


$tick = {

[LESSTHAN]#

.SYNOPSIS

Models a wheel in an odometer, including values from 0 to x, default 10.


.DESCRIPTION

Takes a value and the size of this odometer wheel and increases the odometer value

by 1 and returns that value. If the value exceeds the size of the wheel, the value is

reset to 0.

.PARAMETER $wheelState

The current state of the wheel. This value is not validate, so it could be larger than

the size of the wheel or less than 0.

.PARAMETER $wheelSize

Size of the wheel to be ticked. Default is 10 (0 to 9).

#[GREATERTHAN]

param ($wheelState, $wheelSize = 10)

$wheelState++

if ($wheelState -lt 0) { 0 } # Validate input: any negative value returns a state of 0.

if ($wheelState -gt ($wheelSize-1)) { 0 } # Any value greater than size returns a value of 0.

else {$wheelState} # Return wheel state other than 0.

}


$turnWheel = {

[LESSTHAN]#

.SYNOPSIS

Increases an odometer wheel by a specified number of ticks.


.DESCRIPTION

Increases an odometer wheel by the specified number of ticks. This version

assumes the default odometer wheel (10).

The default state of the odometer is 0, but it can take any value.

.PARAMETER $increment

Number of ticks to be added to wheel.

.PARAMETER $state

Current state of wheel.

#[GREATERTHAN]

param ($increment, $state = 0)

if ($increment -lt 1) { $state } # A value of 0 or less than 0 returns the state unchanged.

if ($increment -gt 0) { # While increment value is greater than 0:

$increment--; # Decrease increment value.

$state = run $tick -arg $state # Tick odometer wheel.


run $turnWheel -argument $increment,$state # Recurse this script block.

}

$state # Display state.


}

"Value 22:"

run $turnWheel -arg 22


"Value 22, starting state 10:"

run $turnWheel -arg 22,10



"Value -1:"

$x = -1

run $turnWheel -arg $x,10 #NOTE: This returns an invalid state.

The only fly in the ointment, now, is that you can get an invalid state – if the increment operation fails, you get a state that can't be the result of a tick. That is, 10 is too large for a wheel. That can be fixed later.



Tuesday, May 10, 2011

Watch Project Wrap up

I started coding on the watch project on May 2. I finished it on May 9 – including a lost day in the middle where I was working on build issues. Before that, there were two days of planning.

So, 8 days, total.

Here are the members of Spring:

PowerShell: $test = new spring


____________________________________________________________________________________________________________________________

PowerShell: $test | get-member



TypeName: Spring


Name MemberType Definition

---- ---------- ----------

display Method System.Void display()

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

set Method bool set(int setValue)

tick Method bool tick()

ToString Method string ToString()

wind Method int wind()

And Hand:

PowerShell: $test = new hand(70, 89)


____________________________________________________________________________________________________________________________

PowerShell: $test | get-member



TypeName: Hand


Name MemberType Definition

---- ---------- ----------

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

tick Method bool tick()

ToString Method string ToString()

Display Property System.Int32 Display {get;}

So, I wrote 2 classes with 2 constructors and 6 public methods in about 8 hours of work.

Of course, these were simple tests because they didn't have ranges of values to pass around. The earlier project – the match stick game – had more complicated stuff and some more complicated tests.

But – on the whole – the methodology I'm practicing seems to work for the problems I've played with.

Monday, May 9, 2011

Designing the Spring Class, Part 2

First up is code documentation for the Spring class. Here's what I came up with:

public class Spring

{

// FIELDS

// Array for the watch hands. Future TODO Use a list so the watch can take any number of hands.

Hand[] hand;

// Main spring of watch.

int mainSpring = 0;

// CONSTRUCTORS

/*

Initializes the hand array and declares and initializes the hands that belong to it.

*/

public Spring ()

{

hand = new Hand[4]; // Initialize the array

hand[0] = new Hand(60, 1); // second hand

hand[1] = new Hand(3600, 60); // minute hand

hand[2] = new Hand(43200, 3600); // hour hand

hand[3] = new Hand(86400, 43200); // day hand

}

// PROPERTIES

// METHODS

/*

Displays all the hands, in order: am/pm, hour, minute, second.

Displayed on a single line. Space serves as separator.

*/

public void display ()

{

Console.Write(hand[3].Display + " ");

Console.Write(hand[2].Display + " ");

Console.Write(hand[1].Display + " ");

Console.Write(hand[0].Display + " ");

}

/*

Simulates wining the clock by increasing the value of mainSpring.

Ignores input after spring reaches 100000.

Returns current value of spring.

*/

public int wind()

{

if (mainSpring [LESSTHAN] 100000) // Maximum tension the spring can take.

{

mainSpring++;

}

return mainSpring;

}

/*

Causes each of the hands to tick once while unwinding the spring one tick.

Returns false if mainSpring is not wound or if any of the hands return a false.

Returns true if everything works.

*/

public bool tick()

{

if (mainSpring [LESSTHAN] 1) return false;

bool temp = true; // Local variable to keep track of results

foreach (Hand x in hand) // For each hand in the array. All take ticks

{ // Does the tick as a side-effect

temp = (x.tick() | temp); // Allows a single false to return a false value.

}

mainSpring--;

return temp;

}

#if DEBUG

// TESTING CODE

#endif

// OVERRIDES

}

Next, I'm going to go back to the blog, where I wrote down what I meant to do with this project.

Well, I planned on including a Set method that would allow the mainSpring to set the clock. Let's do a simple one.

Here it is:

public bool set(int setValue)

{

// Get all hands into a known state.

hand[0] = new Hand(60, 1); // second hand

hand[1] = new Hand(3600, 60); // minute hand

hand[2] = new Hand(43200, 3600); // hour hand

hand[3] = new Hand(86400, 43200); // day hand

while (setValue [GREATERTHAN] 0) {

if (!(tickLight())) return false; // calls correct number of ticks.

setValue--; // false if a tick fails.

}

return true; // true on success.

}

I had to create a new private method that did a tick without decrementing the mainSpring field:

private bool tickLight()

{

bool temp = true; // Local variable to keep track of results

foreach (Hand x in hand) // For each hand in the array. All take ticks

{ // Does the tick as a side-effect

temp = (x.tick() | temp); // Allows a single false to return a false value.

}

return temp;


}

And now I have to do some testing.

I was having a problem testing the display method – the output wasn't comparable to anything. It wasn't working like a string or an int.

I should be able to redirect the output of the Display command to an object and serialize that object for later use. I think I did one of the tests in the earlier project htat way.

But that didn't work here. I do have another way. Let's try this:

# Testing Spring set method

#

$testSpring = new Spring

$testSpring2 = new Spring


$temp = $testSpring.set(99)

$temp = $testSpring.Display()


for ($a = 1; $a -lt 100; $a++)

{

$temp = $testSpring2.wind()

$temp = $testSpring2.tick()

}


"Expected chaff:"

if (!($testSpring.Display() -eq $testSpring.Display())) {"FAIL: Set value should equal 99."}



#

# END Testing Spring set method

This is a little bit klugey.

The fact is, my display method is a little klugey. It relies on a side-effect of the Display method instead of returning a value.

But it is sufficient for now. I'll include a TODO note for future development.

The other thing that planned for back on April 29, 2011, was an entry point so that this project could be compiled outside of my PowerShell setup:

public class Watch

{

static void Main(string[] args)

{

Spring x = new Spring();

}

}

I'm just going to verify that everything still runs and call it a day.

Friday, May 6, 2011

Designing the Spring Class, Part 1

I spent an hour just coding and playing around in the Spring class. Let's see where things stand.

I wrote a constructor for Spring that initialized the hands for the watch. I used an array, instead of a list – it should be adequate and I can retrofit a list in later, if it seems like a good idea.

public Spring ()

{

hand = new Hand[4];

hand[0] = new Hand(60, 1); // second hand

hand[1] = new Hand(3600, 60); // minute hand

hand[2] = new Hand(86400, 3600); // hour hand

hand[3] = new Hand(172800,43200 ); // day hand

}

I didn't write a test for this because that would just be “$test = new Spring” which is going to be included in all my tests anyway.

public int wind()

{

if (mainSpring LT 100000) // Maximum tension the spring can take.

{

mainSpring++;

}

return mainSpring;

}


I can test this. (Oh, there isn't any way to know how tightly wound the spring is without winding it.)

# Testing Spring Wind method

#

$testSpring = new Spring


for ($a = 1; $a -lt 100000; $a++)

{

if ($testSpring.wind( ) -ne $a) {"FAIL:"}

}



for ($a = 100000; $a -lt 200000; $a++)

{

if ($testSpring.wind( ) -ne 100000) {"FAIL:"}

}

This will verify that the spring can be wound, but only so far.

So, next up is the tick method.

public bool tick()

{

if (mainSpring GT 1) return false;

bool temp = true; // Local variable to keep track of results

foreach (Hand x in hand) // For each hand in the array. All take ticks

{ // Does the tick as a side-effect

temp = (x.tick() | temp); // Allows a single false to return a false value.

}

mainSpring--;

return temp;

}

I don't see how one of the ticks calls on a hand could fail, but if it does, I want that failure to be passed up to the mainSpring.

Here's some testing:

$testSpring = new Spring



if ($testSpring.tick()) {"FAIL: First tick should fail since the spring has not been wound."}




for ($a = 1; $a -lt 75; $a++)

{

if ($testSpring.wind( ) -ne $a) {"FAIL: Wind should work."}

}



for ($a = 1; $a -lt 75; $a++)

{

if (!($testSpring.tick( ))) {"FAIL: Tick should work."}

}



if ($testSpring.tick()) {"FAIL: This tick should fail since the spring has not been wound."}

Finally, I wrote a Display method that would show me that state of the watch:

public void display ()

{

Console.Write(hand[3].Display + " ");

Console.Write(hand[2].Display + " ");

Console.Write(hand[1].Display + " ");

Console.Write(hand[0].Display + " ");

}

Yeah, it's Q&D, but it does what it is supposed to do.

Oh, and it gave me an unexpected result:


PowerShell: $testSpring = new Spring


PowerShell: $testSpring.display()

4 24 60 60


4? why 4?


Ad hoc testing time:


PowerShell: for ($i = 1; $i -lt 43201; $i++) { $testSpring.wind(); $testSpring.tick();}

PowerShell: $testSpring.display()

1 12 60 60


Wait a minute – I have the numbers wrong in the mainSpring constructor. This is how it should read:

public Spring ()

{

hand = new Hand[4];

hand[0] = new Hand(60, 1); // second hand

hand[1] = new Hand(3600, 60); // minute hand

hand[2] = new Hand(43200, 3600); // hour hand

hand[3] = new Hand(86400, 43200); // day hand

}

And this gives the following:


2 12 60 60


PowerShell: for ($i = 1; $i -lt 43201; $i++) { $temp = $testSpring.wind(); $temp = $testSpring.tick();}


PowerShell: $testSpring.display()

1 12 60 60

OK, that is the basic code for this project.

Next time, I'll write method documentation and that will be a wrap.

Thursday, May 5, 2011

Side Tracked in designing the Spring Class

Time to start the Spring class.

The spring class will maintain a its own state as a reservoir of ticks. The number of ticks will be increased using a wind method and – while is has ticks – be released by calling the hands. Of course, it will also have to create and maintain the hands.

I'll need a new script to wrap the Spring class –

And then I ran into trouble.

It seems that – using Add-Type as I was – you can't import a class like my new Spring class because it refers to another class (Hand) that the compiler can't find.

I spend some time trying to figure out how to get the compiler to find it, but it was not working.

What I did come up with was a little different way to do my source files. I can give Add-Type a path instead of a string. I'm going to implement that now and call it a day.


foreach ($a in dir .\Code) {

"CODE FILE: $a"

invoke-expression "Add-Type -path Code\$a -IgnoreWarnings"}

foreach ($a in dir .\Test) {

"TEST SCRIPT: $a"

invoke-expression "Test\$a" }

I added the Ignore Warnings flag because it was giving me a warning-as-error about declaring but not using some hand objects. That will be fixed pretty soon.

Wednesday, May 4, 2011

Designing the Hand Class, Part 3

OK, the day hand was not a problem. It took me a little time to work through the cases, but it was fine:

testDayHand 1 2

testDayHand 0 2

testDayHand 43199 2

testDayHand 43201 1

testDayHand 43200 1

testDayHand 86399 1

testDayHand 86400 2

testDayHand 86401 2

This testing, like the other hands, checks at 0 and 1 tick and then again as the number of ticks is sufficient to change the object's display. For Day, that means every 12 hours or 43200 ticks.

Oh, 2 means “a.m.” Well, I guess. 1 will mean “p.m.”

I thought about writing more general tests – a function that would work for all the different hands or for other imaginable hands. I decided, though, that that was beyond my design.

Next, I don't see how to test display any better than what I've done so far. For now, I'm going to put a note in the display test file and call the Hand class done.

Except for documentation, which I will write now.

Here is the final version of the class:


Add-Type @'

#define DEBUG


/*

This class models a hand on a wristwatch. The same class will work for

second hands, minute hands, hour hands, and a.m./p.m. hands.


As an assumption, 2 means a.m., while 1 means p.m.


This class might work for other items (like weeks or equal-length months), but hasn't been designed

or tested for those uses.

*/

public class Hand

{

// FIELDS

// The number of ticks necessary to return to the same state.

int maxState;

// Number of ticks necessary to change the object's displayed state. 60 for a minute, for instance.

int increment;

// Current state of the object. Values 1 to maxState, inclusive.

// Note: not 0-based.

int state;

// CONSTRUCTORS

/*

Specified the type of hand, using the size of the hand (in seconds) and the nubmer of seconds needed to

increment the hand.

xState: Number of ticks necessary to make the hand have the same value.

xIncrement: Number of ticks necessary to cause a change in the hand's displayed value.

*/

public Hand (int xState, int xIncrement)

{

if (xIncrement < 1) { xIncrement = 1;} // validation to avoid negative numbers and divide by 0 errors.

if (xState < xIncrement) { xState = xIncrement;} // validation to avoid cases where increment is larger than the possible size of the hand.

maxState = xState; // Set maxState

increment = xIncrement; // Set increment

state = xState; // Set current state to same as maxState (that is, to midnight.)

}

/*

Displays the value of the hand.

Value is determined by the state of the hand to the resolution specified by increment.

*/

public int Display

{

get

{

if ((state / increment) == 0) return (maxState / increment); // States of less than 1 increment are returned as the max value. That is, 12 oclock and one second is 12 oclock.

return state / increment; // Returns current value. Note the implicit truncation achieved by using only ints.

}

}

// PROPERTIES

// METHODS

/*

Change the state of the hand by one tick, implicitly a second.

Returns: True if the tick can be accomplished. This version does not have a way to return false.

*/

public bool tick()

{

state++; // Increase state by one.

if (state > maxState) // If larger than the size of the hand:

{

state = 1; // Reset to 1

} // There is no 0 value.

return true; // Always return True.

}

#if DEBUG

// TESTING CODE

#endif

// OVERRIDES

}

'@

This is a little short for today (I've been at this about 40 minutes. For this week, I'm trying to do about one hour at a time.)