[R] A little exercise in R!

Petr Savicky savicky at cs.cas.cz
Sat Apr 14 06:54:01 CEST 2012


On Fri, Apr 13, 2012 at 10:34:49PM +0100, Ted Harding wrote:
> Greetings all!
> A recent news item got me thinking that a problem stated
> therein could provide a teasing little exercise in R
> programming.
> 
> http://www.bbc.co.uk/news/uk-england-cambridgeshire-17680326
> 
>   Cambridge University hosts first European 'maths Olympiad'
>   for girls
> 
>   The first European girls-only "mathematical Olympiad"
>   competition is being hosted by Cambridge University.
>   [...]
>   Olympiad co-director, Dr Ceri Fiddes, said competition questions
>   encouraged "clever thinking rather than regurgitating a taught
>   syllabus".
>   [...]
>   "A lot of Olympiad questions in the competition are about
>   proving things," Dr Fiddes said.
> 
>   "If you have a puzzle, it's not good enough to give one answer.
>   You have to prove that it's the only possible answer."
>   [...]
>   "In the Olympiad it's about starting with a problem that anybody
>   could understand, then coming up with that clever idea that
>   enables you to solve it," she said.
> 
>   "For example, take the numbers one up to 17.
> 
>   "Can you write them out in a line so that every pair of numbers
>   that are next to each other, adds up to give a square number?"
> 
> Well, that's the challenge: Write (from scratch) an R program
> that solves this problem. And make it neat.

Hi.

Is recursion acceptable? Using recursion, i obtained
two solutions.

  extend <- function(x)
  {
      y <- setdiff((1:17), x)
      if (length(y) == 0) {
          cat(x, "\n")
          return
      }
      y <- y[(y + x[length(x)]) %in% (1:5)^2]
      for (z in y) {
          extend(c(x, z))
      }
  }

  for (i in 1:17) extend(i)

  16 9 7 2 14 11 5 4 12 13 3 6 10 15 1 8 17 
  17 8 1 15 10 6 3 13 12 4 5 11 14 2 7 9 16 

Petr.



More information about the R-help mailing list