Archive for R code

Le Monde puzzle [#8]

Posted in R, Statistics with tags , , on March 30, 2011 by xi'an

Another mathematical puzzle from Le Monde that relates to a broken calculator (skipping the useless tale):

Given a pair of arbitrary positive integers (x,y) a calculator can either substract the same integer [lesser than min(x,y)] from both x and y or multiply either x or y by 2. Is it always possible to obtain equal entries by iterating calls to this calculator?

While the solution provided in this weekend edition of Le Monde is to keep multiplying x=min(x,y) by 2 until it is larger than or equal to y=max(x,y)/2,  at which stage subtracting 2x-y leads to (y-x,2y-2x) which is one multiplication away from equality, I wrote a simple R code that blindly searches for a path to equality, using as a target function exp{x²+y²+(x-y)²}. I did not even include a simulated annealing schedule as the optimal solution is known. Here is the R code:

Continue reading

Le Monde puzzle [34]

Posted in R, Statistics, University life with tags , , , on October 4, 2010 by xi'an

Since the puzzle in this week (-end) edition of Le Monde is not (easily) solvable via an R program, I chose to go back to an older puzzle that my students can solve.

Eleven [distinguishable] token are [arbitrarily] distributed around a 200 meter perimeter-long ring. They all start moving at the same speed, 18km/h, in arbitrary directions. When two tokens hit one another they instantaneously reverse directions while keeping the same absolute speed. How long does it take for all tokens to be back in their initial positions?

The logical [non-computational] solution was given in an earlier edition: If all tokens move in the same direction, it takes 60×60/(18×5)=40 seconds to complete a turn and hence to see all tokens back to their initial positions. If they are moving into different directions, hits have no impact on the distribution of the tokens when they are not distinguished. Therefore, after 40 seconds, the repartition of the tokens is the same as at time 0, except for a permutation of the individual tokens. Given that there are 11 tokens, it takes at most 11 permutations to see all tokens back to their initial positions, i.e. 440 seconds. Here is the basic R resolution with a dynamic rendering of the moving tokens. It obviously gives 440 seconds as its output.

# warning: plotting takes much more time
for (i in (1:10))
for (j in ((i+1):11))
     if (tokens[i]==tokens[j]) speeds[c(i,j)]=-speeds[c(i,j)]
while (sum(abs(tokens-start))>0){
  for (i in (1:10))
  for (j in ((i+1):11))
     if (tokens[i]==tokens[j]) speeds[c(i,j)]=-speeds[c(i,j)]

Updated R code for Bayesian Core

Posted in Books, R, Statistics with tags , , , on February 8, 2010 by xi'an

Simply to mention a minor change made in the prog4.R code for Bayesian Core. Nothing life-threatening, mind you!, just a


term replacing a