3

I'm having trouble with a specific part of my algorithm and was hoping someone has an idea what I'm doing wrong.

My program basically works like this:

Create 81 empty cells, fill each cell step per step while checking if it's valid there.

I have 3 valid checks and the horizontal valid check (if numbers are double or more in 1 line) is already giving me trouble.

This is my function:

private function isValidHorizontal($index)
    {
        for ($i = 0; $i < 81; $i += 9){

            $firstIndex = $i * 9;
            $lastIndex = 9 * ($i + 1) - 1;

            // fisrt loop tracking fowards, 2nd loop tracking backwards
            if ($index >= $i && $index <= $lastIndex) {
                for ($j = 0; $j <= $lastIndex; $j++) {
                    if ($this->cell[$index]->getValue() == $j) {
                        return false;
                    }
                }
                for ($k = 0; $k >= $firstIndex; $k--){
                    if ($this->cell[$index]->getValue() == $j) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

$index is the position of the cell so when $index = 0 that would be the very first cell. Last cell would be $index = 80

$this->cell[$index]->getValue() returns an int number i checked so I'm getting the value correctly.

The problem it somehow never returns true

Any Ideas? obviously this is just part of the code, if you need more to help, write a comment and I'll edit :)

laurent
  • 88,262
  • 77
  • 290
  • 428
gempir
  • 1,791
  • 4
  • 22
  • 46

2 Answers2

1

In the second inner loop you are using $j instead of $k:

for ($k = 0; $k >= $firstIndex; $k--){
    if ($this->cell[$index]->getValue() == $j) { // Here, change to $k
laurent
  • 88,262
  • 77
  • 290
  • 428
1

You already got the right answer from @this.lau_, but If I may offer some advice, you could shorten it up a bit by changing the logic. PHP isn't really the best suited language for this, so it'll still look a bit clunky, but I might be worth taking a look at. :)

private function isValidHorizontal($index) {
    $taken = [];
    foreach (range($index, 81, 9) as $i) {
        $value = $this->cell[$i]->getValue();
        if (is_int($value) && in_array($value, $taken)) {
            return false;
        }
        $taken[] = $value;
    }
    return true;
}
Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • I get what you want to do and this would make it a lot more efficent but I'm already getting an invalid at the very first cell – gempir Sep 16 '15 at 18:56
  • Yeah, I couldn't test the code since I don't have your object, so I meant it as a rough idea template only. Sorry about that. But at least you got the code from the other answer working. :) – Joel Hinz Sep 16 '15 at 18:57