# Blog

## Archive

Show me a Random Blog Post**2017**

**2016**

**2015**

**2014**

**2013**

**2012**

## Tags

folding paper folding tube maps london underground platonic solids rhombicuboctahedron raspberry pi weather station programming python php news royal baby probability game show probability christmas flexagons frobel coins reuleaux polygons countdown football world cup sport stickers tennis braiding craft wool emf camp people maths trigonometry logic propositional calculus twitter mathslogicbot oeis pac-man graph theory video games games chalkdust magazine menace machine learning javascript martin gardner reddit national lottery rugby puzzles advent game of life dragon curves fractals pythagoras geometry triangles european cup dates palindromes chalkdust christmas card bubble bobble asteroids final fantasy curvature binary arithmetic bodmas statistics error bars estimation accuracy**2016-10-08 12:39:14**

## Logical Contradictions

During my EMF talk this year, I spoke about @mathslogicbot, my Twitter bot that is working its way through the tautologies in propositional calculus. My talk included my conjecture that the number of tautologies of length \(n\) is an increasing sequence (except when \(n=8\)). After my talk, Henry Segerman suggested that I also look at the number of contradictions of length \(n\) to look for insights.

A contradiction is the opposite of a tautology: it is a formula that is False for every assignment of truth values to the variables. For example, here are a few contradictions:

$$\neg(a\leftrightarrow a)$$
$$\neg(a\rightarrow a)$$
$$(\neg a\wedge a)$$
$$(\neg a\leftrightarrow a)$$
The first eleven terms of the sequence whose \(n\)

$$0, 0, 0, 0, 0, 6, 2, 20, 6, 127, 154$$
^{th}term is the number of contradictions of length \(n\) are:This sequence is A277275 on OEIS. A list of contractions can be found here.

For the same reasons as the sequence of tautologies, I would expect this sequence to be increasing. Surprisingly, it is not increasing for small values of \(n\), but I again conjecture that it is increasing after a certain point.

### Properties of the Sequences

There are some properties of the two sequences that we can show. Let \(a(n)\) be the number of tautolgies of length \(n\) and let \(b(n)\) be the number of contradictions of length \(n\).

First, the number of tautologies and contradictions, \(a(n)+b(n)\), (A277276) is an increasing sequence. This is due to the facts that \(a(n+1)\geq b(n)\) and \(b(n+1)\geq a(n)\), as every tautology of length \(n\) becomes a contraction of length \(n+1\) by appending a \(\neg\) to be start and vice versa.

This implies that for each \(n\), at most one of \(a\) and \(b\) can be decreasing at \(n\), as if both were decreasing, then \(a+b\) would be decreasing. Sadly, this doesn't seem to give us a way to prove the conjectures, but it is a small amount of progress towards them.

### Similar Posts

Logic Bot, pt. 2 | Logic Bot | How OEISbot Works | Raspberry Pi Weather Station |

### Comments

Comments in green were written by me. Comments in blue were not written by me.

**2016-06-05 10:57:24**

## Making Names in Life

The Game of Life is a cellular automaton invented by John Conway in 1970,
and popularised by Martin Gardner.

In Life, cells on a square grid are either alive or dead. It begins
at generation 0 with some cells alive and some dead. The cells' aliveness in
the following generations are defined by the following rules:

- Any live cell with four or more live neighbours dies of overcrowding.
- Any live cell with one or fewer live neighbours dies of loneliness.
- Any dead cell with exactly three live neighbours comes to life.

Starting positions can be found which lead to all kinds of behaviour:
from making gliders
to generating prime numbers.
The following starting position is one of my favourites:

It looks boring enough, but in the next generation, it will look like this:

If you want to confirm that I'm not lying, I recommend the free Game of Life Software Golly.

### Going Backwards

You may be wondering how I designed the starting pattern above. A first, it looks like a difficult task: each cell can be dead or alive,
so I need to check every possible combination until I find one. The number of combinations will be \(2^\text{number of cells}\). This will
be a very large number.

There are simplifications that can be made, however. Each of the letters above (ignoring the

*g*s) is in a 3×3 block, surrounded by dead cells. Only the cells in the 5×5 block around this can affect the letter. These 5×5 blocks do no overlap, so can be calculated seperately. I doesn't take too long to try all the possibilities for these 5×5 blocks. The*g*s were then made by starting with an*o*and trying adding cells below.### Can I Make My Name?

Yes, you can make your name.

I continued the search and found a 5×5 block for each letter. Simply Enter your name in the box below and
these will be combined to make a pattern leading to your name!

### Similar Posts

The Mathematical Games of Martin Gardner | MENACE | Logical Contradictions | Dragon Curves |

### Comments

Comments in green were written by me. Comments in blue were not written by me.

**Add a Comment**

**2015-08-29 08:48:00**

## How OEISbot Works

A few weeks ago, I made OEISbot, a Reddit bot which posts information whenever an OEIS sequence is mentioned.

This post explaind how OEISbot works. The full code can be found on GitHub.

### Getting Started

OEISbot is made in Python using PRAW (Python Reddit Api Wrapper). PRAW can be installed with:

pip install praw

Before making a bot, you will need to make a Reddit account for your bot, create a Reddit app and obtain API keys. This python script can be used to obtain the necessary keys.

Once you have your API keys saved in your praw.ini file, you are ready to make a bot.

### Writing the Bot

First, the necessary imports are made.

import praw

import re

import urllib

import json

from praw.objects import MoreComments

import re

import urllib

import json

from praw.objects import MoreComments

To prevent OEISbot from posting multiple links to the same sequence in a thread, a list of all the sequences which have been linked to is loaded.

with open("/home/pi/OEIS/seen") as f:

seen = json.load(f)

seen = json.load(f)

Next, OEISbot logs into Reddit.

r = praw.Reddit('OEIS link and description poster by /u/mscroggs.')

access_i = r.refresh_access_information(refresh_token=r.refresh_token)

r.set_access_credentials(**access_i)

auth = r.get_me()

access_i = r.refresh_access_information(refresh_token=r.refresh_token)

r.set_access_credentials(**access_i)

auth = r.get_me()

The subs which OEISbot will search through are listed. I have used all the math(s) subs which I know about, as these will be the ones mentioning sequences.

subs = ['math','mathpuzzles','casualmath','theydidthemath',

'learnmath','mathbooks','cheatatmathhomework','matheducation',

'puremathematics','mathpics','mathriddles','askmath']

'learnmath','mathbooks','cheatatmathhomework','matheducation',

'puremathematics','mathpics','mathriddles','askmath']

The markup function loads the necessary information from OEIS and formats it. Each comment will end with the output of the me function. The ouput of joiner will be used between sequences which are mentioned.

def markup(seq_n):

pattern = re.compile("%N (.*?)<",re.DOTALL|re.M)

desc=urllib.urlopen("http://oeis.org/A"+seq_n+"/internal").read()

desc=pattern.findall(desc)[0].strip("\n")

pattern = re.compile("%S (.*?)<",re.DOTALL|re.M)

seq=urllib.urlopen("http://oeis.org/A"+seq_n+"/internal").read()

seq=pattern.findall(seq)[0].strip("\n")

new_com = "[A"+seq_n+"](http://oeis.org/A"+seq_n+"/): "

new_com += desc+"\n\n"

new_com += seq+"..."

return new_com

def me():

return "I am OEISbot. I was programmed by /u/mscroggs. [How I work](http://mscroggs.co.uk/blog/20)."

def joiner():

return "\n\n- - - -\n\n"

pattern = re.compile("%N (.*?)<",re.DOTALL|re.M)

desc=urllib.urlopen("http://oeis.org/A"+seq_n+"/internal").read()

desc=pattern.findall(desc)[0].strip("\n")

pattern = re.compile("%S (.*?)<",re.DOTALL|re.M)

seq=urllib.urlopen("http://oeis.org/A"+seq_n+"/internal").read()

seq=pattern.findall(seq)[0].strip("\n")

new_com = "[A"+seq_n+"](http://oeis.org/A"+seq_n+"/): "

new_com += desc+"\n\n"

new_com += seq+"..."

return new_com

def me():

return "I am OEISbot. I was programmed by /u/mscroggs. [How I work](http://mscroggs.co.uk/blog/20)."

def joiner():

return "\n\n- - - -\n\n"

For each sub OEISbot is monitoring, the hottest 10 posts are searched through for mentions of sequences. If a mention is found, a reply is generated and posted.

for sub in subs:

subreddit = r.get_subreddit(sub)

for submission in subreddit.get_hot(limit = 10):

try:

seen[submission.id]

except KeyError:

seen[submission.id] = []

re_s = re.findall("A([0-9]{6})",submission.title)

re_s += re.findall("oeis\.org/A([0-9]{6})",submission.url)

post_me = []

for seq_n in re_s:

if seq_n not in seen[submission.id]:

post_me.append(markup(seq_n))

seen[submission.id].append(seq_n)

if len(post_me)>0:

post_me.append(me())

submission.add_comment(joiner().join(post_me))

break

flat_comments = praw.helpers.flatten_tree(submission.comments)

for comment in flat_comments:

if not isinstance(comment,MoreComments) and comment.author is not None and comment.author.name != "OEISbot":

re_s = re.findall("A([0-9]{6})",comment.body)

post_me = []

for seq_n in re_s:

if seq_n not in seen[submission.id]:

post_me.append(markup(seq_n))

seen[submission.id].append(seq_n)

if len(post_me)>0:

post_me.append(me())

comment.reply(joiner().join(post_me))

break

else:

continue

break

else:

continue

break

subreddit = r.get_subreddit(sub)

for submission in subreddit.get_hot(limit = 10):

try:

seen[submission.id]

except KeyError:

seen[submission.id] = []

re_s = re.findall("A([0-9]{6})",submission.title)

re_s += re.findall("oeis\.org/A([0-9]{6})",submission.url)

post_me = []

for seq_n in re_s:

if seq_n not in seen[submission.id]:

post_me.append(markup(seq_n))

seen[submission.id].append(seq_n)

if len(post_me)>0:

post_me.append(me())

submission.add_comment(joiner().join(post_me))

break

flat_comments = praw.helpers.flatten_tree(submission.comments)

for comment in flat_comments:

if not isinstance(comment,MoreComments) and comment.author is not None and comment.author.name != "OEISbot":

re_s = re.findall("A([0-9]{6})",comment.body)

post_me = []

for seq_n in re_s:

if seq_n not in seen[submission.id]:

post_me.append(markup(seq_n))

seen[submission.id].append(seq_n)

if len(post_me)>0:

post_me.append(me())

comment.reply(joiner().join(post_me))

break

else:

continue

break

else:

continue

break

The list of sequences which have been posted in each thread is saved to prevent duplication later.

with open("/home/pi/OEIS/seen","w") as f:

json.dump(seen,f)

json.dump(seen,f)

### Running the Code

I put this script on a Raspberry Pi which runs it every 10 minutes (to prevent OEISbot from getting refusals for posting too often). This is achieved with a cron job.

*/10 * * * * python /path/to/bot.py

### Making Your Own Bot

The full OEISbot code is available on GitHub. Feel free to use it as a starting point to make your own bot! If your bot is successful, let me know about it in the comments below or on Twitter.

### Similar Posts

Logical Contradictions | Logic Bot, pt. 2 | Logic Bot | Raspberry Pi Weather Station |

### Comments

Comments in green were written by me. Comments in blue were not written by me.

**Add a Comment**

**2015-08-27 09:49:10**

## MENACE

### Machine Educable Noughts And Crosses Engine

In 1961, Donald Michie build MENACE (Machine Educable Noughts And Crosses Engine), a machine capable of learning to be a better player of Noughts and Crosses (or Tic-Tac-Toe if you're American). As computers were less widely available at the time, MENACE was built from from 304 matchboxes.

To save you from the long task of building a copy of MENACE, I have written a JavaScript version of MENACE, which you can play against here.

### How To Play Against MENACE

To reduce the number of matchboxes required to build it, MENACE aways plays first. Each possible game position which MENACE could face is drawn on a matchbox. A range of coloured beads are placed in each box. Each colour corresponds to a possible move which MENACE could make from that position.

To make a move using MENACE, the box with the current board position must be found. The operator then shakes the box and opens it. MENACE plays in the position corresponding to the colour of the bead at the front of the box.

For example, in this game, the first matchbox is opened to reveal a red bead at its front. This means that MENACE (O) plays in the corner. The human player (X) then plays in the centre. To make its next move, MENACE's operator finds the matchbox with the current position on, then opens it. This time it gives a blue bead which means MENACE plays in the bottom middle.

The human player then plays bottom right. Again MENACE's operator finds the box for the current position, it gives an orange bead and MENACE plays in the left middle. Finally the human player wins by playing top right.

MENACE has been beaten, but all is not lost. MENACE can now learn from its mistakes to stop the happening again.

### How MENACE Learns

MENACE lost the game above, so the beads that were chosen are removed from the boxes. This means that MENACE will be less likely to pick the same colours again and has learned. If MENACE had won, three beads of the chosen colour would have been added to each box, encouraging MENACE to do the same again. If a game is a draw, one bead is added to each box.

Initially, MENACE begins with four beads of each colour in the first move box, three in the third move boxes, two in the fifth move boxes and one in the final move boxes. Removing one bead from each box on losing means that later moves are more heavily discouraged. This helps MENACE learn more quickly, as the later moves are more likely to have led to the loss.

After a few games have been played, it is possible that some boxes may end up empty. If one of these boxes is to be used, then MENACE resigns. When playing against skilled players, it is possible that the first move box runs out of beads. In this case, MENACE should be reset with more beads in the earlier boxes to give it more time to learn before it starts resigning.

### How MENACE Performs

In Donald Michie's original tournament against MENACE, which lasted 220 games and 16 hours, MENACE drew consistently after 20 games.

After a while, Michie tried playing some more unusual games. For a while he was able to defeat MENACE, but MENACE quickly learnt to stop losing. You can read more about the original MENACE in

*A Matchbox Game Learning-Machine*by Martin Gardner [1] and*Trial and Error*by Donald Michie [2].You may like to experiment with different tactics against MENACE yourself.

### Play Against MENACE

I have written a JavaScript implemenation of MENACE for you to play against. The source code for this implementation is available on GitHub.

When playing this version of MENACE, the contents of the matchboxes are shown on the right hand side of the page. The numbers shown on the boxes show how many beads corresponding to that move remain in the box. The red numbers show which beads have been picked in the current game.

The initial numbers of beads in the boxes and the incentives can be adjusted by clicking

*Adjust MENACE's settings*above the matchboxes. My version of MENACE starts with more beads in each box than the original MENACE to prevent the early boxes from running out of beads, causing MENACE to resign.Additionally, next to the board, you can set MENACE to play against random, or a player 2 version of MENACE.

Edit: After hearing me do a lightning talk about MENACE at CCC, Oliver Child built a copy of MENACE. Here are some pictures he sent me:

Edit: Oliver has written about MENACE and the version he built in issue 03 of Chalkdust Magazine.

Edit: Inspired by Oliver, I have built my own MENACE. I took it to the MathsJam Conference 2016. It looks like this:

#### References

### Similar Posts

The Mathematical Games of Martin Gardner | Making Names in Life | Video Game Surfaces | Logical Contradictions |

### Comments

Comments in green were written by me. Comments in blue were not written by me.

**2016-12-07**

Matthew

**2016-12-07**

Steve Paget

**2016-12-07**

Steve Paget

**2015-12-14**

Matthew

**2015-12-05**

Joe

**Add a Comment**

**2015-03-15 15:14:29**

## Logic Bot, pt. 2

A few months ago, I set
@mathslogicbot going on the
long task of tweeting all the tautologies (containing 140 characters or less)
in propositional calculus with the symbols \(\neg\) (not), \(\rightarrow\)
(implies), \(\leftrightarrow\) (if and only if), \(\wedge\) (and) and \(\vee\)
(or). My first post on logic bot contains a full
explanation of propositional calculus, formulae and tautologies.

### An Alternative Method

Since writing the original post, I have written an alternative script to
generate all the tautologies.
In this new method, I run through all possible strings of length 1 made
with character in the logical language, then strings of length 2, 3 and so on.
The script then checks if they are valid formulae and, if so, if they are
tautologies.

In the new script, only formulae where the first appearances of variables
are in alphabetical order are considered. This means that duplicate tautologies
are removed. For example, \((b\rightarrow(b\wedge a))\) will not be counted as
it is the same as \((a\rightarrow(a\wedge b))\).

You can view or download this alternative code on
github.
All the terms of the sequence that I have calculated so far can be viewed
here and the tautologies for these terms are
here.

### Sequence

One advantage of this method is that it generates the tautologies sorted by
the number of symbols they contain, meaning we can generate the sequence whose
\(n\)

^{th}term is the number of tautologies of length \(n\).The first ten terms of this sequence are

$$0, 0, 0, 0, 2, 2, 12, 6, 57, 88$$
as there are no tautologies of length less than 5; and, for example two
tautologies of length 6 (\((\neg a\vee a)\) and \((a\vee \neg a)\)).

This sequence is listed as
A256120 on OEIS.

#### Properties

There are a few properties of this sequence that can easily be shown.
Throughout this section I will use \(a_n\) to represent the \(n\)

^{th}term of the sequence.Firstly, \(a_{n+2}\geq a_n\). This can be explained as follows: let \(A\)
be a tautology of length \(n\). \(\neg\neg A\) will be of length \(n+2\) and
is logically equivalent to \(A\).

Another property is \(a_{n+4}\geq 2a_n\): given a tautology \(A\) of length
\(n\), both \((a\vee A)\) and \((A\vee a)\) will be tautologies of length
\(n+4\). Similar properties could be shown for \(\rightarrow\),
\(\leftrightarrow\) and \(\wedge\).

Given properties like this, one might predict that the sequence will be
increasing (\(a_{n+1}\geq a_n\)). However this is not true as \(a_7\) is 12
and \(a_8\) is only 6. It would be interesting to know at how many points in
the sequence there is a term that is less than the previous one. Given the
properties above it is reasonable to conjecture that this is the only one.

Edit: The sequence has been published on OEIS!

### Similar Posts

Logical Contradictions | Logic Bot | How OEISbot Works | Raspberry Pi Weather Station |

### Comments

Comments in green were written by me. Comments in blue were not written by me.

**Add a Comment**

Add a Comment