Felipe Ruiz
Felipe Ruiz

Reputation: 181

SplMinHeap and top

I'm trying to extend PHP's SplMinHeap so I can limit the amount of items my heap can hold. The problem is, when I try to access the top element, which should be the min, it gives me the max value. The code I have so far is pretty simple:

class MyHeap extends SplMinHeap {
    public static $limit = 10;

    public function compare($value1, $value2) {
         return ($value1 - $value2);
    }

    public function myInsert($value) {
        if ( $this->count() < self::$limit ) {
            $this->insert($value);
        } else {
            var_dump($this->top());
        }
    }
};

When I insert the numbers 1 to 15 I would expect it to print 1 5 times, instead it prints 10. I also tried extending the insert method, using the same code as myInsert but replacing $this->insert with parent::insert. I just didn't know whether that would use my extended compare or the default one, that's why I switched it.

Strangely enough, if use a normal SplMinHeap and insert the same numbers I will get 1 when calling top().

Can anyone help me figure out what I'm doing wrong?

Upvotes: 0

Views: 663

Answers (2)

vascowhite
vascowhite

Reputation: 18430

I'm not sure what your compare method is meant to achieve, as it is doing exactly the same as the default compare method, but removing it resolves the problem. You have declared the compare method as public, which generate a warning as the method in the base class is protected.

Also you can override the insert method directly and everything will work fine:-

class MyHeap extends SplMinHeap {
    public static $limit = 10;

    public function insert($value) {
        if ($this->count() < self::$limit) {
            parent::insert($value);
        } else {
            var_dump($this->top());
        }
    }
};

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

The problem is the compare method. Just change compare

public function compare($value1, $value2) {
     return ($value2 - $value1);
}

and you will get your SplMinHeap. Also I think you should extend SplHeap class, not SplMinHeap.

Upvotes: 2

Related Questions