Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The famous countdown game loved among mathematicians and people adoring numbers and why not find a way to check for solutions.

So the game is (was) known as a TV show where then host would give a random 3-digit number and the contestants would draw 6 random numbers from stack of numbers. Given the time limit, the winner was the one who would create a formula matching the result or being closest.

Many ways, tips, tricks and optimisations were already considered, maybe the most famous was the Reverse Polish notation where operators follow their operands and is a great fit for the game.

With useless functionality, I have decided to use permuteGeneral function from RcppAlgos or same functionality could be achieved with combn function.

library(RcppAlgos)

countDown_puzzle <- function(six, res_num) {
oper <- c("+","-","/","*")
res <- 0
d2 <- permuteGeneral(six)
for (i in 1:nrow(d2)){
for (o in 1:1000){

r <- paste0(as.integer(d2[i,1]),' ',as.character(sample(oper,1)),' (',as.integer(d2[i,2]),' ',as.character(sample(oper,1)),' ((', as.integer(d2[i,3]),' ',as.character(sample(oper,1)),as.integer(d2[i,4]),') ',as.character(sample(oper,1)),
as.integer(d2[i,5]),')',as.character(sample(oper,1)),as.integer(d2[i,6]), ') ', sep ="")
res <- eval(parse(text=r))
if(res == res_num){
print(paste0("Solution: ", r, ' with result of: ', res, ' for given vector: ', paste(six, collapse = " "), sep=""));
}
}
}
}


And simply run the function:

countDown_puzzle(c(100,9,4,1,7,25), 463)


If you want to generate also the numbers and a random solution:

set.seed(2908)
number_pool <- c(1:11, 25, 50, 75, 100, 200)
six <- sample(number_pool, 6, replace=FALSE)
res_num <- sample(100:999,1)

# run function
countDown_puzzle(six, res_num)


There are many immediate optimisations to this game, such as:
– there is no need to multiply or divide by 1
– intermediate solutions become non-integer
– intermediate solution become negative number
– redundant calculations as: x+y = x, respectively for subtractions.
– and many more.

Non of there were taken into consideration, but it could be a great start for optimisation.

As always, code is available at Github.

Happy R-coding!