## To invoke just source the file and do
## puzzle<-gensudoku(entropy=30)
## entropy determines the complexity/difficulty of the puzzle

gensudoku<-function(entropy=10)
{
	latingrid<-function()
	{ #inner function
		P<-sample(1:9)
			R<-sample(1:9)
			M<-matrix(0,9,9)
			for (coll in 1:9)
			{
				for(roww in 1:9)
				{
					M[roww,coll] <- P[ ((roww+R[coll]) %% 9)+1]

				}

			}
		return(M)
	}

	foo.goo<-list(flag=F)
		while (!foo.goo$flag)
		{
			oMat<-latingrid()
			foo.goo<-foogoo(oMat,entropy)
		#	flag<-foo.goo$flag	
		}
	cat("\n Good Luck with Puzzle #",trunc(runif(1)*1e6),"\n")
	cat("-------------------------------------------------------------------\n")
	print(foo.goo$puzzleMat)
	cat("-------------------------------------------------------------------\n")
	return(foo.goo$puzzleMat)
}



foogoo<-function(oMat,entropy)
{

	for (x in 1:9) # try 1 to 9
	{
		for (y in 1:9) # try 1 to 9
		{ sub.y<-1+3*floor((y-1)/3) # find the submatrix 3x3 block for the current matrix
	  	sub.x<-1+3*floor((x-1)/3)
		submat<-(oMat[seq(sub.x,sub.x+2),seq(sub.y,sub.y+2)])
		l.submat<-length(which(submat==oMat[x,y]))
		if ( any(oMat[x,-y]==oMat[x,y]) | any(oMat[-x,y]==oMat[x,y]) | l.submat>1 )  { # if not a valid grid
					return(list(flag=FALSE))	}

		}

	}
	solMat<-oMat
	puzzleMat<-oMat	
	# so we have a consistent grid let us throw some points away
	# this can help control the complexity
	howmany.pt<- trunc(30+runif(1)*entropy);howmany.pt<-min(howmany.pt,50)
	puzzleMat[-(trunc(runif(howmany.pt)*81))]<-0
	#print(solMat)
	
 	return(list(flag=TRUE,puzzleMat=puzzleMat))


}

