Filter: Difference between revisions
Content added Content deleted
No edit summary |
(Added AppleScript version) |
||
Line 2: | Line 2: | ||
Select certain elements from an Array into a new Array in a generic way. E.g., select all even numbers from an Array |
Select certain elements from an Array into a new Array in a generic way. E.g., select all even numbers from an Array |
||
==[[AppleScript]]== |
|||
[[Category:AppleScript]] |
|||
set array to {1, 2, 3, 4, 5} |
|||
set evens to {} |
|||
repeat with i in array |
|||
if (i mod 2 = 0) then set evens to evens & i |
|||
end repeat |
|||
==[[C]]== |
==[[C]]== |
Revision as of 04:22, 24 January 2007
Filter
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Select certain elements from an Array into a new Array in a generic way. E.g., select all even numbers from an Array
AppleScript
set array to {1, 2, 3, 4, 5} set evens to {} repeat with i in array if (i mod 2 = 0) then set evens to evens & i end repeat
C
int arr[5] = {1,2,3,4,5}; int *result; int memoryReqd = 0,length = sizeof(arr)/sizeof(arr[0]), i,j; for (i=0; i<length; i++) { if(0 == arr[i]%2) { memoryReqd++; } } result = (int*)malloc(memoryReqd*sizeof(int)); for(i=0,j=0; i<length; i++) { if(0 == arr[i]%2) { result[j++]=arr[i]; } }
// Test our resultant array for(i=0; i<memoryReqd; i++) { printf("%d\n",result[i]); }
C#
// .NET 1.x solution 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() );
// .NET 2.0 solution 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() );
Haskell
ary = [1..10] evens = [ x | x <- ary, even x ]
Java
int[] array = new int[] {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]);
Perl
my @list = (1, 2, 3, 4, 5, 6); my @even = grep { 0 == $_%2; } @list;
Python
values = range(10) evens = [x for x in values if x % 2 == 0]
Ruby
ary = [1,2,3,4,5,6] even_ary = ary.select{|el|el%2==0} # => [2, 4, 6]
Standard ML
val ary = [1,2,3,4,5,6]; List.filter (fn x => x mod 2 = 0) ary