Logo

Programming-Idioms

  • Java
  • Python

Idiom #196 Pass a sub-array

Given an integer array a of size n, pass the first, third, fifth and seventh, ... up to the m th element to a routine foo which sets all these elements to 42.

def foo(data, r):
    for i in r: 
        data[i] = 42

foo(a, range(0, m+1, 2))
def foo(s):
    global a
    m = (s.stop - 1) - s.start
    a[s] = [42] * ((m // s.step) + 1)
foo(slice(0, m + 1, 2))

The slice must be m < n.
interface F { void set(int a[], int m); }
F f = (a, m) -> {
    for (int i = 1; i <= m; a[i] = 42, i = i + 2);
};
void foo(int a[], int m) {
    for (int i = 1; i <= m; a[i] = 42, i = i + 2);
}

Passes the entire `a` reference.
void Foo(out int element)
{
    element = 42;
}

for (int i = 0; i < m; i += 2)
{
    Foo(out a[i]);
}

a.Length is the size of a at run-time.

Requires m <= a.Length; the code does not verify this beforehand.

References to individual elements are passed to Foo().

New implementation...
< >
tkoenig