Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the term 'single pass' defined?

Does implementing a procedure in a single pass mean non-recursive? Or does it mean that the procedure should never recur on the same information twice?

I ask this because I was under the impression that it was the first definition, but now I have stumbled across a homework problem that I can't figure out without using recursion but says "complete in a single pass".

like image 444
jblittle Avatar asked Sep 14 '25 05:09

jblittle


1 Answers

A "single pass" means that each element in a collection of elements (be it: a list, an array, a set, a vector, a map, a tree, a graph, a string, etc.) is visited ("iterated over") once and only once - it doesn't matter if the procedure is recursive or iterative. For example, the following recursive procedure in Scheme adds all the elements in a list in a single pass:

(define (sum lst)
  (if (null? lst)
      0
      (+ (car lst)
         (sum (cdr lst)))))

The same procedure can be written in a tail recursive fashion - meaning: when the recursive call happens inside another procedure, is its final action; it may produce a return value which is then immediately returned by the calling procedure. Anyway, only a single pass is executed over the elements in the list:

(define (sum lst)
  (let loop ((lst lst)
             (acc   0))
    (if (null? lst)
        acc
        (loop (cdr lst) (+ (car lst) acc)))))

Compare the above two examples with this code in Java: it's an iterative method, but once again a single pass is performed over the array:

int sum(int[] array) {
    int acc = 0;
    for (int x : array)
        acc += x;
    return acc;
}
like image 103
Óscar López Avatar answered Sep 17 '25 21:09

Óscar López