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.




include c:\cxpl\codes;          \intrinsic 'code' declarations
 
proc Filter(A, B, Option);      \Select all even numbers from array A
int  A, B, Option;              \ and return them in B, unless Option = true
int  I, J;
[J:= 0;
for I:= 1 to A(0) do
        if (A(I)&1) = 0 then
                [J:= J+1;
                if Option then
                        A(J):= A(I)
                else    B(J):= A(I);
                ];
if Option then A(0):= J else B(0):= J;
];
 
int Array, Evens(11), I;
[Array:= [10, 3, 1, 4, 1, 5, 9, 2, 6, 5, 4];
Filter(Array, Evens, false);
for I:= 1 to Evens(0) do
        [IntOut(0, Evens(I));  ChOut(0, ^ )];
CrLf(0);
 
Filter(Array, Evens \not used\, true);
for I:= 1 to Array(0) do
        [IntOut(0, Array(I));  ChOut(0, ^ )];
CrLf(0);
]