Nim and the Sinclair Cambridge Programmable calculator

The game of Nim comes in many forms, but the idea is same: players take turns to remove objects from a pile and the player left taking the last object loses. Or wins. You can play it so you win if you take the last piece, but I think it’s usually last piece loses, which apparently makes it a misère game. (Apparently they play Nim in Last Year at Marienbad, so I probably ought to get round to watching that one day.)

I taught Nim in my first ever year 3 class, and I was reminded of it when students from Queen Mary University of London were showing the Dr Nim game at Science Museum Lates (thank you Alan O’Donohoe!). This is a plastic game with marbles about the size and colour of an etch-a-sketch that is designed to win at Nim. It’s basically an ingenious, plastic computer:

I was convinced that Nim was one of the first computer games I ever played, probably on my brother’s Kim-1. But I can’t find anything about a Kim Nim so I now think the first version I really played was on the Sinclair Cambridge Scientific Programmable Calculator which came out in 1977. This was quite an amazing machine. The same elder brother had an eyewateringly-expensive HP programmable calculator that stored programs on magnetic strips. But the Sinclair was a machine cheap enough for me, a schoolboy, to own.

I think it’s fair to say I never used any from volumes 2, 3 or 4 such as ‘Inverse Hyperbolic Functions’ (volume 2), ‘Doppler effect (non-relativistic)’ (volume 3) or ‘Operating point of transistor in base-potential divider and emitter resistor bias’ (volume 4). Playing Nim and spelling rude words was probably, age 12, more my thing.

In the table below is the program for the ‘matchstick game’ from volume 1 (‘General/Finance/Statistics’) of the four volume boxed set of programs that came with the Sinclair Cambridge Programmable. It’s a simple version of Nim where you have 1 pile, you type in how many matchsticks you want to start with and you and the calculator take it in turns to take 1, 2 or 3 sticks from the pile. Whoever is left with the last stick is the loser.

I cannot decypher how this code works, and would love some help, because eventually got it to stay on long enough to enter and run the program for the matchstick game. And work it does! I cannot beat it, and it must be using a strategy to divide the pile into groups of 4 to ensure the human player is always left with 4 sticks in their penultimate move (see Dr Nim video above for more on this strategy for winning 1-pile Nim). It seems like an ingenious algorithm that uses less than 36 instructions to play this, and with such a ridiculously limited instruction set.

Here’s what I’ve worked out about what it does, although apart from possibly repeatedly subtracting 4 I cannot figure out precisely how it works. ‘sto’ means store a number in memory. ‘rcl’ means recall a number from memory. You can ignore the hash/pound sign # as that just means the next digit is a number not an instruction and you can also ignore ▼ which tells the calculator that the next instruction needs a shift, it’s a ‘lower case’ instruction found underneath that key’s label. The pleasing command ‘gin’ is nothing to do with drink, but means ‘go if negative’, which I think is the only conditional branching instruction the Cambridge Programmable has. I assume the following two digits are the address the program branches to if the number being considered is indeed negative.

If you can draw me a flowchart or write pseudocode for precisely how this program works (and who was the author!?) I shall be hugely grateful…

instruction step
sto 00
- 01
( 02
rcl 03
+ 04
# 05
3 06
- 07
# 08
4 09
- 10
- 11
12
gin 13
0 14
7 15
+ 16
17
gin 18
2 19
4 20
# 21
5 22
- 23
# 24
4 25
= 26
) 27
- 28
stop 29
= 30
stop 31
= 32
= 33
= 35
= 36

To play the game, you enter the program and enter the number of sticks you you want to play with then press RUN. The machine plays. Then you enter 1, 2 or 3 depending on how many sticks you are taking and press RUN again. Then press RUN to get the machine to play, and repeat until you have 1 stick left, you loser…

I seem to have lost the actual manual for the calculator, although it’s not massively helpful it does explain a few things like brackets.
You can find out more about winning Nim strategies here and here.

Posted in computers, nostalgia | Tagged , , , | Leave a comment

Human Voices by Penelope Fitzgerald

another b-type

Human Voices by Penelope Fitzgerald (1980). 4th Estate Books, £8.99

It’s hard not think that I was destined to read, and indeed love, this book. Andy Miller recommended it to me saying he thought it would be right up my street – what with with my fondness for women writers and having worked myself for many years as a sound engineer in BBC radio, how could I not love this novel set in Broadcasting House (BH) in World War II with a finely-described view of the corporation’s jargon, technical details and beautifully humorous and observed human frailties? He tweeted a page in which two characters return from an absurd field trip recording sound effects of church doors with hours of material: ‘the quality’s superb, particularly on the last fifty-three bands or so’…

‘The engineer who had gone with them said nothing. He went straight away to have a drink.’

Just as I started reading the book for myself, something in Hermione Lee’s introduction seemed oddly familiar. Penelope Fitzgerald had lived in poverty on a boat on the Thames. This rang a bell. I quickly googled her life and a conversation I had some two years ago came back to me: she had taught English at the same girls’ school in South Kensington where I taught for two years recently. A Computer Science teacher, I was an interloper in the tiny, cramped English department office and it was the then head of English at Queen’s Gate, Jim Denchfield, who had recommended Penelope Fitzgerald to me. (I liked to think that my English degree allowed me passage into their world, and indeed I loved listening to them discussing books and the pupils’ responses to them. I did not envy them their marking, however.)

Fitzgerald’s name had fallen out of my head instantly (yes, you at the back there, nominal aphasia bugged me my entire teaching career until I decided not to worry about it any more) but I carried with me the idea that I had taught at the same school as a somewhat eccentric and neglected novelist, albeit one, I now realise, who won the Booker Prize.

A Queen’s Gate pupil remembers “her mild high voice often straying off into silence, and with a surprisingly sweet, warm smile”. Another pupil’s diary recorded:

“January 22 1965. Morning, treble English. To the lighthouse. Suzanne Judy & me drawing talking. Please I mean I am so sorry but honestly if you don’t like it please try to understand you see. Write about something like making the tea no please I mean I expect you don’t do such low things as that . . . . Mrs Fitzgerald double First Oxon.”

A N Wilson reviewing Hermione Lee’s bigoraphy of Penelope Fitzgerald in the TLS.

Hermione Lee describes how Penelope Fitzgerald started writing in the Queen’s Gate staff room:

“during my free periods as a teacher in a small, noisy staff room, full of undercurrents of exhaustion, worry and reproach.”

although I have to say that the English office I inhabited had major overcurrents of laughter and the most supportive colleagues I have ever worked with.

Human Voices is a short book, but not a slight one. Penelope Fitzgerald wrote with great economy but creates memorable scenes and characters that immerse you in a well-rounded world without exposition or needless description. I was amazed how familiar the world of BH in WWII was to me, really not so very different from Bush House (home of the BBC World Service) I joined in 1991 – the photo at the top of this page of me in the early 90s shows how even some of the studio equipment looked like it was of wartime vintage. Some of the jargon was the also same – assistants working on programmes were still called RPAs as they were in the 1940s.

The book outlines a battle for supremacy between live and pre-recorded programmes and how pre-recorded sound was regarded with some suspicion – to be ‘true’ it had to be live, and how this is the origin of, when it is not silenced for repairs, always using a live feed of the chimes of Big Ben, something I faded up and down in transmissions all my BBC career, from World Service programmes in dozens of different languages to The Westminster Hour on Sunday nights on Radio 4 right at the end of my BBC days.

The temporary dormitories in BH feature prominently in the story, and there were still dorms for shift workers in Bush House in the 90s and they afforded me just as much sleep as they seem to have done in wartime (i.e. none at all). A producer is informed he cannot fade the Marseillaise early for fear of causing offence, just as I was instructed never to fade our own national anthem before the end. Fitzgerald describes how some staffers are chosen to be placed on the ‘Indispensable Emergency Personnel List’ who, in the event of an invasion, would barricade themselves inside the basement of BH with hand grenades and, indeed, similar lists existed in the BBC I worked for – though I was, of course, never indispensable and never received the secret instructions myself.

Penelope Fitzgerald was famously a ‘late starter’, publishing her first book when she was 59, further endearing her to me. Still time, you see, still time to write that book. I am also a late starter reading her books, but I will now put that right as soon as I can and devour as many of her others as I can get my hands on.

Posted in BBC, fiction, literature, radio | Tagged , , , , , , | Leave a comment

10 things I have learned since becoming a teacher

As I lurch into my last three weeks of my teaching career (for a while at least) I thought I’d make a list of what my short but eventful teaching career has taught me. Most of these are teaching-specific but some may have resonances in the wider world.

The first two are the most important so if it’s all a bit TL/DR, just read those. They both came from the same person, Georgina Harland, who is as practical as she is wise.

1) Never under-estimate what you can achieve in 10 minutes. An excellent transferable life-skill. The classroom teacher is so busy that every second counts and where previously I may have thought it’s not worth starting a task in such a short amount of available time, now I know better. Do that bit of filing, make that resource, plan that lesson. 10 minutes. It’s longer than you think.

2) Life’s too short to laminate. Controversial one this, and I do sometimes laminate resources that are designed to be handled by children and re-used. But displays? Nah. Slap the childrens’ work up. Don’t mount it, don’t double-back it, don’t laminate it.

3) Confidence. I’m a naturally shy person, teaching is all about performing and has given me much greater confidence in life in general. I would not, for example, have been able to address a packed funeral before I had trained as a teacher.

4) Adults and children are quite similar. I think they learn the same ways, the lessons we learn from how to teach children should apply to teaching adults too. I sat through many 30-slide parroted PowerPoint presentations in which I was instructed that teaching should not be didactic. Now that, Alanis, is ironic.

5) Don’t print PowerPoint slides. Just take notes if you must. I have binders full of PowerPoint presentations from teacher training and CPD which I have never ever revisited. And almost certainly never will.

6) Every teacher should supply teach for a bit. I hated supply teaching but I learned so much. I discovered teachers were (at least in London) in much greater demand than I had realised (a couple of times I was offered a job before I even took my coat off), that I could have shopped around much more when looking for my first teaching post, that every school is totally different, that there are some very odd people running schools. In the space of six months I had more experience of different ways of doing things than some teachers (senior leaders even) manage in entire careers.

7) 95% of planning is wasted. I’ve probably been doing it all wrong but even when I had to make detailed lesson plans I would invariably forget things, and the lesson would take a different turn. I think good teachers adapt and are flexible within lessons; if a child says or does something unexpected but brilliant, I run with it, that can become the focus of the lesson. That has to be better than sticking rigidly to a script. I have been lucky in recent years to work in schools where I have been given the freedom to do this and did not have to submit next week’s detailed lesson plans by 7pm on Sunday into a folder that, it later transpired, no-one ever looked at (yes, that really happened to me).

8) Related to point 7 above, children are your best creative resource. They can’t, I admit, do your planning for you but they do constantly amaze with their creativity. I had a Year 1 girl go off-piste and make unexpectedly beautiful patterns in Scratch so that became the focus of our next lesson. My Code Club was wonderfully hijacked by another girl whose extraordinary Scratch animations and games entertained and transfixed everyone including me.

9) Fads and factionalism – no thanks. Even in my short (5 year) teaching career I have seen things come and go out of favour. Learning styles, mindfulness, multiple intelligences, growth mindsets, Maslow’s Hierarchy of Cheese (I’m pretty sure it was cheese), I’ve been taught them then been told they don’t even exist. There’s probably a grain of truth in most of these things: good lessons should stimulate many of the senses but let’s not turn every teaching point into a song made out of differently-textured smells differentiated 30 ways to accommodate each child’s ‘learning style’. Life’s too short.

Edu-twitter spats depress me beyond words, and the viscousness with which I see members of ‘the greatest profession’ ripping each other to shreds over things I just don’t understand makes me feel like I’m doing an extra playground duty rather than relaxing after hours. What would you say to children at school behaving like that? Children and adults. Much the same, see?

10) I don’t know how you do it. Class teachers in state primary schools, I’m talking to you. The job is insanely difficult, and no-one, but no-one who has not done this job (or possibly lived with someone who does it) can begin to understand how extraordinarily demanding (and damaging) the job can be. You need to have the patience of a saint, the wisdom of Solomon, time-management skills unheard of in any other industry, a bladder the size of Texas, a conviction that this is the only job that will make you happy, boundless enthusiasm, creativity, plus a severe lack of friends, family or social life in term time would be an advantage.

I could go on. I started teaching late in life because I thought I had time for ‘one more adventure’. It’s been quite a trip, but apparently I still have time for another adventure…

Posted in education | Tagged | Leave a comment

Web-based intro to ScratchJr


It’s been bugging me for a while that there’s no web-based intro to ScratchJr, MIT’s awesome version of Scratch for younger children. And ScratchJr only runs on tablets. I made some simple block-coding activities like this turtle drawing game and this maze game of my own in Scratch because I didn’t have any tablets and I needed to teach coding to young children in Reception and Year 1 classes.

I’ve since been teaching actual ScratchJr on some borrowed tablets and it’s given me the idea to make a very much simplified version of ScratchJr that can be used on laptops and desktop computers – made in Scratch, of course.

You don’t snap blocks together – there are 10 blocks already there, which you click on to cycle through different block types, most of the movement blocks and show/hide. Click on numbers below to change number of steps moved or hop distance. Click on red end block to toggle ‘forever’. Click go flag to run program, cycle though backgrounds with picture button, you can add name with ABC button, click on cat to change sprite. Press i to show instructions being executed, D to add date (useful for teachers who need to screenshot evidence), N to remove name.

Guide cat to the planetHave a play, let me know what you think. It could be a useful introduction to ScratchJr, especially if tablets aren’t always available. You could also use it with children who have already used ScratchJr as an assessment tool: choose a background with a particular goal (planet, castle, end of the road) and ask the class to program their sprites to reach it. The limited set of blocks and options would stop children going too far off-task (which I find can be a problem with both the most and least-able children!).

Posted in education, ICT | Tagged , , | Leave a comment

Microbit class votes

microbits in a grid voting yes and noUp to 25 pupils each has a micro:bit which they can use for voting YES or NO to any question. Pupils press button A to answer ‘no’ to a question, or button B to answer ‘yes’. They can shake their micro:bits to display their ID number and clear the display.

The answers are displayed in a grid on the teacher’s micro:bit’s display – dark/black pixels mean that person has not yet voted, dim ones mean a ‘no’ vote was recorded and bright ones mean a ‘yes’ vote was received from that pupil. The teacher can press button A to clear her micro:bit’s display.

This is based on another MakeCode project, the Voting Machine, again simplified and translated into Python.

Flash this program on to the teacher’s micro:bit:

from microbit import *
import radio
radio.on()

while True:
    message = radio.receive()
    if message:
        id = message[:2]
        vote = message[2:]
        print(id,vote)
        x = int(id[:1])
        y = int(id[1:])
        if vote == "0":
            bright = 4
        if vote == "1":
            bright = 9
        display.set_pixel(x, y, bright)
    if button_a.was_pressed():
        display.clear()

microbit pupil ID number grid

And flash the following program on to the pupils’ micro:bits. The ID numbers need setting according to the diagram above. (It’s the cunning use of these ID numbers that makes the code simpler). You might want to sit the class in a 5 x 5 grid if that’s possible – I do, however, appreciate class sizes are normally more than 25!

from microbit import *
import radio
radio.on()
id = "00"
display.scroll(id)

while True:
    if accelerometer.was_gesture("shake"):
        display.scroll(id)
    if button_a.was_pressed():
        display.show(Image.NO)
        radio.send(id+"0")
    if button_b.was_pressed():
        display.show(Image.YES)
        radio.send(id+"1")

It works by each voter’s micro:bit transmitting a 3 digit string such as
031
This would mean voter ID number 03 has voted ‘yes’. If they voted ‘no’ it would send ’030′. The teacher’s program splits the string up to identify the column (0) and row (3) of the voter, and lights the appropriate pixel bright for a ‘yes’ vote and dimly for a ‘no’.

You could also have fun drawing pictures or perhaps playing games like noughts and crosses with this or use it so pupils can say they need more help with a topic without the embarrassment of putting their hands up.

Version 2: add vote counting

Here’s a more advanced version of the teacher’s program. This one counts the Yes and No votes and displays them on the teacher’s display when button B is pressed, e.g. ‘Yes:2 No:5′. It then clears the display, so only use this when everyone has voted.

from microbit import *
import radio
radio.on()

def countvotes():
    yes = 0
    no = 0
    for column in range(5):
        for row in range(5):
            if display.get_pixel(column, row) == 4:
                no += 1
            if display.get_pixel(column,row) == 9:
                yes += 1
    votes = "Yes:"+ str(yes) + "   No:"+str(no)
    return(votes)

while True:
    message = radio.receive()
    if message:
        id = message[:2]
        vote = message[2:]
        print(id,vote)
        x = int(id[:1])
        y = int(id[1:])
        if vote == "0":
            bright = 4
        if vote == "1":
            bright = 9
        display.set_pixel(x, y, bright)
    if button_a.was_pressed():
        display.clear()
    if button_b.was_pressed():
        display.scroll(countvotes())

Version 3: Allow teacher to clear all screens

This version allows the teacher not just to count the votes cast but also clear pupils’ screens and ask them to vote again. It has slightly different code for both pupils and teacher. The teacher presses button B as before to count up the ‘yes’ and ‘no’ votes, but pressing button A will clear all the pupils’ displays and scroll the word ‘vote!’ across them.

Pupil program version 3:

from microbit import *
import radio
radio.on()
id = "00"

display.scroll(id)

while True:
    if accelerometer.was_gesture("shake"):
        display.scroll(id)
    if button_a.was_pressed():
        display.show(Image.NO)
        radio.send(id+"0")
    if button_b.was_pressed():
        display.show(Image.YES)
        radio.send(id+"1")
    message = radio.receive()
    if message == "vote":
        display.scroll("vote!")

Teacher program version 3:

from microbit import *
import radio
radio.on()

def countvotes():
    yes = 0
    no = 0
    for column in range(5):
        for row in range(5):
            if display.get_pixel(column, row) == 4:
                no += 1
            if display.get_pixel(column,row) == 9:
                yes += 1
    votes = "Yes:"+ str(yes) + "   No:"+str(no)
    return(votes)

while True:
    message = radio.receive()
    if message:
        id = message[:2]
        vote = message[2:]
        print(id,vote)
        x = int(id[:1])
        y = int(id[1:])
        if vote == "0":
            bright = 4
        if vote == "1":
            bright = 9
        display.set_pixel(x, y, bright)
    if button_a.was_pressed():
        radio.send("vote")
        display.clear()
    if button_b.was_pressed():
        display.scroll(countvotes())

It would be cool to add some feedback on a large screen – perhaps have a micro:bit communicating with a program on a computer to display a grid of yes/no answers – or just point a visualiser at the teacher’s micro:bit?

Posted in microbit | Tagged , | Leave a comment