Jump to content

Greatest subsequential sum: Difference between revisions

m
→‎{{header|Perl 6}}: Modernize; no longer need to work around bug
(added kotlin)
m (→‎{{header|Perl 6}}: Modernize; no longer need to work around bug)
Line 2,101:
{{trans|Python}}
 
{{works with|Rakudo|#21 "Seattle"2016.12}}
 
<lang perl6>sub maxsubseqmax-subseq (*@a) {
my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0;
for @a.kv -> $i, $x {
Line 2,120:
 
For each starting position, we calculate all the subsets starting at that position.
They are combined with the best subset ($max_subsetmax-subset) from previous loops, to form (@subsets).
The best of those @subsets is saved at the new $max_subsetmax-subset.
 
Consuming the array (.shift) allows us to skip tracking the starting point; it is always 0.
 
The empty sequence is used to initialize $max_subsetmax-subset, which fufillsfulfils the "all negative" requirement of the problem.
 
<lang perl6>sub max_submax-seqsubseq ( *@a ) {
Note that once the triangular comma bug is resolved, the inner-loop subset calculation line can be shortened to "my @subsets = [\,] @a;".
<lang perl6>sub max_sub-seq ( *@a ) {
 
my $max_subsetmax-subset = []();
while @a {
my @subsets = @a.keys.map: { [\,] @a[0..$_] ] };
@subsets.push(: $max_subset)max-subset;
$max_subsetmax-subset = @subsets.max: { [+] .list };
@a.shift;
}
 
return $max_subsetmax-subset;
}
 
max_submax-seqsubseq( -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ).perl.say;
max_submax-seqsubseq( -2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1 ).perl.say;
max_submax-seqsubseq( -2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1 ).perl.say;</lang>
 
{{out}}
<pre>
[(3, 5, 6, -2, -1, 4])
[(3, 5, 6, -1, 4])
[]()</pre>
 
=={{header|Phix}}==
10,351

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.