Accumulate Checking an Array

From Progzoo
Jump to navigation Jump to search

You can use an accumulator to check if some condition is true for every element. For example we can check that every element is equal to 10. The array {10, 10, 10} would pass the test and return true, the array {10, 12, 10} would fail the test and return false.

boolean acc = true;
for (v:a)
  if (v!=10)
    acc = false;
return acc;

We can do a little better than that. As soon as we find one value that is false there is no need to look at the rest of the array. We can "short circuit" the evaluation by returning immediately we find a false.

for (v:a)
  if (v!=10)
    return false;
return true;

All 1s

Return true if every element is equal to 1, otherwise return false.

[Font] [Default] [Show] [Resize] [History] [Profile]

Any ones

Return true if 1 occurs in the array, otherwise return false.

[Font] [Default] [Show] [Resize] [History] [Profile]

Words beginning with s

Return true if every element starts with the letter "s", otherwise return false.

f({"sock","shoe","spats"})    -> true
f({"silver","gold"})          -> false
f({"swim","swam","swan"})     -> true
f({"saturday","sunday"})      -> true

[Font] [Default] [Show] [Resize] [History] [Profile]