Java解决方案检查器问题

时间:2013-12-04 05:01:29

标签: java loops sudoku drjava

我已经错过了这项任务的截止日期,但我仍然不知道我不明白我正在为这个项目做些什么。它是数独解决方案检查器的第2部分,需要添加四个方法

public boolean checkAndPrintReport( ) {*/return true;}

应检查每个失败的行或列的所有行和打印行。其他人

public boolean isGoodRow( int yRowParam ) {return true;}
public boolean isGoodColumn( int xColParam ) {return true;}
public boolean isGoodBlock(int xBlockP, int yBlockP) {return true;} 

最后,我的checkAll()方法应该有三个嵌套循环,每个循环调用上面三次。

我不明白这部分需要什么,因为我认为我已经在这里编写了一个解决方案检查器

public int timesRowHas( int yParam, int number ) { 
    int nTimesHas = 0;
    for( int x = 0; x < 9; x++ )
        if( this.getCell(x, yParam) == number )
            nTimesHas = nTimesHas + 1;

    return( nTimesHas );
}

public int timesColHas( int xParam, int number ) {
    int nTimesHas = 0;
    for( int y = 0; y < 9; y++ )
        if( this.getCell(xParam, y) == number )
            nTimesHas = nTimesHas + 1;

    return( nTimesHas );
}

public int timesBlockHas( int xBlockParam, int yBlockParam, int number ) {
    if( xBlockParam < 0 || xBlockParam > 2 || yBlockParam < 0 || yBlockParam > 2 )
        throw new IllegalArgumentException("Bad xBlockParam or bad yBlockParam or both..");

    int nTimesHas = 0; 
    for (int x=0; x<3; x++)
        for (int y=0; y<3;y++)
            nTimesHas = nTimesHas +getCell(xBlockParam+x, yBlockParam+y);

    return(nTimesHas);
 }

1 个答案:

答案 0 :(得分:0)

您编写的功能正是您所需要的。您的函数仅检查一行(列或框)中单个数字的次数。

要判断行(列或框)是否合适,您确实需要检查所有数字(1-9),而不仅仅是其中一个。

然而,好消息是可以使用您的功能实现所需的功能:

public boolean isGoodRow( int yRowParam ){
    // for number = 1,..,9, ensure the count is not > 1
    for(int i=1; i<=9; i++)
        if(timesRowHas(yRowParam, i) > 1)
            return false;
    return true;
}

(如果您感兴趣):这不是最有效的解决方案,它在O(n 2 )时间内运行。 isGoodRow()可以在O(n)时间内通过对行中的#进行直方图来找到。


一旦实现了必要的功能:

public boolean isGoodRow( int yRowParam )
public boolean isGoodColumn( int xColParam )
public boolean isGoodBlock(int xBlockP, int yBlockP)

然后你只需要用它们来实现checkAndPrintReport()

public boolean checkAndPrintReport(){ 
   for(int i=0; i<9; i++)
        if(!isGoodRow(i) || !isGoodColumn(i) || !isGoodBlock(i/3, i%3)
            return false;
   return true;
}