'Looping through a multidimensional array error

Im making a sudoku game. The Multidimensional array is called array. I basically flattening the array and search for dublicates. I cannot seem to turn this unefficient piece of code:

if(true)
            return
            findDoublicates(flattenArray(array, 0, 0))
            && findDoublicates(flattenArray(array, 0, 3))
            && findDoublicates(flattenArray(array, 0, 6))
            && findDoublicates(flattenArray(array, 3, 0))
            && findDoublicates(flattenArray(array, 3, 3))
            && findDoublicates(flattenArray(array, 3, 6))
            && findDoublicates(flattenArray(array, 6, 0))
            && findDoublicates(flattenArray(array, 6, 3))
            && findDoublicates(flattenArray(array, 6, 6));
}
return true;

into this

for (int i = 0; i < array.Length; i += 3)
{
    for (int j = 0; j < array.Length; j += 3)
    {
        if (findDoublicates(flattenArray(array, i, j))) return false;
    }
}
return true;

Basically, the flattenArray method takes in a multidimensional array and 2 coordinates from which it flattens down a 3*3 piece of the array. For whatever reason it just returns false all the time.

I dont think its because of findDoublicates and flattenArray since they work perfectly in my other cases. In the upper example everything works fine but in the second example something goes wrong and i cant notice what it is.

Am i missing something obvious?

Answer

if(true)
{
    for (int i = 0; i < array.Length; i += 3)
    {
        for (int j = 0; j < array.Length; j += 3)
        {
            if (!findDoublicates(flattenArray(array, i, j))) return false;  
        }
    }
}
return true;

forgot to invert the return of findDoublicates



Solution 1:[1]

It might be that you got your condition wrong in the second piece of code.

In the first snippet, you return true if all the findDoublicates() return true, and false on the first findDoublicates() that's false.

In the second snippet, you return false as soon as you find a findDoublicates() that is true.

Try this:

if(true)
{
    for (int i = 0; i < array.Length; i += 3)
    {
        for (int j = 0; j < array.Length; j += 3)
        {
            if (!findDoublicates(flattenArray(array, i, j))) return false;  
        }
    }
}
return true;

Also, you might want to rename it findDuplicates()...

Solution 2:[2]

The first piece of code return true if every check are true, and false as soon as one of the check is false.

The second piece of code return true if every check are false, and false as soon as one of the check is true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vmallet
Solution 2 Kaiak