合并2组间隔

时间:2014-03-09 22:51:37

标签: recursion scheme racket

我有一个联合方法设置来组合两组有序间隔:

(define (union set1 set2)
  (cond [(empty? set1) set2]
        [(empty? set2) set1]
        [(< (caar set1) (caar set2)) (cons (car set1) (union (cdr set1)
                                                             set2))]
        [else (cons (car set2) (union set1
                                      (cdr set2)))]))

给出2个列表'((1 3) (5 10) (19 29))'((2 4) (17 25) (30 49)),它们会产生

'((1 3) (2 4) (5 10) (17 25) (19 29) (30 49))上面的代码。

但是通过上述实现,重叠间隔未得到正确处理。我需要合并重叠间隔以生成'((1 3) (2 4) (5 10) (17 29) (30 49))。我怎样才能处理这些间隔合并以便没有重叠?

1 个答案:

答案 0 :(得分:2)

假设您正在使用半开放时间间隔[from upto),则Racket提供interval-map模块:

  

interval-map是一个可变数据结构,它将精确整数的半开区间映射到值。在离散点查询间隔映射,查询结果是映射到包含该点的间隔的值。

提供的示例:

> (define r (make-interval-map))
> (interval-map-set! r 1 5 'apple)
> (interval-map-set! r 6 10 'pear)
> (interval-map-set! r 3 7 'banana)
> (dict-map r list)
'(((1 . 3) apple) ((3 . 7) banana) ((7 . 10) pear))

使用示例输入'((1 3) (5 10) (19 29))'((2 4) (17 25) (30 49))

#lang racket/base
(require data/interval-map
         racket/list
         racket/match
         racket/dict)

(define im (make-interval-map))

;; Add your first set
(for ([x '((1 3) (5 10) (19 29))])
  (interval-map-set! im (first x) (second x) #f))

;; Add your second set
(for ([x '((2 4) (17 25) (30 49))])
  (interval-map-set! im (first x) (second x) #f))

;; The result
(map car (dict-map im list))
;; => '((1 . 2) (2 . 4) (5 . 10) (17 . 25) (25 . 29) (30 . 49))