Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find correct min / max values of a list in Perl 6

Tags:

raku

New to Perl6, trying to figure out what I'm doing wrong here. The problem is a simple checksum that takes the difference of the max and min values for each row in the csv

The max and min values it returns are completely wrong. For the first row in the csv, it returns the max as 71, and the min as 104, which is incorrect.

Here's the link to the repo for reference, and the link to the corresponding problem.

#!/usr/bin/env perl6

use Text::CSV;

sub checksum {
    my $sum = 0;
    my @data = csv(in => "input.csv");
    for @data -> @value {
        $sum += (max @value) - (min @value);
    }
    say $sum;
}

checksum
like image 443
Jake Meyer Avatar asked Dec 14 '22 19:12

Jake Meyer


1 Answers

I assume your input contains numbers, but since CSV is a text format, the input is being read in as strings. min and max are operating based on string sorting, so max("4", "10") is 4 but max("04", "10") is 10. To solve this, you can either cast each element to Numeric (int, floating point, etc.) before you get the min/max:

@input.map(*.Numeric).max

or pass a conversion function to min and max so each element is parsed as a number as it's compared:

@input.max(*.Numeric)

The first solution is better for your case, since the second solution is an ephemeral conversion, converting internally but still returning a string. Final note: in normal code I would write +* or { +$_ } to mean "treat X as a number", but in this case I prefer being explicit: .Numeric.

like image 54
piojo Avatar answered Dec 16 '22 08:12

piojo