Rafraîchissoir

By Shahed Nooshmand

Perl Weekly Challenge: week 61

Task #1

Given a list of 4 or more numbers, write a script to find the contiguous sublist that has the maximum product. The length of the sublist is irrelevant; your job is to maximize the product.

Here you go:

raku -e 'say (for ^$_ X ^$_ -> (\a, \b) { $_ => [*] |$_ given $_[a..b] }).max(*.value) given <2 5 -1 3>'

It’s very simple. The trick is really in the $_s (if that’s how you pluralise $_). Just for fun, I’m gonna replace each $_ with the value it holds.

raku -e 'say (for ^<2 5 -1 3> X ^<2 5 -1 3> -> (\a, \b) { <2 5 -1 3>[a..b] => [*] |<2 5 -1 3>[a..b] }).max(*.value)'

Task #2

You are given a string containing only digits (0..9). The string should have between 4 and 12 digits.

Write a script to print every possible valid IPv4 address that can be made by partitioning the input string.

For the purpose of this challenge, a valid IPv4 address consists of four “octets” i.e. A, B, C and D, separated by dots (.).

Each octet must be between 0 and 255, and must not have any leading zeroes. (e.g., 0 is OK, but 01 is not.)

Here’s my solution:

raku -e '$_[0].join(".").say for "25525511135" ~~ m:ex«^ ( 0 || <[1..9]> \d* <?{ $/ ≤ 255 }> ) ** 4 $»;'

It may not seem like much, but it’s doing exactly what the problem says. The string of numbers is exhaustively matched against what the problem defines as a valid IPv4 address. The pattern tries different ways to partition the string into four numbers (note the ** 4), each of which is either 0, or a number whose leftmost digit is not 0 and which isn’t greater than 255. Each “octet” is captured in the same group 0, so the group is actually a list of octets which we then join using dots — and that’s our address.