print(`This is a supplementary package (written by Pablo Blanco) for RectTile.txt. Please read RectTile.txt.`): print(`https://sites.math.rutgers.edu/~zeilberg/tokhniot/Recto.txt`): print(``): print(`It is one of two Maple packages accompanying the article`): print(`Rectangling A Rectangle, by Pablo Blanco, Robert Dougherty-Bliss, Natalya Ter-Saakov, and Doron Zeilberger, available from`): print(`https://sites.math.rutgers.edu/~zeilberg/mamarim/mamarimhtml/recto.html`): print(`First written: April 6, 2026.`): print(`This version: May 24, 2026.`): read `RectTile.txt`: with(combinat): Help:=proc(): if args=NULL then: print(`The procedures are:`): print(`checkTiling, isInRect, MakeGoodPuzzle, MakePuzzle, PlotPuz, RandIntPuz, RandRTFew, RectOrd, RectoSolver, TryAllTiles`): elif nargs=1 and args[1]=MakeGoodPuzzle then: print(`MakeGoodPuzzle(T,K): given a board T, keeps trying, up to K times, to make a puzzle with a unique solution. If it failes it returns FAIL.`): print(`It returns [SOL,PUZ].`): print(`Try MakeGoodPuzzle([7$7],10);`): elif nargs=1 and args[1]=RectoSolver then: print(`RectoSolver(L,PUZ): Given a tiling configuration and recto puzzle PUZ, outputs SOME solution to the puzzle. If there is no solution, outputs FAIL`): print(`Try:`): print(`L:=[5$5]:`): print(`P:=MakePuzzle(L):`): print(`SOL:=P[1]; PUZ:=P[2];`): print(`T:=RectoSolver(L,PUZ);`): print(`WARNING: for boards larger than 5 by 5 it is EXTREMELY SLOW, use procedure SOLVE instead in the parent package RectTile.txt`): print(`For one of the New York Times puzzles try`): print(` PUZ:={[[1, 3], 5], [[2, 5], 5], [[3, 3], 4], [[4, 4], 6], [[5, 3], 5], [[6, 4], 7]};`): print(`RectoSolver([6$6],PUZ);`): print(`For the April 26, 2026 New York Times puzzles try`): print(`PUZ:= {[1,2],4], [[1,6],5], [[2,1],3], [[2,7],6], [[3,3],4], [[3,5],5], [[4,4],4], [[5,3],5], [[5,5],3], [[6,1],6], [[6,7],4], [[7,2],7] ,[[7,6],5]]);`): print(`RectoSolver([7$7],PUZ);`): print(`Alternatively, try:`): print(`T:=RectoSolver(L,PUZ,true);`): print(`to output ALL solutions to the puzzle.`): elif nargs=1 and args[1]=PlotPuz then: print(`PlotPuz(a,b,PUZ,SOL). Plots a recto puzzle PUZ inside the grid [a]x[b]. Optionally, also plots a potential solution to the puzzle, SOL.`): print(`Try:`): print(`P:=MakePuzzle([4$6]);`): print(`SOL:=P[1]: PUZ:=P[2]:`): print(`PlotPuz(6,4,PUZ);`): print(`PlotPuz(6,4,PUZ,SOL);`): elif nargs=1 and args[1]=checkTiling then: print(`checkTiling(SOL,PUZ): given a recto puzzle PUZ and a potential solution SOL, returns true when SOL is a solution and false otherwise.`): print(`Note: the procedure does not actually check if the given tiles COVER the tiling configuration (total area check).`): print(`Try:`): print(`checkTiling(op(MakePuzzle([6$6])));`): elif nargs=1 and args[1]=TryAllTiles then: print(`TryAllTiles(T,PUZ): Given a configuration T and a recto puzzle PUZ, checks all rectangular tilings of T to solve the puzzle.`): print(`Try:`): print(`P:=MakePuzzle([3$3]);`): print(`SOL:=P[1]: PUZ:=P[2]:`): print(`FOUND:=TryAllTiles([3$3],PUZ);`): print(`evalb(FOUND=SOL);`): elif nargs=1 and args[1]=MakePuzzle then: print(`MakePuzzle(T,R): Given a configuration T and an (optional) set of rectangular tiles R. MakePuzzle(T,R) returns the coordinates for the numbers in a Recto puzzle. The output is [SOl,PUZ], where the first coordinate is the solution and the second coordinate is the puzzle. Try:`): print(`MakePuzzle([3$4]);`): elif nargs=1 and args[1]=RandIntPuz then: print(`RandIntPuz(T): Given a tiling configuration T, tries to randomly generate an interesting Recto puzzle. Try: `): print(`MakeIntPuz([4$3]);`): elif nargs=1 and args[1]=RandRTFew then: print(`RandRTFew(T,k): Given a tiling configuration T, tries to randomly generate a set of at most k tiles to tile T. If it fails, the procedure prints FAIL and returns the last attempt. Try:`): print(`S:=RandRTFew([5$5],10);`): print(`PlotT(5,5,S);`): fi: end: PlotPuz:=proc(a,b,PUZ, SOL:={}) local s,i,j,so,y,x,v,p,pt,rec,Pt: p:=plot([[0,0],[b,0],[b,a],[0,a],[0,0]],thickness=2,axes=none,scaling=constrained): for i from 1 to a-1 do p:=p,plot([[0,i],[b,i]]): od: for j from 1 to b-1 do p:=p,plot([[j,0],[j,a]]): od: if SOL<>{} then: for s in SOL do pt:=s[1]: rec:=s[2]: Pt:=[pt[2],a-pt[1]+1]: p:=p,plot([Pt,Pt-[rec[2],0],Pt-[rec[2],rec[1]], Pt-[0,rec[1]],Pt], thickness=5): od: fi: #print(p): display({p,plots[textplot]({seq([so[1][2]-0.5,a-(so[1][1]-0.5),convert(so[2],string)],so in PUZ)},'font'=["times", "roman", 40])}): end: # given a recto puzzle PUZ and a configuration T, outputs a solution to the puzzle. TryAllTiles:=proc(L,PUZ) local allT,t: if nops(L) >=5 and L[-1]>=5 then: print(`WARNING: this procedure may not terminate quickly with such a "large" input.`): fi: allT:=TIrP(L): for t in allT do: if checkTiling(t,PUZ) then: return(t): fi: od: return(FAIL): # no such tiling found end: # given a configuration L and a tiling t of that configuration, checks if the tiling solves the recto puzzle PUZ checkTiling:=proc(t,PUZ) local k1,k2,i,S1,S2,numSources,s,r: k1:=nops(t): k2:=nops(PUZ): # check that the number of tiles and the number of sources is the same if k1<>k2 then: #print(`Number of tiles do not match.`,k1,k2): return(false): fi: S1:={seq(t[i][2][1]+t[i][2][2] ,i=1..k1)}: # set of tiles' sum of dimensions S2:={seq(PUZ[i][2],i=1..k1)}: # set of prescribed dimension sizes if S1<>S2 then: return(false): fi: # check that the tile sizes match up # check that every rectangle contains EXACTLY one source AND its dimensions match. for r in t do: numSources:=0: for s in PUZ do: if isInRect(s[1],r) then: numSources++: # check that the dimensions match the prescription if r[2][1]+r[2][2] <> s[2] then: return(false): fi: fi: if numSources>1 then: #print(`Too many sources:`,r): return(false): fi: od: if numSources < 1 then: #print(`Too few sources:`,r): return(false): fi: od: return(true): end: # returns true, if the coordinate L:=[i,j] is in rectangle R isInRect:=proc(L,R) local Co,i,j: i:=L[1]: j:=L[2]: Co:=Corners1(R): if i>=Co[3][1]+1 and i<=Co[1][1] and j>=Co[1][2]+1 and j<=Co[3][2] then: return(true): fi: return(false): end: # Given a tiling configuration L and a set of tiles T, returns true if T is a tiling of L. isTiling:=proc(L,T) local Larea,n,t,i,j,Co1,Co2,l1,r1,l2,r2: n:=nops(T): # the number of tiles # check for pairwise intersection # note: I borrowed some ideas online to write this, to avoid extra casework. for i from 1 to n do: Co1:=Corners1(T[i]): l1:=Co1[4]: r1:=Co1[2]: #print(`first corners:`,l1,r1): for j from i+1 to n do: Co2:=Corners1(T[j]): l2:=Co2[4]: r2:=Co2[2]: #print(`second corners:`,l2,r2): # checks if one rectangle is next the other if l1[2] >= r2[2] or l2[2] >= r1[2] then: next: fi: # checks if one rectangle is above to the other if r1[1] <= l2[1] or r2[1] <= l1[1] then: next: fi: return(false): # if neither case is true, the rectangles overlap od: od: true: end: # PUZ is a a set where PUZ[i]=[[i,j], val] # i,j are the coordinates of the "source" vertex in matrix notation and val is the "value" of the source # L is the tiling configuration RectoSolver:=proc(L,PUZ,all:=false) local s,S,n,i,pr,A,cArea,Tarea,prevIt,currIt,sI,j,t,Tiles,solns: n:=nops(PUZ): # there are n sources. S:=[seq(RectOrd(s, L) ,s in PUZ)]; # a list of the current rectangles associated with each source A:=[(-1)$n]: # how many rectangles are available for each source for i from 1 to n do: A[i]:= S[i]:-reset(): od: solns:={}: # the set of all solutions. If all=true, we will return this instead. # cartesian product we are iterating over pr:=cartprod([seq({`$`(0..(A[i]-1))} ,i=1..n)]): prevIt:=pr[nextvalue](): for i from 1 to n do: S[i]:-newR(): od: cArea:=convert(L,`+`): # the area of the configuration Tiles:=()->[seq(S[i]:-peek() ,i=1..n)]: # returns the current LIST of tiles ## check if puzzle is resolved immediately: ## if isTiling(L,Tiles()) then: return({op(Tiles())}): fi: while not(pr[finished]) do: currIt:=pr[nextvalue](): sI:=isSucc(prevIt,currIt): # successor information j:=sI[3]: # this is the coordinate that increased S[j]:-newR(): # change that coordinate. # there is more to change... if not(sI[1]) then: for i in sI[2] do: S[i]:-reset(): # reset the appropriate coordinates. S[i]:-newR(): # call newR once. (the first call doesn't do anything). od: fi: Tarea:=add(t[2][1]*t[2][2],t in Tiles()): # the area of T, double-counting overlap if Tarea = cArea then: # if this condition is not met, we know the puzzle is not solved if isTiling(L,Tiles()) then: # check if the puzzle has been solved if not(all) then: return({op(Tiles())}): fi: solns:=solns union {convert(Tiles(),set)}: fi: fi: prevIt:=currIt: od: # if a solution was found, return all solutions. (assume all=true) if solns<>{} then: return(solns): fi: return(FAIL): # no solution was found... end: # given two lists L1 and L2, where L2 follows L1 in lexicographic order, return [bool, S,idx]. # bool is true or false: indicates if L2 and L1 have hamming dist = 1 # if bool is false, S is the set of indices of L2 that have "returned to zero". Otherwise, it is {}. # idx is the index of the coordinate that has increased from L1 to L2, which did NOT reset. isSucc:=proc(L1,L2) local bool,idx,i,j,ham,n,test: ham:=0: n:=nops(L1): if n<>nops(L2) then: error "inputs are different lengths": fi: test:=false: # first, compute the hamming distance for i from 1 to n do: ham+=max(L2[i]-L1[i],L1[i]-L2[i]): # this should only occur once. if L2[i] > L1[i] then: idx:=i: if test then: error "inputs were not lexicographic": fi: test:=true: fi: od: if ham > 1 then: bool:=false: # L2 is NOT a "successor" of L1. return([bool,{seq(j,j=idx+1..n)}, idx]): else: bool:=true: return([bool,{},idx]): fi: end: # generates a Recto Puzzle with the given tiling, the user may specify the tiles. Otherwise, generates the puzzle randomly. MakePuzzle:=proc(T,R:={}) local r,Q,Co,y,x,v,R1: Q:=DEQueue(): # this will contain the "sources" of the puzzle # see if the user has specified a puzzle R1:=R: if R = {} then: R1:=RandRT(T): fi: #print(R1): # for testing purposes for r in R1 do: # this code randomly chooses where the source block will be Co:=Corners1(r): y:=rand(Co[3][1]+1..Co[1][1])(): x:= rand(Co[1][2]+1..Co[3][2])(): v:=r[2][1]+r[2][2]: # sum of the rectangle's dimensions Q:-push_front([[y,x],v]): od: [R1,convert(Q,set)]: end: # Tries to make an "interesting" Recto puzzle randomly, through several attempts. RandIntPuz:=proc(T) local n,m,size,R,i,L: n:=nops(T): m:=T[-1]: L:=3*(sqrt(n*m))/4 + (min(n,m)*sqrt(max(n,m)))/4: #print(trunc(L)): R:=RandRTFew(T,trunc(L)+1): size:=nops(R): i:=1: while size < trunc(min(sqrt(n),sqrt(m))) and i<100 do: R:=RandRTFew(T,trunc(sqrt(n*m))+1): size:=nops(R): i++: od: R: # this is the puzzle's "solution" #print(R): MakePuzzle(T,R): end: # RandRTFew(T,k): RandRT but with at most k tiles. In an n x m tiling, tries to generate this 2*n*m times. RandRTFew:=proc(T,k) local n,m,R,i,size,limit: n:=nops(T): m:=T[-1]: R:=RandRT(T): size:=nops(R): i:=1: limit:=1000: # the 2*n*m limit is arbitrary, there's no reason for it. while size > k and i < limit do: R:=RandRT(T): size:=nops(R): i++: od: if i = limit then: print(FAIL): fi: # a specified tiling was not found. #print(i,size): R: end: # an object to determine the first or next rectangle containing a "source", in a particular ordering. # L:= [[y,x],value] and T is the tiling RectOrd:=proc(L,T): module(): export peek,newR,corners,firstcall,reset: local x,y,value,xshift, yshift, dimx, dimy,widthmax, heightmax,failstate,numRecs: widthmax:=max(T): # the largest width of the tiling heightmax:=nops(T): # assuming all T[i] > 0. x:=L[1][2]: y:=L[1][1]: value:=L[2]: dimx:=1: dimy:=()->value-dimx: # this is a procedure so that it doesn't need to be updated. xshift:=0: # xshift 0 means that our "source" is at the rightmost coordinate of the rectangle yshift:=0: # yshift 0 means source is at topmost coordinate of the rectangle corners:=()->Corners1([[y-yshift,x+xshift] ,[dimy(),dimx]]): firstcall:=true: failstate:=false: numRecs:=-1: # output the current rectangle, in the format [[i,j],[a,b]]. i,j are the top-right coordinates and a,b are the dimensions peek:=proc() local i,j,leftx,rightx,topy,boty,c: c:=corners(): if max(seq(c[i][1],i=1..4)) > heightmax or max(seq(c[i][2],i=1..4)) > widthmax or min(seq(c[i][2],i=1..4)) < 0 or min(seq(c[i][1],i=1..4)) < 0 then: firstcall:=false: newR(): fi: # compute the top-right coordinates of the rectangle. j:=x+xshift: i:=y-yshift: #print(xshift,yshift,dimx,dimy()): # return FAIL if all valid rectangles have been considered if failstate then: return(FAIL): fi: return([[i,j] ,[dimy(),dimx]]): end: # outputs how many valid rectangles there are, from the beginning. reset:=proc(): # reset all information dimx:=1: xshift:=0: yshift:=0: firstcall:=true: failstate:=false: # count number of rectangles if numRecs = -1 then: numRecs:=0: while newR() do: numRecs++: od: # reset all info dimx:=1: xshift:=0: yshift:=0: firstcall:=true: failstate:=false: fi: numRecs: end: # try a new legal rectangle. returns true as long as VALUE is not violated. newR:=proc() local c,i,isIterated: # refuse to do anything if all dimension combinations are exhausted. if dimy() <= 0 then: return(false): fi: c:=corners(): isIterated:=true: # these conditions try to ensure that the rectangle fits within the tiling. This code only works when the tiling is rectangular while max(seq(c[i][1],i=1..4)) > heightmax or max(seq(c[i][2],i=1..4)) > widthmax or min(seq(c[i][2],i=1..4)) < 0 or min(seq(c[i][1],i=1..4)) < 0 or isIterated and not(firstcall) do: isIterated:=false: if xshift < dimx-1 then: xshift++: c:=corners(): # if we have shifted x to its limit... elif xshift = dimx-1 then: # try shifting y now.. if yshift < dimy()-1 then: yshift++: xshift:=0: # reset the x shift. #return(true): c:=corners(): next: fi: # otherwise, start changing the dimension dimx++: xshift:=0: yshift:=0: c:=corners(): # check if dimension is still OK. if dimy() <= 0 then: failstate:=true: return(false): fi: fi: od: if firstcall then: firstcall:=false: fi: true: end: end: end: #MakeGoodPuzzle(T,K): given a board T, keeps trying, up to K times, to make a puzzle with a unique solution. If it failes it returns FAIL. #It returns [SOL,PUZ]. MakeGoodPuzzle:=proc(T,K) local P,i,gu: for i from 1 to K do P:=MakeRandPuz1(T): gu:=SOLVE(T,P[2]): if not member(P[1],gu) then print(`Something bad happened`): RETURN(FAIL): fi: if nops(gu)=1 then RETURN([gu[1],P[2]]): fi: od: FAIL: end: