Task

Select certain elements from an Array into a new Array in a generic way.



To demonstrate, select all even numbers from an Array.

As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.




(subscriptrange):
filter_values: procedure options (main); /* 15 November 2013 */
   declare a(20) fixed, b(*) fixed controlled;
   declare (i, j, n) fixed binary;
 
   a = random()*99999; /* fill the array with random elements from 0-99998 */
   put list ('Unfiltered values:');
   put skip edit (a) (f(6));
   /* Loop to count the number of elements that will be filtered */
   n = 0;
   do i = 1 to hbound(a);
      n = n + filter(a(i));
   end;
   allocate b(n);
   j = 0;
   do i = 1 to hbound(a);
      if filter(a(i)) then do; j = j + 1; b(j) = a(i); end;
   end;
   put skip list ('Filtered values:');
   put skip edit (b) (f(6));
 
filter: procedure (value) returns (bit(1));
   declare value fixed;
 
   return (iand(abs(value), 1) = 0);
end filter;
 
end filter_values;