During the holiday Mickey and I have been watching a program called brainbox challenge on the BBC. Neither of us can keep up with any of the competitors, although Mickey sometimes beats them to it on the memory games. One of the games is called code 9. The rules are (fairly) simple. The competitors are given a mathematical operation to perform on two numbers. However each digit of the numbers has first to be coded by subtracting it from 9. Thus 1 becomes 8; 12, becomes 87 etc. After completing the operation the competitors have to apply the code again to the answer. So 1 +1 becomes 8+8=16, which is then recoded to give the answer 83. As I just can’t get my brain to do it unaided I thought of writing a function in R to help.

This line carries out the operation on whole positive numbers.

code9<-function(x)as.numeric(paste(unlist(lapply(strsplit(as.character(x),””),

function(x)9-as.numeric(x))),collapse=””))

so

code9(code9(10)+code9(10))

[1] 821

This works as a one liner, but there should be a better way requiring fewer steps within the function using a regular expression.

### Like this:

Like Loading...