connected?
dvanhorn <[email protected]>
| Newsgroups | gmane.org.ballistichelmet.lambda |
|---|---|
| Message-ID | <[email protected]> |
So Aaron and I were discussing algorithms to determine if a given set is
connected. Here is my algorithm, which is a generic algorithm for finite
sets, parameterized by some predicate touching? which returns true when two
elements are touching and false otherwise. It's not very efficient, but
fairly elegant IMHO. I'd like to see other approaches...
David
This code uses the list set functions specified in Olin Shivers' SRFI-1,
available at http://srfi.schemers.org/srfi-1/. From MzScheme it can be loaded
with (require (lib "list.ss" "srfi" "1")).
;; A set s is connected iff it contains 1 or fewer elements or...
;; We choose a singleton subset of s, c_0, which by definition is
;; connected. Let c_n be the union of c_n-1 and all elements in s that
;; touch an element in c_n-1. When c_n = c_n-1 we know that c_n does not
;; touch any more elements in s. If c_n = s, then s is connected,
;; otherwise s is not connected.
;; 'a set -> bool
(define (connected? s)
(if (<= (length s) 1) #t
(let ((touching-s?
(lambda (x) (filter (lambda (y) (touching? x y)) s))))
(let loop ((c (list (car s))))
(let ((c+1 (apply lset-union equal? c (map touching-s? c))))
(if (lset= equal? c c+1)
(lset= equal? c s)
(loop c+1)))))))