Filter: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 67: | Line 67: | ||
foreach( int i in evens ) |
foreach( int i in evens ) |
||
System.Console.WriteLine( i.ToString() ); |
System.Console.WriteLine( i.ToString() ); |
||
==[[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]); |
Revision as of 21:55, 23 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
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
Haskell
ary = [1..10] evens = [ x | x <- ary, even x ]
Python
values = range(10) evens = [x for x in values if x % 2 == 0]
Perl
my @list = (1, 2, 3, 4, 5, 6); my @even = grep { 0 == $_%2; } @list;
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() );
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]);