Price fraction: Difference between revisions

→‎{{header|Perl 6}}: Clean up the parsing solution
(→‎{{header|Perl 6}}: reverse the order of the three solutions)
(→‎{{header|Perl 6}}: Clean up the parsing solution)
Line 2,129:
}</lang>
 
If we expect to rescale many prices, a better approach would be to build a look-up table using an array of 101 entries.
Memory is cheap, and array lookupindexing is blazing fast.
 
<lang perl6>my @price = map *.value, flat
Line 2,156:
 
while prompt("value: ") -> $value {
say @price[ $value * 100 ] // "Out of range";
}</lang>
 
We can also build this same look-up array by parsing the table as formatted in the task description:
{{works with|rakudo|2015-10-20}}
 
{{works with|rakudo|2015-10-202016.07}}
<lang perl6>my $table = q:to/END/;
>= 0.00 < 0.06 := 0.10
Line 2,183 ⟶ 2,185:
END
 
my $value = 0.44@price;
 
for $table.lines -> $line {
say price($value);
$line ~~ /:s '>=' \s+ (\S+) \s+ '<' \s+ (\S+) \s+ ':=' \s+ (\S+)/;
@price[$0*100 ..^ $1*100] »=» +$2;
}
 
subwhile priceprompt($"value: ") -> $value {
say @price[$value * 100] // "Out of range";
{
for $table.lines -> $line {
$line ~~ / '>=' \s+ (\S+) \s+ '<' \s+ (\S+) \s+ ':=' \s+ (\S+)/;
return $2 if $0 <= $value < $1;
}
fail "Out of range";
}</lang>
 
Anonymous user