This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
var a = List.filled(n,0);
foo(a.take(m).toList());
foo(List<int> a) {
a.fillRange(0, a.length, 42);
}
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
Less idiomatic implementation which modifies array a in place by defining a as a list reference and accessing its elements.
$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);
Perl list A is accessed in list context as @A and in scalar context as $A. Passing A as \@A turns A into a list reference, which is received in foo as $aref and accessed as a list slice using the @$aref[@i] syntax; @i on the rhs is the length of the sublist and x is the repeat operator. The empty return ensures we don't return the sublist and emphasizes that the caller should get results from arg1.
def foo(s):
global a
m = (s.stop - 1) - s.start
a[s] = [42] * ((m // s.step) + 1)
foo(slice(0, m + 1, 2))
The slice must be m < n.
# @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? })
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
a.Length is the size of a at run-time.
Requires m <= a.Length; the code does not verify this beforehand.
References to individual elements are passed to Foo().
Requires m <= a.Length; the code does not verify this beforehand.
References to individual elements are passed to Foo().