DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 131

Challenge, My solutions

TASK #1 › Consecutive Arrays

Task

Submitted by: Mark Anderson

You are given a sorted list of unique positive integers.

Write a script to return list of arrays where the arrays are consecutive integers.

My solution

This is pretty straight forward, so doesn't need much explanation. Even though the task says the list is ordered and unique, I do this anyway. You never know what input someone will provide!

I seed the @output array with the first number. Then then work through each number removing it from the array. If that number is one more than the last number in the last array of @output, I add the value to the existing row. If it is not, this means it is a new sequence, so add a new row to the array.

I then use map to display the result in the requested format.

Examples

 ./ch-1.pl 1 2 3 6 7 8 9
([1, 2, 3], [6, 7, 8, 9])

$ ./ch-1.pl 11 12 14 17 18 19
([11, 12], [14], [17, 18, 19])

$ ./ch-1.pl 2 4 6 8
([2], [4], [6], [8])

$ ./ch-1.pl 1 2 3 4 5
([1, 2, 3, 4, 5])
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Find Pairs

Task

Submitted by: Yary

You are given a string of delimiter pairs and a string to search.

Write a script to return two strings, the first with any characters matching the “opening character” set, the second with any matching the “closing character” set.

My solution

There would be a couple of way to tackle this, and my choice is based largely on the output in the examples. For this I take the first string (the delimiter parts) and work on it two characters at a time adding them to the $open and $close string. If the character is not an alphanumeric character, I escape it with a back quote. perlre states "Unlike some other regular expression languages, there are no backslashed symbols that aren't alphanumeric. So anything that looks like \\, \(, \), \[, \], \{, or \} is always interpreted as a literal character, not a metacharacter"

I then use this regexp string (wrapped in [^ and ]) to remove the characters that don't match the pattern and display the results.

Examples



$ ./ch-2.pl '""[]()' '"I like (parens) and the Apple ][+" they said.'
"(["
")]"

$ ./ch-2.pl '**//<>' '/* This is a comment (in some languages) */ <could be a tag>'
/**/<
/**/>
Enter fullscreen mode Exit fullscreen mode

Discussion (0)