HtDP taught us how to check if there exists path(s) from one node to another.

I tried to implement accumulating all the paths between two nodes as:

```racket
(define (find-paths origin dest G path)
  (cond
    [(equal? origin dest) (reverse (cons dest path))]
    [else
     (find-paths/all (neighbors origin G) dest G (cons origin path))]))

(define (find-paths/all lons dest G path)
  (cond
    [(empty? lons) '(#f)]
    [else
     (map (λ (n) (find-paths n dest G path)) lons)]))
```

However, when I tested it by

```racket
(define sample-graph
  '((A (B E))
    (B (E))))

(define (neighbors origination G)
  (cadr (assoc origination G)))

(find-paths 'A 'E sample-graph '())
```

The answer is: '(((A B E)) (A E))

In order to get the right answer, I have to write another `flatten` function as:

```racket
(define (flatten-path lop)
  (cond
    [(empty? lop) empty]
    [(not (list? (caar lop))) (cons (first lop) (flatten-path (rest lop)))]
    [else
     (append (flatten-path (first lop)) (flatten-path (rest lop)))]))

(filter (λ (path) (not (boolean? (car path)))) (flatten-path (find-paths 'A 'E 
sample-graph '())))
```

And now it works.

I was wondering if maybe I could improve it? 

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to