如何找到最小长度

How to find the minimum length

我有一个 XY 乘以 XY 向量 b (a 2d array/matrix)。此向量中的每个条目都有一个列表,其长度可以从 1 到 X*Y 个元素。我想遍历向量的所有元素并找出具有最小长度列表的向量的行和列(或者如果有多个 return 其中一个或所有也很好).

我从以下(不完整的代码)开始

 (define (find-minimum-row-col b X Y)
  (for*/first ([row (* X Y)]
               [col (* X Y)]               
               #:when (< ( length (vector-ref (vector-ref b row) col))) the-min-sofar))
    (cons row col)))

我不确定如何以功能方式跟踪 运行 最小坐标和相应坐标(即不使用 set! on the-min-sofar 变量)

试试这个:

(define (find-minimum-row-col a)
  (for*/fold ([the-min '(0 . 0)])
             ([row (in-range (vector-length a))]
              [col (in-range (vector-length (vector-ref a 0)))])
    (if (< (length (vector-ref (vector-ref a row) col))
           (length (vector-ref (vector-ref a (car the-min)) (cdr the-min))))
        (cons row col)
        the-min)))

诀窍是使用for*/fold 将迭代结果累加到the-min 变量中,并根据需要更新它。我们不必传递矩阵的维度,只要矩阵为 non-empty 并且所有行都具有相同的列数,所有这一切都有效。例如:

(find-minimum-row-col '#(#((1) (2 2) (3 3 3))
                         #((2 2) (1) (3 3 3))
                         #((2 2) () (2 2))))
=> '(2 . 1)