Archive for ifelse

multiplying the bars

Posted in Kids, R with tags , , , , , , , on February 25, 2020 by xi'an

The latest Riddler makes the remark that the expression

|-1|-2|-3|

has no unique meaning (and hence value) since it could be

| -1x|-2|-3 | = 5   or   |-1| – 2x|-3| = -5

depending on the position of the multiplication sign and asks for all the possible values of

|-1|-2|…|-9|

which can be explored by a recursive R function for computing |-i|-(i+1)|…|-(i+2j)|

vol<-function(i,j){x=i
  if(j){x=c(i-(i+1)*vol(i+2,j-1),abs(i*vol(i+1,j-1)+i+2*j))
  if(j>1){for(k in 1:(j-2))
        x=c(x,vol(i,k)-(i+2*k+1)*vol(i+2*k+2,j-k-1))}}
  return(x)}

producing 40 different values for the ill-defined expression. However, this is incorrect as the product(s) hidden in the expression only involve a single term in vol(i,j)… I had another try with the decomposition of the expression vol(i,j) into a first part and a second part

prod<-function(a,b) a*b[,1]+b[,2]

val<-function(i,j){
  x=matrix(c(i,0),ncol=2)
  if(j){x=rbind(cbind(i,prod(-(i+1),val(i+2,j-1))),
          cbind(abs(prod(-i,val(i+1,j-1))-i-2*j),0))
    if(j-1){for(k in 2:(j-1)){
      pon=val(i,k-1)
      for(m in 1:dim(pon)[1])
          x=rbind(x,cbind(pon[m,1],pon[m,2]+prod(-(i+2*k-1),val(i+2*k,j-k))))}}}
  return(x)}

but it still fails to produce the right version.

Le Monde puzzle [#1132]

Posted in Kids, R, Statistics with tags , , , , , on February 24, 2020 by xi'an

A vaguely arithmetic challenge as Le weekly Monde current mathematical puzzle:

Given two boxes containing x and 2N+1-x balls respectively. If one proceeds by repeatedly transferring half the balls from the even box to the odd box, what is the largest value of N for which the resulting sequence in one of the boxes covers all integers from 1 to 2N?

The run of a brute force R search return 2 as the solution

lm<-function(N)
fils=rep(0,2*N)
bol=c(1,2*N)
while(max(fils)<2){
    fils[bol[1]]=fils[bol[1]]+1
    bol=bol+ifelse(rep(!bol[1]%%2,2),-bol[1],bol[2])*c(1,-1)/2}
return(min(fils))}

with obvious arguments that once the sequence starts cycling all possible numbers have been visited:

> lm(2)
[1] 1
> lm(3)
[1] 0

While I cannot guess the pattern, there seems to be much larger cases when lm(N) is equal to one, as for instance 173, 174, 173, 473, 774 (and plenty in-between).