Rafraîchissoir

By Shahed Nooshmand

Perl Weekly Challenge: week 65

Task #1

You are given two positive numbers $N and $S.

Write a script to list all positive numbers having exactly $N digits where sum of all digits equals to $S.

Here’s one solution:

(10**($N-1)..^10**$N).grep(*.comb.sum == $S).say

Task #2

You are given a string $S. Write a script print all possible partitions that gives Palindrome. Return -1 if none found.

Please make sure, partition should not overlap. For example, for given string “abaab”, the partition “aba” and “baab” would not be valid, since they overlap.

Example 1

Input: $S = 'aabaab'
Ouput:
 There are 3 possible solutions.
 a) 'aabaa'
 b) 'aa', 'baab'
 c) 'aba'

I usually don’t include the examples since they’re irrelevant. This time, though, I am baffled. I seriously don’t understand the example.

I think the confusion lies in the definition of partition. A partition of a string is supposedly a group of non-overlapping, non-empty substrings of it that, if concatenated in order, make up the string. In the example, b is indeed, under this definition, a partition of $S. But a and c are only substrings. I really don’t get how those could be “possible solutions”.

Anyway, here’s my solution:

.values.map(~*).say for $S ~~ m:ex« ^ (\w+ <?{$/ eq $/.flip}>)* $ »

Given the example string, "aabaab", this is the result:

(aabaa b)
(aa baab)
(aa b aa b)
(aa b a a b)
(a aba a b)
(a a baab)
(a a b aa b)
(a a b a a b)

Seems alright to me.