Logo

Programming-Idioms

Given an integer array a of size n, pass the first, third, fifth and seventh, ... up to the m th element to a routine foo which sets all these elements to 42.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
void Foo(out int element)
{
    element = 42;
}

for (int i = 0; i < m; i += 2)
{
    Foo(out a[i]);
}
import std.range;
void foo(Range)(Range r) {
	r.fill(42);
}

foo(a.indexed(iota(0,m,2)));
var a = List.filled(n,0);
foo(a.take(m).toList());
foo(List<int> a) {
  a.fillRange(0, a.length, 42);
}
! Caller:
  integer, dimension(n) :: a
  call foo(a(1:m:2))

! Callee:

  subroutine foo(a)
    integer, dimension(:), intent(inout) :: a
    a = 42
  end subroutine foo
void foo(int a[], int m) {
    for (int i = 1; i <= m; a[i] = 42, i = i + 2);
}
interface F { void set(int a[], int m); }
F f = (a, m) -> {
    for (int i = 1; i <= m; a[i] = 42, i = i + 2);
};
fun foo(a : IntArray, idx: IntProgression) = 
  idx.forEach{ a[it] = 42 }
foo(a, 0 .. (m-1) step 2)
uses Math;
procedure foo(var L: Integer);
begin
  L := 42;
end;

begin
  for i := 0 to Min(m, n-1) do
    if not odd(i) then foo(a[i]);
end.
$n=25;
$m=15;

$A[$n-1] = undef;         # autovivify @A to length $n

sub foo  {
    my ($aref, @i) = @_;
    @$aref[@i] = (42) x @i;
    return;
}

foo(\@A, grep { 0 == $_ % 2 } 0 .. $m);

use Data::Dumper;
print Dumper(@A);
use strict;
my $n = 25;
my $m = 16;

my $a = [ 0..$n-1 ];            # create list reference

sub foo  {
    my ($aref, @idx) = @_;      # unpack sub arguments
    foreach my $i ( @idx ) {
        $aref->[$i] = 42;       # dereference element using ->
    }
}

my @subarray;                   # create list
for ( my $i=0; $i < $m; $i += 2 ) {
    push @subarray, $a->[$i];   # dereference element using ->
}

foo($a, @subarray);             # pass list reference and list

print join ', ', @{ $a };       # deref
def foo(s: slice):
    global a
    m = (s.stop - 1) - s.start
    a[s] = [42] * ((m // s.step) + 1)
foo(slice(0, m + 1, 2))
def foo(data, r):
    for i in r: 
        data[i] = 42

foo(a, range(0, m+1, 2))
# @param a [Array<Integer>]
# 
# @return [Array<Integer>]
# 
def foo(a)
  a.fill(42)
end

foo(arry.select(&:odd?))

# For older versions of ruby:
# foo(arry.select { |x| x.odd? })
fn foo(el: &mut i32) {
    *el = 42;
}
a.iter_mut().take(m).step_by(2).for_each(foo);
Imports System
Sub Foo(ByRef element As Integer)
    element = 42
End Sub

' Statements in caller:
For i = 0 To m - 1 Step 2
    Foo(a(i))
Next