Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

5
Task/Filter/00-META.yaml Normal file
View file

@ -0,0 +1,5 @@
---
category:
- Iteration
from: http://rosettacode.org/wiki/Filter
note: Basic language learning

10
Task/Filter/00-TASK.txt Normal file
View file

@ -0,0 +1,10 @@
;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.
<br><br>

View file

@ -0,0 +1,3 @@
V array = Array(1..10)
V even = array.filter(n -> n % 2 == 0)
print(even)

View file

@ -0,0 +1,5 @@
(defun filter-evens (xs)
(cond ((endp xs) nil)
((evenp (first xs))
(cons (first xs) (filter-evens (rest xs))))
(t (filter-evens (rest xs)))))

View file

@ -0,0 +1,23 @@
MODE TYPE = INT;
PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
BEGIN
FLEX[0]TYPE result;
FOR key FROM LWB from TO UPB from DO
IF where(from[key]) THEN
[UPB result+1]TYPE new result;
new result[:UPB result] := result;
new result[UPB new result] := from[key];
result := new result
FI
OD;
result
END;
[]TYPE from values = (1,2,3,4,5,6,7,8,9,10);
PROC where even = (TYPE value)BOOL: NOT ODD value;
print((select(from values, where even), new line));
# Or as a simple one line query #
print((select((1,4,9,16,25,36,49,64,81,100), (TYPE x)BOOL: NOT ODD x ), new line))

View file

@ -0,0 +1,26 @@
begin
% sets the elements of out to the elements of in that return true from applying the where procedure to them %
% the bounds of in must be 1 :: inUb - out must be at least as big as in and the number of matching %
% elements is returned in outUb - in and out can be the same array %
procedure select ( integer array in ( * ); integer value inUb
; integer array out ( * ); integer result outUb
; logical procedure where % ( integer value n ) %
) ;
begin
outUb := 0;
for i := 1 until inUb do begin
if where( in( i ) ) then begin
outUb := outUb + 1;
out( outUb ) := in( i )
end f_where_in_i
end for_i
end select ;
% test the select procedure %
logical procedure isEven ( integer value n ) ; not odd( n );
integer array t, out ( 1 :: 10 );
integer outUb;
for i := 1 until 10 do t( i ) := i;
select( t, 10, out, outUb, isEven );
for i := 1 until outUb do writeon( i_w := 3, s_w := 0, out( i ) );
write()
end.

View file

@ -0,0 +1,2 @@
x:range[100]
{1- x mod 2}hfilter x

View file

@ -0,0 +1,2 @@
(0=2|x)/x20
2 4 6 8 10 12 14 16 18 20

View file

@ -0,0 +1 @@
$ awk 'BEGIN{split("1 2 3 4 5 6 7 8 9",a);for(i in a)if(!(a[i]%2))r=r" "a[i];print r}'

View file

@ -0,0 +1,5 @@
BEGIN {
split("1 2 3 4 5 6 7 8 9",a);
for(i in a) if( !(a[i]%2) ) r = r" "a[i];
print r
}

View file

@ -0,0 +1,108 @@
DEFINE PTR="CARD"
INT value ;used in predicate
PROC PrintArray(INT ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
PrintI(a(i))
IF i<size-1 THEN
Put(' )
FI
OD
Put(']) PutE()
RETURN
;jump addr is stored in X and A registers
BYTE FUNC Predicate=*(PTR jumpAddr)
DEFINE STX="$8E"
DEFINE STA="$8D"
DEFINE JSR="$20"
DEFINE RTS="$60"
[STX Predicate+8
STA Predicate+7
JSR $00 $00
RTS]
PROC DoFilter(PTR predicateFun
INT ARRAY src BYTE srcSize
INT ARRAY dst BYTE POINTER dstSize)
INT i
dstSize^=0
FOR i=0 TO srcSize-1
DO
value=src(i)
IF Predicate(predicateFun) THEN
dst(dstSize^)=value
dstSize^==+1
FI
OD
RETURN
PROC DoFilterInplace(PTR predicateFun
INT ARRAY data BYTE POINTER size)
INT i,j
i=0
WHILE i<size^
DO
value=data(i)
IF Predicate(predicateFun)=0 THEN
FOR j=i TO size^-2
DO
data(j)=data(j+1)
OD
size^==-1
ELSE
i==+1
FI
OD
RETURN
BYTE FUNC Even()
IF (value&1)=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC NonNegative()
IF value>=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Main()
INT ARRAY src=[65532 3 5 2 65529 1 0 65300 4123],dst(9)
BYTE srcSize=[9],dstSize
PrintE("Non destructive operations:") PutE()
PrintE("Original array:")
PrintArray(src,srcSize)
DoFilter(Even,src,srcSize,dst,@dstSize)
PrintE("Select all even numbers:")
PrintArray(dst,dstSize)
DoFilter(NonNegative,src,srcSize,dst,@dstSize)
PrintE("Select all non negative numbers:")
PrintArray(dst,dstSize)
PutE()
PrintE("Destructive operations:") PutE()
PrintE("Original array:")
PrintArray(src,srcSize)
DoFilterInplace(Even,src,@srcSize)
PrintE("Select all even numbers:")
PrintArray(src,srcSize)
DoFilterInplace(NonNegative,src,@srcSize)
PrintE("Select all non negative numbers:")
PrintArray(src,srcSize)
RETURN

View file

@ -0,0 +1,6 @@
var arr:Array = new Array(1, 2, 3, 4, 5);
var evens:Array = new Array();
for (var i:int = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 0)
evens.push(arr[i]);
}

View file

@ -0,0 +1,4 @@
var arr:Array = new Array(1, 2, 3, 4, 5);
arr = arr.filter(function(item:int, index:int, array:Array) {
return item % 2 == 0;
});

View file

@ -0,0 +1,32 @@
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
procedure Array_Selection is
type Array_Type is array (Positive range <>) of Integer;
Null_Array : Array_Type(1..0);
function Evens (Item : Array_Type) return Array_Type is
begin
if Item'Length > 0 then
if Item(Item'First) mod 2 = 0 then
return Item(Item'First) & Evens(Item((Item'First + 1)..Item'Last));
else
return Evens(Item((Item'First + 1)..Item'Last));
end if;
else
return Null_Array;
end if;
end Evens;
procedure Print(Item : Array_Type) is
begin
for I in Item'range loop
Put(Item(I));
New_Line;
end loop;
end Print;
Foo : Array_Type := (1,2,3,4,5,6,7,8,9,10);
begin
Print(Evens(Foo));
end Array_Selection;

View file

@ -0,0 +1,28 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Array_Selection is
type Array_Type is array (Positive range <>) of Integer;
function Evens (Item : Array_Type) return Array_Type is
Result : Array_Type (1..Item'Length);
Index : Positive := 1;
begin
for I in Item'Range loop
if Item (I) mod 2 = 0 then
Result (Index) := Item (I);
Index := Index + 1;
end if;
end loop;
return Result (1..Index - 1);
end Evens;
procedure Put (Item : Array_Type) is
begin
for I in Item'range loop
Put (Integer'Image (Item (I)));
end loop;
end Put;
begin
Put (Evens ((1,2,3,4,5,6,7,8,9,10)));
New_Line;
end Array_Selection;

View file

@ -0,0 +1,51 @@
integer
even(integer e)
{
return !(e & 1);
}
list
filter(list l, integer (*f)(integer))
{
integer i;
list v;
i = 0;
while (i < l_length(l)) {
integer e;
e = l_q_integer(l, i);
if (f(e)) {
lb_p_integer(v, e);
}
i += 1;
}
return v;
}
integer
main(void)
{
integer i;
list l;
i = 0;
while (i < 10) {
lb_p_integer(l, i);
i += 1;
}
l = filter(l, even);
i = 0;
while (i < l_length(l)) {
o_space(1);
o_integer(l_q_integer(l, i));
i += 1;
}
o_byte('\n');
return 0;
}

View file

@ -0,0 +1,7 @@
PROC main()
DEF l : PTR TO LONG, r : PTR TO LONG, x
l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
r := List(ListLen(l))
SelectList({x}, l, r, `Mod(x,2)=0)
ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC

View file

@ -0,0 +1,15 @@
List<Integer> integers = new List<Integer>{1,2,3,4,5};
Set<Integer> evenIntegers = new Set<Integer>();
for(Integer i : integers)
{
if(math.mod(i,2) == 0)
{
evenIntegers.add(i);
}
}
system.assert(evenIntegers.size() == 2, 'We should only have two even numbers in the set');
system.assert(!evenIntegers.contains(1), '1 should not be a number in the set');
system.assert(evenIntegers.contains(2), '2 should be a number in the set');
system.assert(!evenIntegers.contains(3), '3 should not be a number in the set');
system.assert(evenIntegers.contains(4), '4 should be a number in the set');
system.assert(!evenIntegers.contains(5), '5 should not be a number in the set');

View file

@ -0,0 +1,6 @@
set array to {1, 2, 3, 4, 5, 6}
set evens to {}
repeat with i in array
if (i mod 2 = 0) then set end of evens to i's contents
end repeat
return evens

View file

@ -0,0 +1,17 @@
to filter(inList, acceptor)
set outList to {}
repeat with anItem in inList
if acceptor's accept(anItem) then
set end of outList to contents of anItem
end
end
return outList
end
script isEven
to accept(aNumber)
aNumber mod 2 = 0
end accept
end script
filter({1,2,3,4,5,6}, isEven)

View file

@ -0,0 +1,43 @@
-------------------------- FILTER --------------------------
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
--------------------------- TEST ---------------------------
on run
filter(even, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
--> {0, 2, 4, 6, 8, 10}
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1,3 @@
arr: [1 2 3 4 5 6 7 8 9 10]
print select arr [x][even? x]

View file

@ -0,0 +1,49 @@
array = 1,2,3,4,5,6,7
loop, parse, array, `,
{
if IsEven(A_LoopField)
evens = %evens%,%A_LoopField%
}
stringtrimleft, evens, evens, 1
msgbox % evens
return
IsEven(number)
{
return !mod(number, 2)
}
; ----- Another version: always with csv string ------
array = 1,2,3,4,5,6,7
even(s) {
loop, parse, s, `,
if !mod(A_LoopField, 2)
r .= "," A_LoopField
return SubStr(r, 2)
}
MsgBox % "Array => " array "`n" "Result => " even(array)
; ----- Yet another version: with array (requires AutoHotKey_L) ------
array2 := [1,2,3,4,5,6,7]
even2(a) {
r := []
For k, v in a
if !mod(v, 2)
r.Insert(v)
return r
}
; Add "join" method to string object (just like python)
s_join(o, a) {
Loop, % a.MaxIndex()
r .= o a[A_Index]
return SubStr(r, StrLen(o) + 1)
}
"".base.join := Func("s_join")
MsgBox % "Array => " ",".join(array2) "`n" "Result => " ",".join(even2(array2))

View file

@ -0,0 +1,34 @@
REM Create the test array:
items% = 1000
DIM array%(items%)
FOR index% = 1 TO items%
array%(index%) = RND
NEXT
REM Count the number of filtered items:
filtered% = 0
FOR index% = 1 TO items%
IF FNfilter(array%(index%)) filtered% += 1
NEXT
REM Create a new array containing the filtered items:
DIM new%(filtered%)
filtered% = 0
FOR index% = 1 TO items%
IF FNfilter(array%(index%)) THEN
filtered% += 1
new%(filtered%) = array%(index%)
ENDIF
NEXT
REM Alternatively modify the original array:
filtered% = 0
FOR index% = 1 TO items%
IF FNfilter(array%(index%)) THEN
filtered% += 1
array%(filtered%) = array%(index%)
ENDIF
NEXT
END
DEF FNfilter(A%) = ((A% AND 1) = 0)

View file

@ -0,0 +1,40 @@
get "libhdr"
// Copy every value for which p(x) is true from in to out
// This will also work in place by setting out = in
let filter(p, in, ilen, out, olen) be
$( !olen := 0
for i = 0 to ilen-1 do
if p(in!i) do
$( out!!olen := in!i
!olen := !olen + 1
$)
$)
// Write N elements from vector
let writevec(v, n) be
for i = 0 to n-1 do writef("%N ", v!i)
let start() be
$( // Predicates
let even(n) = (n&1) = 0
let mul3(n) = n rem 3 = 0
let nums = table 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
let arr = vec 20
let len = ?
writes("Numbers: ")
writevec(nums, 15)
// Filter 'nums' into 'arr'
filter(even, nums, 15, arr, @len)
writes("*NEven numbers: ")
writevec(arr, len)
// Filter 'arr' in place for multiples of 3
filter(mul3, arr, len, arr, @len)
writes("*NEven multiples of 3: ")
writevec(arr, len)
wrch('*N')
$)

View file

@ -0,0 +1,4 @@
_filter {(𝔽𝕩)/𝕩}
Odd 2|
Odd _filter 12345

View file

@ -0,0 +1 @@
1 3 5

View file

@ -0,0 +1,58 @@
@echo off
setlocal enabledelayedexpansion
set numberarray=1 2 3 4 5 6 7 8 9 10
for %%i in (%numberarray%) do (
set /a tempcount+=1
set numberarray!tempcount!=%%i
)
echo Filtering all even numbers from numberarray into newarray...
call:filternew numberarray
echo numberarray - %numberarray%
echo newarray -%newarray%
echo.
echo Filtering numberarray so that only even entries remain...
call:filterdestroy numberarray
echo numberarray -%numberarray%
pause>nul
exit /b
:filternew
set arrayname=%1
call:arraylength %arrayname%
set tempcount=0
for /l %%i in (1,1,%length%) do (
set /a cond=!%arrayname%%%i! %% 2
if !cond!==0 (
set /a tempcount+=1
set newarray!tempcount!=!%arrayname%%%i!
set newarray=!newarray! !%arrayname%%%i!
)
)
exit /b
:filterdestroy
set arrayname=%1
call:arraylength %arrayname%
set tempcount=0
set "%arrayname%="
for /l %%i in (1,1,%length%) do (
set /a cond=!%arrayname%%%i! %% 2
if !cond!==0 (
set /a tempcount+=1
set %arrayname%!tempcount!=!%arrayname%%%i!
set %arrayname%=!%arrayname%! !%arrayname%%%i!
)
)
exit /b
:arraylength
set tempcount=0
set lengthname=%1
set length=0
:lengthloop
set /a tempcount+=1
if "!%lengthname%%tempcount%!"=="" exit /b
set /a length+=1
goto lengthloop

View file

@ -0,0 +1,5 @@
( :?odds
& ( 1 2 3 4 5 6 7 8 9 10 16 25 36 49 64 81 100:? (=.!sjt*1/2:/&!odds !sjt:?odds)$() ()
| !odds
)
)

View file

@ -0,0 +1,2 @@
#Prints [2, 4, 6, 8, 10]
p 1.to(10).select { x | x % 2 == 0 }

View file

@ -0,0 +1,2 @@
blsq ) 1 13r@{2.%n!}f[
{2 4 6 8 10 12}

View file

@ -0,0 +1,18 @@
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>
int main() {
std::vector<int> ary;
for (int i = 0; i < 10; i++)
ary.push_back(i);
std::vector<int> evens;
std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens),
std::bind2nd(std::modulus<int>(), 2)); // filter copy
std::copy(evens.begin(), evens.end(),
std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}

View file

@ -0,0 +1,17 @@
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
int main() {
vector<int> ary = {1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> evens;
copy_if(ary.begin(), ary.end(), back_inserter(evens),
[](int i) { return i % 2 == 0; });
// print result
copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
}

View file

@ -0,0 +1,9 @@
ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
ArrayList evens = new ArrayList();
foreach( int i in array )
{
if( (i%2) == 0 )
evens.Add( i );
}
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );

View file

@ -0,0 +1,4 @@
List<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
List<int> evens = array.FindAll( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );

View file

@ -0,0 +1,4 @@
IEnumerable<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
IEnumerable<int> evens = array.Where( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );

View file

@ -0,0 +1,5 @@
int[] array = { 1, 2, 3, 4, 5 };
int[] evens = array.Where(i => (i % 2) == 0).ToArray();
foreach (int i in evens)
Console.WriteLine(i);

43
Task/Filter/C/filter.c Normal file
View file

@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdlib.h>
int even_sel(int x) { return !(x & 1); }
int tri_sel(int x) { return x % 3; }
/* using a predicate function sel() to select elements */
int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace)
{
int i, j, *out;
if (inplace) out = in;
else out = malloc(sizeof(int) * len);
for (i = j = 0; i < len; i++)
if (sel(in[i]))
out[j++] = in[i];
if (!inplace && j < len)
out = realloc(out, sizeof(int) * j);
*outlen = j;
return out;
}
int main()
{
int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i, len;
int *even = grep(in, 10, &len, even_sel, 0);
printf("Filtered even:");
for (i = 0; i < len; i++) printf(" %d", even[i]);
printf("\n");
grep(in, 8, &len, tri_sel, 1);
printf("In-place filtered not multiple of 3:");
for (i = 0; i < len; i++) printf(" %d", in[i]);
printf("\n");
return 0;
}

View file

@ -0,0 +1,3 @@
module SelectFromArray
import StdEnv

View file

@ -0,0 +1,2 @@
array :: {Int}
array = {x \\ x <- [1 .. 10]}

View file

@ -0,0 +1,2 @@
Start :: {!Int}
Start = {x \\ x <-: array | isEven x}

View file

@ -0,0 +1,4 @@
;; range and filter create lazy seq's
(filter even? (range 0 100))
;; vec will convert any type of seq to an array
(vec (filter even? (vec (range 0 100))))

View file

@ -0,0 +1 @@
[1..10].filter (x) -> not (x%2)

View file

@ -0,0 +1,2 @@
(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)

View file

@ -0,0 +1,2 @@
(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)

View file

@ -0,0 +1,72 @@
include "cowgol.coh";
# Cowgol has strict typing and there are no templates either.
# Defining the type this way makes it easy to change.
typedef FilterT is uint32;
# In order to pass functions around, we need to define an
# interface. The 'FilterPredicate' interface will take an argument
# and return zero if it should be filtered out.
interface FilterPredicate(x: FilterT): (keep: uint8);
# Filter an array and store it a new location. Returns the new length.
sub Filter(f: FilterPredicate,
items: [FilterT],
length: intptr,
result: [FilterT]):
(newLength: intptr) is
newLength := 0;
while length > 0 loop
var item := [items];
items := @next items;
if f(item) != 0 then
[result] := item;
result := @next result;
newLength := newLength + 1;
end if;
length := length - 1;
end loop;
end sub;
# Filter an array in place. Returns the new length.
sub FilterInPlace(f: FilterPredicate,
items: [FilterT],
length: intptr):
(newLength: intptr) is
newLength := Filter(f, items, length, items);
end sub;
# Filter that selects even numbers
sub Even implements FilterPredicate is
keep := (~ x as uint8) & 1;
end sub;
# Filter an array
var array: uint32[] := {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var filtered: uint32[@sizeof array];
var length := Filter(Even, &array[0], @sizeof array, &filtered[0]);
# Print result
var i: uint8 := 0;
while i < length as uint8 loop
print_i32(filtered[i]);
print_char(' ');
i := i + 1;
end loop;
print_nl();
# Filter the result again in place for numbers less than 8
sub LessThan8 implements FilterPredicate is
if x < 8 then keep := 1;
else keep := 0;
end if;
end sub;
length := FilterInPlace(LessThan8, &filtered[0], length);
i := 0;
while i < length as uint8 loop
print_i32(filtered[i]);
print_char(' ');
i := i + 1;
end loop;
print_nl();

7
Task/Filter/D/filter-1.d Normal file
View file

@ -0,0 +1,7 @@
void main() {
import std.algorithm: filter, equal;
immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto evens = data.filter!(x => x % 2 == 0); // Lazy.
assert(evens.equal([2, 4, 6, 8, 10]));
}

10
Task/Filter/D/filter-2.d Normal file
View file

@ -0,0 +1,10 @@
import tango.core.Array, tango.io.Stdout;
void main() {
auto array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// removeIf places even elements at the beginnig of the array and returns number of found evens
auto evens = array.removeIf( ( typeof(array[0]) i ) { return (i % 2) == 1; } );
Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
}

View file

@ -0,0 +1,25 @@
program FilterEven;
{$APPTYPE CONSOLE}
uses SysUtils, Types;
const
SOURCE_ARRAY: array[0..9] of Integer = (0,1,2,3,4,5,6,7,8,9);
var
i: Integer;
lEvenArray: TIntegerDynArray;
begin
for i in SOURCE_ARRAY do
begin
if not Odd(i) then
begin
SetLength(lEvenArray, Length(lEvenArray) + 1);
lEvenArray[Length(lEvenArray) - 1] := i;
end;
end;
for i in lEvenArray do
Write(i:3);
Writeln;
end.

View file

@ -0,0 +1,35 @@
program FilterEven;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Types,
Boost.Int;
var
Source, Destiny: TIntegerDynArray;
begin
Source.Assign([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// Non-destructively
Destiny := Source.Filter(
function(Item: Integer): Boolean
begin
Result := not odd(Item) and (Item <> 0);
end);
Writeln('[' + Destiny.Comma + ']');
Readln;
end.
// Destructively
Source.Remove(
function(Item: Integer): Boolean
begin
Result := odd(Item) or (Item = 0);
end);
Writeln('[' + Source.Comma + ']');
End.

View file

@ -0,0 +1,10 @@
func Array.Filter(pred) {
var arr = []
for x in this when pred(x) {
arr.Add(x)
}
arr
}
var arr = [1..20].Filter(x => x % 2 == 0)
print(arr)

View file

@ -0,0 +1,13 @@
func Array.Filter(pred) {
var i = 0
while i < this.Length() {
if !pred(this[i]) {
this.RemoveAt(i)
}
i += 1
}
}
var arr = [1..20]
arr.Filter(x => x % 2 == 0)
print(arr)

View file

@ -0,0 +1,3 @@
var xs = [1..20]
var arr = xs.Iterate().Filter(x => x % 2 == 0).Map(x => x.ToString())
print(arr.ToArray())

2
Task/Filter/E/filter-1.e Normal file
View file

@ -0,0 +1,2 @@
pragma.enable("accumulator")
accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }

5
Task/Filter/E/filter-2.e Normal file
View file

@ -0,0 +1,5 @@
var result := []
for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
result with= x
}
result

2
Task/Filter/E/filter-3.e Normal file
View file

@ -0,0 +1,2 @@
def makeSeries := <elang:control.makeSeries>
makeSeries([1,2,3,4,5,6,7,8,9,10]).filter(fn x,_{x %% 2 <=> 0}).asList()

View file

@ -0,0 +1,7 @@
a[] = [ 1 2 3 4 5 6 7 8 9 ]
for i = 1 to len a[]
if a[i] mod 2 = 0
b[] &= a[i]
.
.
print b[]

View file

@ -0,0 +1,16 @@
(iota 12) → { 0 1 2 3 4 5 6 7 8 9 10 11 }
;; lists
(filter even? (iota 12))
→ (0 2 4 6 8 10)
;; array (non destructive)
(vector-filter even? #(1 2 3 4 5 6 7 8 9 10 11 12 13))
→ #( 2 4 6 8 10 12)
;; sequence, infinite, lazy
(lib 'sequences)
(define evens (filter even? [0 ..]))
(take evens 12)
→ (0 2 4 6 8 10 12 14 16 18 20 22)

View file

@ -0,0 +1,3 @@
open list
evenList = filter' (\x -> x % 2 == 0) [1..]

View file

@ -0,0 +1 @@
evenList = [& x \\ x <- [1..] | x % 2 == 0]

View file

@ -0,0 +1,13 @@
import system'routines;
import system'math;
import extensions;
import extensions'routines;
public program()
{
auto array := new int[]{1,2,3,4,5};
var evens := array.filterBy:(n => n.mod:2 == 0).toArray();
evens.forEach:printingLn
}

View file

@ -0,0 +1,13 @@
import system'collections;
import system'routines'stex;
import system'math;
import extensions;
public program()
{
int[] array := new int[]{1,2,3,4,5};
array
.filterBy:(int n => n.mod:2 == 0)
.forEach:(int i){ console.printLine(i) }
}

View file

@ -0,0 +1,6 @@
iex(10)> numbers = Enum.to_list(1..9)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex(11)> Enum.filter(numbers, fn x -> rem(x,2)==0 end)
[2, 4, 6, 8]
iex(12)> for x <- numbers, rem(x,2)==0, do: x # comprehension
[2, 4, 6, 8]

View file

@ -0,0 +1 @@
(seq-filter (lambda (x) (= (% x 2))) '(1 2 3 4 5 6 7 8 9 10))

View file

@ -0,0 +1,2 @@
Numbers = lists:seq(1, 5).
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).

View file

@ -0,0 +1 @@
EvenNumbers = [X || X <- Numbers, X rem 2 == 0].

View file

@ -0,0 +1,9 @@
sequence s, evens
s = {1, 2, 3, 4, 5, 6}
evens = {}
for i = 1 to length(s) do
if remainder(s[i], 2) = 0 then
evens = append(evens, s[i])
end if
end for
? evens

View file

@ -0,0 +1,4 @@
let lst = [1;2;3;4;5;6]
List.filter (fun x -> x % 2 = 0) lst;;
val it : int list = [2; 4; 6]

View file

@ -0,0 +1,2 @@
10 <iota> >array [ even? ] filter .
! prints { 0 2 4 6 8 }

View file

@ -0,0 +1,2 @@
10 <iota> [ even? ] filter .
! prints V{ 0 2 4 5 8 }

View file

@ -0,0 +1,3 @@
USE: vectors
10 <iota> >vector [ even? ] filter! .
! prints V{ 0 2 4 5 8 }

View file

@ -0,0 +1,9 @@
USE: locals
10 <iota> >vector [| v |
v [ even? ] filter drop
v pprint " after filter" print
v [ even? ] filter! drop
v pprint " after filter!" print
] call
! V{ 0 1 2 3 4 5 6 7 8 9 } after filter
! V{ 0 2 4 6 8 } after filter!

View file

@ -0,0 +1,11 @@
class Main
{
Void main ()
{
items := [1, 2, 3, 4, 5, 6, 7, 8]
// create a new list with just the even numbers
evens := items.findAll |i| { i.isEven }
// display the result
echo (evens.join(","))
}
}

View file

@ -0,0 +1,12 @@
(= filter (fn (f lst)
(let res (cons nil nil))
(let tail res)
(while lst
(let item (car lst))
(if (f item) (do
(setcdr tail (cons item nil))
(= tail (cdr tail))))
(= lst (cdr lst)))
(cdr res)))
(print (filter (fn (x) (< 5 x)) '(1 4 5 6 3 2 7 9 0 8)))

View file

@ -0,0 +1 @@
(6 7 9 8)

View file

@ -0,0 +1,16 @@
: sel ( dest 0 test src len -- dest len )
cells over + swap do ( dest len test )
i @ over execute if
i @ 2over cells + !
>r 1+ r>
then
cell +loop drop ;
create nums 1 , 2 , 3 , 4 , 5 , 6 ,
create evens 6 cells allot
: .array 0 ?do dup i cells + @ . loop drop ;
: even? ( n -- ? ) 1 and 0= ;
evens 0 ' even? nums 6 sel .array \ 2 4 6

View file

@ -0,0 +1,9 @@
module funcs
implicit none
contains
pure function iseven(x)
logical :: iseven
integer, intent(in) :: x
iseven = mod(x, 2) == 0
end function iseven
end module funcs

View file

@ -0,0 +1,43 @@
program Filter
use funcs
implicit none
integer, parameter :: N = 100
integer, dimension(N) :: array
integer, dimension(:), pointer :: filtered
integer :: i
forall(i=1:N) array(i) = i
filtered => filterwith(array, iseven)
print *, filtered
contains
function filterwith(ar, testfunc)
integer, dimension(:), pointer :: filterwith
integer, dimension(:), intent(in) :: ar
interface
elemental function testfunc(x)
logical :: testfunc
integer, intent(in) :: x
end function testfunc
end interface
integer :: i, j, n
n = count( testfunc(ar) )
allocate( filterwith(n) )
j = 1
do i = lbound(ar, dim=1), ubound(ar, dim=1)
if ( testfunc(ar(i)) ) then
filterwith(j) = ar(i)
j = j + 1
end if
end do
end function filterwith
end program Filter

View file

@ -0,0 +1,63 @@
' FB 1.05.0 Win64
Type FilterType As Function(As Integer) As Boolean
Function isEven(n As Integer) As Boolean
Return n Mod 2 = 0
End Function
Sub filterArray(a() As Integer, b() As Integer, filter As FilterType)
If UBound(a) = -1 Then Return '' empty array
Dim count As Integer = 0
Redim b(0 To UBound(a) - LBound(a))
For i As Integer = LBound(a) To UBound(a)
If filter(a(i)) Then
b(count) = a(i)
count += 1
End If
Next
If count > 0 Then Redim Preserve b(0 To count - 1) '' trim excess elements
End Sub
' Note that da() must be a dynamic array as static arrays can't be redimensioned
Sub filterDestructArray(da() As Integer, filter As FilterType)
If UBound(da) = -1 Then Return '' empty array
Dim count As Integer = 0
For i As Integer = LBound(da) To UBound(da)
If i > UBound(da) - count Then Exit For
If Not filter(da(i)) Then '' remove this element by moving those still to be examined down one
For j As Integer = i + 1 To UBound(da) - count
da(j - 1) = da(j)
Next j
count += 1
i -= 1
End If
Next i
If count > 0 Then
Redim Preserve da(LBound(da) To UBound(da) - count) '' trim excess elements
End If
End Sub
Dim n As Integer = 12
Dim a(1 To n) As Integer '' creates dynamic array as upper bound is a variable
For i As Integer = 1 To n : Read a(i) : Next
Dim b() As Integer '' array to store results
filterArray a(), b(), @isEven
Print "The even numbers are (in new array) : ";
For i As Integer = LBound(b) To UBound(b)
Print b(i); " ";
Next
Print : Print
filterDestructArray a(), @isEven
Print "The even numbers are (in original array) : ";
For i As Integer = LBound(a) To UBound(a)
Print a(i); " ";
Next
Print : Print
Print "Press any key to quit"
Sleep
End
Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27

View file

@ -0,0 +1,2 @@
b = array[1 to 100]
c = select[b, {|x| x mod 2 == 0}]

View file

@ -0,0 +1,2 @@
fun main(as: []int): []int =
filter (fn x => x%2 == 0) as

View file

@ -0,0 +1,10 @@
# Built-in
Filtered([1 .. 100], IsPrime);
# [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ]
Filtered([1 .. 10], IsEvenInt);
# [ 2, 4, 6, 8, 10 ]
Filtered([1 .. 10], IsOddInt);
# [ 1, 3, 5, 7, 9 ]

View file

@ -0,0 +1,43 @@
sRandom As New String[]
'______________________________________________________________________________________________________
Public Sub Main()
Dim siCount As Short
For siCount = 0 To 19
sRandom.Add(Rand(1, 100))
Next
Print sRandom.join(",")
NewArray
Destructive
End
'______________________________________________________________________________________________________
Public Sub NewArray() 'Select certain elements from an array into a new array in a generic way
Dim sEven As New String[]
Dim siCount As Short
For siCount = 0 To sRandom.Max
If Even(sRandom[siCount]) Then sEven.Add(sRandom[siCount])
Next
Print sEven.join(",")
End
'______________________________________________________________________________________________________
Public Sub Destructive() 'Give a second solution which filters destructively
Dim siIndex As New Short[]
Dim siCount As Short
For siCount = 0 To sRandom.Max
If Odd(sRandom[siCount]) Then siIndex.Add(siCount)
Next
For siCount = siIndex.max DownTo 0
sRandom.Extract(siIndex[siCount], 1)
Next
Print sRandom.join(",")
End

40
Task/Filter/Go/filter.go Normal file
View file

@ -0,0 +1,40 @@
package main
import (
"fmt"
"math/rand"
)
func main() {
a := rand.Perm(20)
fmt.Println(a) // show array to filter
fmt.Println(even(a)) // show result of non-destructive filter
fmt.Println(a) // show that original array is unchanged
reduceToEven(&a) // destructive filter
fmt.Println(a) // show that a is now changed
// a is not only changed, it is changed in place. length and capacity
// show that it still has its original allocated capacity but has now
// been reduced in length.
fmt.Println("a len:", len(a), "cap:", cap(a))
}
func even(a []int) (r []int) {
for _, e := range a {
if e%2 == 0 {
r = append(r, e)
}
}
return
}
func reduceToEven(pa *[]int) {
a := *pa
var last int
for _, e := range a {
if e%2 == 0 {
a[last] = e
last++
}
}
*pa = a[:last]
}

View file

@ -0,0 +1 @@
def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}

View file

@ -0,0 +1,2 @@
ary = [1..10]
evens = [x | x <- ary, even x]

View file

@ -0,0 +1 @@
evens = filter even ary

View file

@ -0,0 +1,6 @@
import Data.Array
ary = listArray (1,10) [1..10]
evens = listArray (1,n) l where
n = length l
l = [x | x <- elems ary, even x]

View file

@ -0,0 +1 @@
result = array[where(NOT array AND 1)]

View file

@ -0,0 +1,10 @@
procedure main()
every put(A := [],1 to 10) # make a list of 1..10
every put(B := [],iseven(!A)) # make a second list and filter out odd numbers
every writes(!B," ") | write() # show
end
procedure iseven(x) #: return x if x is even or fail
if x % 2 = 0 then return x
end

1
Task/Filter/J/filter-1.j Normal file
View file

@ -0,0 +1 @@
(#~ f) v

5
Task/Filter/J/filter-2.j Normal file
View file

@ -0,0 +1,5 @@
] v=: 20 ?@$ 100 NB. vector of 20 random integers between 0 and 99
63 92 51 92 39 15 43 89 36 69 40 16 23 2 29 91 57 43 55 22
v #~ -.2| v
92 92 36 40 16 2 22

3
Task/Filter/J/filter-3.j Normal file
View file

@ -0,0 +1,3 @@
isEven=: 0 = 2&| NB. verb testing for even numbers
(#~ isEven) v
92 92 36 40 16 2 22

9
Task/Filter/J/filter-4.j Normal file
View file

@ -0,0 +1,9 @@
select=: adverb def '(#~ u)'
isPrime=: 1&p:
isEven select v
92 92 36 40 16 2 22
isPrime select v
43 89 23 2 29 43
(isEven *. isPrime) select v
2

1
Task/Filter/J/filter-5.j Normal file
View file

@ -0,0 +1 @@
v=: isEven select v

View file

@ -0,0 +1,15 @@
fn filter<T>(anon array: [T], anon filter_function: fn(anon value: T) -> bool) throws -> [T] {
mut result: [T] = []
for value in array {
if filter_function(value) {
result.push(value)
}
}
return result
}
fn main() {
mut numbers: [i64] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let filtered = filter(numbers, fn(anon x: i64) -> bool => x % 2 == 0)
println("{}", filtered)
}

View file

@ -0,0 +1,6 @@
int[] array = {1, 2, 3, 4, 5 };
List<Integer> evensList = new ArrayList<Integer>();
for (int i: array) {
if (i % 2 == 0) evensList.add(i);
}
int[] evens = evensList.toArray(new int[0]);

View file

@ -0,0 +1,5 @@
public static <T> T[] filter(T[] input, Predicate<T> filterMethod) {
return Arrays.stream(input)
.filter(filterMethod)
.toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size));
}

View file

@ -0,0 +1,2 @@
Integer[] array = {1, 2, 3, 4, 5};
Integer[] result = filter(array, i -> (i % 2) == 0);

View file

@ -0,0 +1,2 @@
def array = [1..100];
def evens = array[n | n mod 2 == 0];

Some files were not shown because too many files have changed in this diff Show more