球拍:在向量上的滑动窗口

时间:2018-05-14 02:59:29

标签: scheme racket sliding-window subsequence

在Racket中对有限序列执行滑动窗口有哪些好方法,例如找到4个数字的任何子序列的最高总和?

(define example #(3 1 4 5 10 23 1 50 0 12 40 12 43 20))

1 个答案:

答案 0 :(得分:1)

首先找到前缀总和:

#lang racket
(define example #(3 1 4 5 10 23 1 50 0 12 40 12 43 20))

(define-values (sums sum)
  (for/fold ([sums '()] [sum 0]) ([x example])
    (values (cons sum sums) (+ sum x))))
(list->vector (cons sum sums))

结果:

'#(224 204 161 149 109 97 97 47 46 23 13 8 4 3 0)

然后......获利。

利润可能是这样:

#lang racket
(define example #(3 1 4 5 10 23 1 50 0 12 40 12 43 20))

(define (prefix-sums xs)
  (define-values (sums sum)
    (for/fold ([sums '()] [sum 0]) ([x xs])
      (values (cons sum sums) (+ sum x))))
  (list->vector (reverse (cons sum sums))))

(define (sum4 xs i)
  (- (vector-ref xs (+ i 4))
     (vector-ref xs    i)))

(define (sum4s xs)
  (for/list ([i (- (vector-length xs) 4)])
    (sum4 (prefix-sums xs) i)))

(apply max (sum4s example))