# # # Written by: # -- # John L. Weatherwax 2009-04-21 # # email: wax@alum.mit.edu # # Please send comments and especially bug reports to the # above email address. # #----- # problem on epage 56 # fix the random.seed, so I'll always get the same answer: set.seed(10131985) s=matrix(0,ncol=9,nrow=9) s[1,c(6,8)] = c(6,4) s[2,c(1:3,8)] = c(2,7,9,5) s[3,c(2,4,9)] = c(5,8,2) s[4,3:4] = c(2,6) s[6,c(3,5,7:9)] = c(1,9,6,7,3) s[7,c(1,3:4,7)] = c(8,5,2,4) s[8,c(1,8:9)] = c(3,8,5) s[9,c(1,7,9)] = c(6,9,1) #Part (a): s #Part (b): pool = array(TRUE,dim=c(9,9,9)) for( ii in 1:9 ){ for( jj in 1:9 ){ if( s[ii,jj]!=0 ){ notPossible = (1:9)[-s[ii,jj]] # this selection of the 1:9 indexes is not possible at this spot pool[ii,jj,notPossible] = FALSE } } } #Part (f): while( sum(s==0)>0 ){ # generate a random a,b element a = sample(1:9,1) b = sample(1:9,1) if( s[a,b]==0 ){ # this element has not alread been filled boxa = 3*trunc((a-1)/3)+1 boxa = boxa:(boxa+2) boxb = 3*trunc((b-1)/3)+1 boxb = boxb:(boxb+2) for ( u in (1:9)[pool[a,b,]]) pool[a,b,u] = (sum(u==s[a,])+sum(u==s[,b])+sum(u==s[boxa,boxb]))==0 if( sum(pool[a,b,])==1 ) s[a,b]=(1:9)[pool[a,b,]] } }