Home

The Flatland Paradox

This post contains some simple code for simulating the Flatland Paradox in R. This is not meant to be optimal code or a perfect solution, it's just a quick look at a fun problem.

You can read about the paradox and its solution here. As it's described on the linked site, the paradox is essentially that the path that shortens the length of the string is most likely to reveal the treasure. When I first read about it, it took me a while to understand the problem, so I wrote up a little simulation to get my head around it. This post has the code to the simulation I wrote.

The code is pretty short and pretty annotated, so I'll let it speak for itself:

#flatland simulation
longer<-NULL
j<-1
#go through 500 trials of the paradox, enough to get a good sense of what happens
while(j<=500){
#N is the length of the "trip"
N<-sample(5:30,1)
#vect will record the steps of the trip
vect<-NULL
k<-1
while(k<=N){
#here, 1 through 4 represent the directions (N,S,E,W), that one might travel
toadd<-sample(1:4,1)
vect<-c(vect,toadd)
#if you're past the first step, check whether the last two steps cancel with each other
#here, we check cancellation by checking summation to 5 (isomorphic to backtracking)
if(length(vect)>1){
if((vect[length(vect)]+vect[length(vect)-1])==5){
#if the last two steps cancel, remove the last two steps taken on the trip
vect<-vect[-length(vect)]
vect<-vect[-length(vect)]
}
}
if(k==(N-1)){
#store "vect no x", the vector before the last step is taken
vectnox<-vect
}
k<-k+1
}#end inside while
#"longer" records whether the trip is shorter or longer after the last step
#longer also tells us whether backtracking helped (1 means it did)
longer<-c(longer,length(vect)-length(vectnox))
j<-j+1
}#end outside while
#the mean will be around .5, meaning that backtracking helps about 3/4 of the time.
mean(longer)

This simulation gives us the counter-intuitive answer: that backtracking is indeed the best strategy for locating the treasure.