2

I am coding a Sudoku program. I found the number in the array determine whether duplicate each other is hard.

Now I have an array: int streamNum[SIZE]

  • if SIZE=3,I can handle this problem like:if(streamNum[0]!=streamNum[1])...
  • if SIZE=100,I think that I need a better solution, is there any standard practice?
4

3 回答 3

1

有几种不同的方法可以做到这一点,我想最简单的方法是编写两个循环

bool has_duplicate = false;
for (int i = 0; i < SIZE && !has_duplicate; ++i)
    for (int j = i + 1; j < SIZE && !has_duplicate; ++j)
        if (streamNum[i] == streamNum[j])
            has_duplicate = true;
if (has_duplicate)
{
    ...
}
else
{
    ...
}

第一个循环遍历数组中的每个元素,第二个循环检查数组的其余元素中是否存在重复项(这就是它从 开始的原因i + 1)。一旦找到重复项,两个循环都会退出(就是这样&& !has_duplicate做的)。

这不是最有效的方法,更有效的方法是在查找重复项之前对数组进行排序,但这会同时修改数组的内容。

我希望我已经足够了解您的要求。

于 2013-10-06T07:34:05.703 回答
1
for(int i=0;i<size;i++){
    for(int j=i+1;j<size;j++){
        if(streamNUM[i]==streamNUM[j]){
           ...........
        }
     }
}

我假设你需要是否有重复这可能会有所帮助

如果不评论

于 2013-10-06T07:35:34.857 回答
0

It's a little unclear what exactly you're looking to do here but I'm assuming as it's sudoku you're only interested in storing numbers 1-9?

If so to test for a duplicate you could iterate through the source array and use a second array (with 9 elements - I've called it flag) to hold a flag showing whether each number has been used or not.

So.. something like:

for (loop=0;loop<size;loop++) {
    if (flag[streamNum[loop]]==true) {
        //duplicate - do something & break this loop
        break;
    }
    else {
       flag[streamNum[loop]=true;
    }
}

Here's how I'd test against Sudoku rules - it checks horizontal, vertical and 3x3 block using the idea above but here 3 different flag arrays for the 3 rules. This assumes your standard grid is held in an 81-element array. You can easily adapt this to cater for partially-completed grids..

for (loop=0;loop<9;loop++) {
    flagH=[];
    flagV=[];
    flagS=[];

    for (loop2=0;loop2<9;loop2++) {
        //horizontal
        if(flagH[streamNum[(loop*9)+loop2]]==true) {
           duplicate
        else {
           flagH[streamNum[(loop*9)+loop2]]=true);
        }

        //column test
        if(flagV[streamNum[loop+(loop2*9)]]==true) {
        ..same idea as above

        //3x3 sub section test
        basecell = (loop%3)*3+Math.floor(loop/3)*27; //topleft corner of 3x3 square
        cell = basecell+(loop2%3+(Math.floor(loop2/3)*9));
        if(flagS[streamNum[cell]]==true) {
        ..same idea as before..

   }
}
于 2013-10-06T07:47:25.290 回答