Skip to content

Instantly share code, notes, and snippets.

@gweissman
Created April 15, 2012 01:13
Show Gist options
  • Save gweissman/2389140 to your computer and use it in GitHub Desktop.
Save gweissman/2389140 to your computer and use it in GitHub Desktop.
Alternative approach to 4-digit brain teaser...
# alternative approach to teaser game
library(gtools)
library(lattice)
# get data set
load(url('http://www.babelgraph.org/data/brain_teaser_data.Rdata'))
ls()
# set operators
ops <- c('+','-','*','/')
# get all possible operator combinations 4^3=64
combos <- permutations(n=4,r=3,v=ops,repeats.allowed=TRUE)
# define function to calculate error from operator combos
CalcError <- function (op) {
# generate model from operators and apply to each data set
rr <- apply(series, 1, function(x) {
mycode <- paste('abs(',x[1],op[1],x[2],op[2],x[3],op[3],x[4],')-',x[5])
eval(parse(text=mycode))
})
return (sum(abs(unlist(rr))))
}
# check validity of each model
model.error <- apply(combos,1,CalcError)
# review results
results <- data.frame( model=as.character(apply(combos,1,
function(x) paste(x[1],x[2],x[3],sep=''))),
error = model.error)
summary(results)
densityplot(~error,results)
dotplot(model~error,results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment