// import visualization libraries {const{ Tracer, Array2DTracer, Array1DTracer, LogTracer, Randomize, Layout, VerticalLayout }=require('algorithm-visualizer');// }functionfilledArray(length, value){returnArray(...Array(length)).map(Number.prototype.valueOf, value);}constN=5;//配置幻方大小const board =(functioncreateArray(N){const result =[];for(let i =0; i <N; i++){
result[i]=filledArray(N,0);}return result;}(N));// define tracer variables {const boardTracer =newArray2DTracer('幻方');const logger =newLogTracer('算法过程');
Layout.setRoot(newVerticalLayout([boardTracer, logger]));
boardTracer.set(board);
logger.println(`${N}阶幻方`);
Tracer.delay();// }// logger {
logger.println('开始执行');// }let x =0, y =(N-1)/2for(let i =1; i <=N*N; i ++){
board[x][y]= i;// logger {
logger.println(`在${x}行${y}列填入${i}`);// }// visualizer {
boardTracer.patch(x, y, i);
Tracer.delay();// }if(x ===0&& y !=N-1) x =N-1, y +=1;elseif(y ==N-1&& x !==0) x -=1, y =0;elseif(x ===0&& y ==N-1) x +=1;elseif(board[x -1][y +1]!==0) x +=1;else x -=1, y +=1;}// logger {
logger.println(`完成`);// }