Puzzle: A path through pairs making squares

April 23, 2012
By

(This article was first published on Revolutions, and kindly contributed to R-bloggers)

Ted Harding posed an interesting puzzle challenge on the r-help mailing list recently. Here's the puzzle:

Take the numbers 1, 2, 3, etc. up to 17.

Can you write out all seventeen numbers in a line so that every pair of numbers that are next to each other, adds up to give a square number?

You can figure out the solution from first principles fairly easily (hint: what neighbours must 17 have?), but Ted's challenge was to write a "neat" R function to solve this puzzle programmatically. The r-help thread generated several solutions (including an elegant one based on recursion, and a generalization to larger sets of numbers), but I wanted to highlight this solution from Vincent Zoonekynd on StackOverflow:

# Allowable pairs form a graph
p <- outer(
1:17, 1:17,
function(u,v) round(sqrt(u + v),6) == floor(sqrt(u+v)) )
)
rownames(p) <- colnames(p) <- 1:17
image(p, col=c(0,1))

# Read the solution on the plot
library(igraph)
V(g)$label <- V(g)$name
plot(g, layout=layout.fruchterman.reingold)

It's a clever use of the graph theory. Consider the numbers 1-17 as vertices in a graph, with connections between pairs defined by whether they sum to a square. The call to outer defines the T/F adjacency matrix (which the code displays as an image), and then the plot.igraph function displays the graph as an R chart:

All you need to do is to trace a path that passes through each number once, and you have your solution to the puzzle. A neat and unexpected use of the igraph package for handling graphs in R.

StackOverflow: Ordering 1:17 by perfect square pairs

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...