Phillip Trelford's Array

POKE 36879,255

Random Art

Earlier in the year I came across a Stanford coding assignment inspired by Andrej Bauer’s Random Art. Pictures are built using randomly chosen mathematical expressions that take an x and y value and return a colour. The implementation on Andrej’s site uses OCaml, but is closed source, however a clear Python example is given.

F# version

The Python version worked out-of-the-box but took a while to render (10s of seconds) so I rewrote it in F# (a language based on OCaml) to improve generation time (to less than a second).

The random pictures are unsurprisingly a bit hit and miss so I set up a script to generate batches of 1000 and then sifted through to find ones I liked, here’s a few examples:

Random0093 tartan
Random0937 Random - Copy (9)

 

The image generation is a heavy compute task, running on my i7 Desktop was noticeably faster than my MBP. For yet faster generation the F# code was trivial to parallelise using the Array.Parallel module.

You can run the F# version on Linux, Mac or Windows, just run this snippet as an F# script: http://fssnip.net/si

 

Go version

I’ve been picking up the Go programming language recently, just out of curiosity, and thought this would be an interesting task to try.

Initially I’d used Notepad and the command line on Windows, for this task I switched to Mac and the Atom editor with go-plus, which gives syntax colouring and some code completion and appears to be a relatively popular choice nowadays:

Go Editors

Aside: for editing F# in Atom try the excellent atom-fsharp

Rather than building a UI, I simply used Go’s image package which supports setting pixels and saving images.

Here’s a skeleton using a fixed function:

To produce random art I used an interface to define expressions with each type defined using a structure and associated evaluation function. The expressions are then randomly selected and then composed. The source is available as a gist.

Here's some pictures from the first run:

output472 output518
output164 output670

 

Comparing implementations

The F# and Go implementations feel quite close. In F# I used a discriminated union to define the expression types and functions for evaluation. Similarly in Go I used structures to define the expression data and functions for evaluation. In both cases separating the concerns of data representation and evaluation. In effect, if we ignore the curly braces, programming in Go feels to me more akin to programming in F# than programming C# or Java. Other similarities include multiple return values in Go and first class tuples in F#, and Go’s defer and F#’s use keyword for simple resource management.

 

Hands On Random Art Class

If you’re interested in producing your own random art, I’ll be running a free class at the F#unctional Londoners in October, where we’ll explore some different formulas.

Ocean Revival

This weekend I had the pleasure of sitting on the Ocean Q&A panel at Revival 2014 in Wolverhampton. I worked at Ocean in Manchester in my early 20s on titles like Jurassic Park (PC & Amiga) and Addams Family Values (SNES & Megadrive). It was fun to reminisce about the good old days with other former Ocean employees and people who’d played the games.

Ocean panel

The panel closely coincided with the public release of The History of Ocean Software book by Chris Wilkins which was funded as a Kickstarter:

Ocean the history

There were plenty of old games to play at the event too. I particularly enjoyed Rez on a PS2, Omega Race on a Vic-20 and a Flappy Bird clone on a Commodore 64.

Flappy Bird C64

When we got home, my 7yo and I pulled the Vic-20 out of the garage, and played some more Omega Race with the joystick we’d just picked up:



My 7yo has been picking up Python recently, with a Coding Club - Python Basics book.

One of the tasks is to print out the 5 times table:

number = 1
while i <= 12:
    print(number,"x 5 =",number*5)
    number = number + 1

Funnily enough Vic-20 Basic (circa 1981) was easily up to the challenge too:

5 times table

And good old FizzBuzz was no bother either:

FizzBuzz Vic-20

Then my son had a go at Magic 8-ball, but sadly lost the code he’d spent a while typing in when it is closed, so we re-wrote it again in F# so there was less to type:

let answers =[
   "Go for it!"
   "No way Jose!"
   "I'm not sure. Ask me again."
   "Fear of the unknown is what imprisons us."
   "It would be madness to do that!"
   "Only you can save mankind!"
   "Makes no difference to me, do or don't - whatever."
   "Yes, I think on balance that is the right choice"
   ]

printfn "Welcome to Magic 8-Ball."

printfn "Ask me for advice and then press enter to shake me"
System.Console.ReadLine() |> ignore

for i = 1 to 4 do printfn "Shaking..."

let rand = System.Random()
let choice = rand.Next(answers.Length)

printfn "%s" (answers.[choice])

Why not dig out your old computers and have some programming and games fun! :)

Code Golf

Last month Grant Crofton popped down from Leeds to the F#unctional Londoners meetup at Skills Matter to run a fun hands on code golf session. The idea of code golf is to implement a specific algorithm in the fewest possible characters. This is not the kind of thing you should be doing in enterprise code, but it is fun, and an interesting way of exploring features in a programming language.

On the night we attempted condensed versions of FizzBuzz and 99 bottles of beer, with Ross and I winning the first challenge and Simon & Adrian the second.

FizzBuzz Score99 Bottles Score

Thanks again to Grant for a really fun session.

F# FizzBuzz

A while back I strived to squeeze an F# implementation of FizzBuzz into a tweet, and with white space removed it weighs in at 104 characters (excluding line breaks):

for n=1 to 100 do 
 printfn"%s"
  (match n%3,n%5 with 0,0->"FizzBuzz"|0,_->"Fizz"|_,0->"Buzz"|_,_->string n)

The implementation, although quite clear, requires a fair number of characters for the pattern matching portion.

After some head scratching we came up with the idea of using a lookup to select the string to display:

N %3 N % 5 Index Output
0 0 0 N
>0 0 1 “Fizz”
0 >0 2 “Buzz”
>0 >0 3 “FizzBuzz”

This took the implementation down to 89 characters (without line breaks):

for i=1 to 100 do
 printfn"%s"["FizzBuzz";"Buzz";"Fizz";string i].[sign(i%5)*2+sign(i%3)]

Another trick is to abuse the sign function, to get 1 if the result of the modulus is above 0 and 0 otherwise.

The lookup trick can be used in other languages, and here’s a few examples, just for fun.

VB.Net FizzBuzz

VB.Net has a reputation for being a little verbose, but using the lookup trick it was possible to it get down to 96 characters (excluding line breaks):

For i=1 To 100:
Console.WriteLine({i,"Fizz","Buzz","FizzBuzz"}(-(i Mod 3=0)-(i Mod 5=0)*2))
:Next

In VB.Net true values translate to –1 and false to 0. This allowed me to simply negate the result of i % N = 0 to compute an index.

Python FizzBuzz

Using a similar trick in Python, where true translates to 1 and 0 to false, I was able to get to a very respectable 79 characters (excluding line breaks):

for x in range(1,101):
 print([x,"Fizz","Buzz","FizzBuzz"][(x%3==0)+2*(x%5==0)])

Python’s simple print function also helped to keep the character count down.

Amanda FizzBuzz

Amanda is a variant of David Turner’s quintessential functional programming language Miranda. Amanda runs on Windows, and is used for teaching FP at some universities.

Using a list comprehension it was possible to squeeze in to a mere 67 characters:

[["FizzBuzz","Buzz","Fizz",itoa x]!(min[1,x%3]+min[1,x%5]*2)|x<-[1..100]]

Note: this is cheating a little as we are not explicitly writing to the console.

APL FizzBuzz

APL is a very mature language, dating back to the 1960s, and is still used commercially today. It also wins hands down in code golf with just 54 characters:

⍪{'FizzBuzz' 'Buzz' 'Fizz'⍵[1+(2×1⌊5|⍵)+1⌊3|⍵]}¨⍳100

APL is particularly strong at matrix processing and provides single character representations for common operations:

Notation Name Meaning
B Index generator Creates a list from 1 to B
¨ Each for each loop
Table Produces a one column matrix
B Floor Greatest integer less than or equal to B

Try APL in your browser now.

Challenge

Can you beat the APL implementation of FizzBuzz?

Have fun!