Filter: Difference between revisions
Content added Content deleted
No edit summary |
(Properly ordering the languages) |
||
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 |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
==[[C]]== |
==[[C]]== |
||
Line 67: | Line 46: | ||
foreach( int i in evens ) |
foreach( int i in evens ) |
||
System.Console.WriteLine( i.ToString() ); |
System.Console.WriteLine( i.ToString() ); |
||
⚫ | |||
⚫ | |||
⚫ | |||
==[[Java]]== |
==[[Java]]== |
||
Line 75: | Line 58: | ||
} |
} |
||
int[] evens = evensList.toArray(new int[0]); |
int[] evens = evensList.toArray(new int[0]); |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ |
Revision as of 22:04, 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
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