Sudoku算法并将Python正确翻译为Typescript / Javascript

如何解决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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-