如何解决Sudoku算法并将Python正确翻译为Typescript / Javascript
我正在构建一个以Angular为前端的小型Sudoku Web应用程序。我已经将游戏核心逻辑外包给了一个类,如果使用以3为基础的9x9板,则该类当前无法提供正确的解决方案。当然,每个3x3单元只包含1-9的数字,但是行和列不能正确求解。该代码是我复制和修改的Python算法的翻译,尽管Python文件可以正常工作(以及其他基础),但将其转换为JS / TS却不那么容易,因为由于随机性很难解决数字。这与TS / JS问题一样是Python问题,因为问题的根源可能是我对Python的了解中最薄弱的一环-使用for循环创建数组,尤其是使用多个数组时。以下是有效的原始Python代码。它在网格中设置行和列(编辑:我试图通过使用非随机数来隔离问题,并且确认行下方那些字符的Typescript等效代码被确认是错误的,很可能是整个问题的根源。我应该如何解决呢?):
rows = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ]
cols = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
下面是我编写的Typescript代码。为了避免代码重复,我将算法外包给一个方法。 “ rc”用上面的代码代替r和c(rBase的范围是从0到base,在这种情况下为3):
private setItems(inputArray: number[]): void {
const shuffledArray = this.shuffle([...this.rBase]);
for(let i = 0; i < shuffledArray.length; i++) {
const rc = shuffledArray[i];
const secondShuffledArray = this.shuffle([...this.rBase]);
const g = secondShuffledArray[i];
inputArray[i] = this.base*g + rc;
}
}
我认为还有另一种方法可能是故障的根源,即从行和列生成木板的那条线。但是,在此之前,似乎行和列已经存在错误:
# produce board using randomized baseline pattern
board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
“ nums”是从1到base ^ 2 + 1(以3为1-9的基数)的混排范围。 TS:
for(let i = 0; i < rows.length; i++) {
const r = rows[i];
this.board[i] = range(0,this.side);
for(let j = 0; j < cols.length; j++) {
const c = cols[j];
this.board[i][j] = this.nums[this.pattern(r,c)];
}
}
}
各个文件也都在下面。模式方法中的操作顺序似乎相互匹配,已经测试了这两种方法。预先感谢您提供任何答案。
Python:
print("Welcome to Sudoku!");
base = ""
while type(base) is not int or base < 3 or base > 16:
try:
base = int(input("Please choose a base size 3-16 (ex 3 equals 9x9 board): "))
if base < 3 or base > 16:
raise TypeError("Only integers more than 3 or less than 16")
except:
print("Sorry,please try again!")
side = base*base
# pattern for a baseline valid solution
def pattern(r,c): return (base*(r%base)+r//base+c)%side
# randomize rows,columns and numbers (of valid base pattern)
from random import sample
def shuffle(s): return sample(s,len(s))
rBase = range(base)
rows = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ]
cols = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
nums = shuffle(range(1,base*base+1))
# produce board using randomized baseline pattern
board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
# squares = side*side
# empties = squares * 3//6
# for p in sample(range(squares),empties):
# board[p//side][p%side] = 0
numSize = len(str(side))
def expandLine(line):
return line[0]+line[5:9].join([line[1:5]*(base-1)]*base)+line[9:13]
line0 = expandLine("╔═══╤═══╦═══╗")
line1 = expandLine("║ . │ . ║ . ║")
line2 = expandLine("╟───┼───╫───╢")
line3 = expandLine("╠═══╪═══╬═══╣")
line4 = expandLine("╚═══╧═══╩═══╝")
symbol = " 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nums = [ [""]+[symbol[n] for n in row] for row in board ]
print(line0)
for r in range(1,side+1):
print( "".join(n+s for n,s in zip(nums[r-1],line1.split("."))) )
print([line2,line3,line4][(r%side==0)+(r%base==0)])
TS:
import {range} from 'lodash';
export class Game {
private side: number;
private nums: number[];
private solution: number[][];
private rBase: number[];
public board: number[][] = [];
constructor(private base: number = 3){
this.side = this.base*this.base;
this.nums = this.shuffle(range(1,this.base*this.base+1));
this.rBase = range(0,this.base);
const rows: number[] = range(0,this.side);
const cols: number[] = range(0,this.side);
this.setItems(rows);
this.setItems(cols);
for(let i = 0; i < rows.length; i++) {
const r = rows[i];
this.board[i] = range(0,this.side);
for(let j = 0; j < cols.length; j++) {
const c = cols[j];
this.board[i][j] = this.nums[this.pattern(r,c)];
}
}
console.log(this.board);
//const squares: number = this.side^2;
//const empties: number = Math.floor((squares * 3)/6);
}
private pattern = ( r: number,c: number) => {
return (this.base*(r%this.base)+Math.floor(r/this.base+c)) %this.side;
}
private shuffle = (inputArray: number[]): number[] => {
for(let i = inputArray.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * i);
const temp = inputArray[i]
inputArray[i] = inputArray[j]
inputArray[j] = temp
}
return inputArray;
}
private setItems(inputArray: number[]): void {
const shuffledArray = this.shuffle([...this.rBase]);
for(let i = 0; i < shuffledArray.length; i++) {
const rc = shuffledArray[i];
const secondShuffledArray = this.shuffle([...this.rBase]);
const g = secondShuffledArray[i];
inputArray[i] = this.base*g + rc;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。