data-structuresschemeheapracketr5rs

Combine Two Heaps Given a First Order Relation


What I have to do:

Define a SCHEME procedure, named (combine f Ha Hb), which accepts three arguments, f, a firstorder relation which is used to order the elements in the heap, and two heap structures, Ha and Hb, which have been constructed using the same first-order relation.

Example of a test case:

( define Ha ( heap-insert-list > ( list 9 5 7 3) ( list )))
( define Hb ( heap-insert-list > ( list 2 8 4 6) ( list )))
( combine > Ha Hb )
(9 (7 () (5 () (3 () ()))) (8 (4 () ()) (6 () (2 () ()))))

My code:

(define (create-heap v H1 H2)
(list v H1 H2))
(define (h-min H) (car H))
(define (left heap)
  (cadr heap))
(define (right heap)
  (caddr heap))

(define (combine f Ha Hb)
  (cond ((null? Ha) Hb)
    ((null? Hb) Ha)
    ((< (h-min Ha) (h-min Hb))
     (create-heap (h-min Ha)
                  Hb
                  (combine (left Ha) (right Ha))))
    (else
     (create-heap (h-min Hb)
                  Ha
                  (combine (left Hb) (right Hb)) Ha))))

My code is doing something right as I am getting 50% on my test cases, but it is not completely passing them.


Solution

  • Well, for starters you're not using the f procedure! This:

    ((< (h-min Ha) (h-min Hb))
    

    ... Most likely should look like this:

    ((f (h-min Ha) (h-min Hb))
    

    Also, you forgot to pass the f parameter when calling the recursion:

    (combine f (left Ha) (right Ha))