DEV Community

Simon Green
Simon Green

Posted on

3 2

Weekly Challenge 083

Challenge 083

TASK #1 › Words Length

This is relatively straight forward task. I take the string and use the regex /^\s*\S+?\s+(.*)\s+\S+\s*$/ to strip out the first and last words (and any leading or trailing white space). I then strip out white-space from the string, and return the length.

Examples

» ./ch-1.pl "The Weekly Challenge"
6

» ./ch-1.pl "The purpose of our lives is to be happy"
23
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Flip Array

This is another task where I will be interested to see the other solutions Team PWC members offer up. Abigail made an excellent post last week explaining the number theory behind her work.

Firstly I've retrieve the values, and verified they are all positive numbers.

I then go through a loop from 0 to 2n-2 (2n-1 is all negative, and thus won't provide a non-negative sum). If the binary bit is true, then I flip the number. For example if the numbers are 2 4 6 8 and the loop count is 5 (binary 101), then the combination I am using is 2 -4 6 -8.

Once I have the combination in the loop, I sum the numbers. If the sum is less than 0, I proceed to the next iteration. If the solution is better than any previous numbers (either a lower sum, or the same sum with a lower number of flipped values), then I record it.

Once the loop is complete, I then present the result.

This solution requires 2n-1 calculations. So even for 10 numbers, there is only 1023 iterations through the main loop. There may be more efficient ways to solve this challenge. I guess I'll find out during this week.

Examples

» ./ch-2.pl 3 10 8
RESULT IS: 1 (-10 3 8)

» ./ch-2.pl 12 10 2
RESULT IS: 1 (-12 2 10)
Enter fullscreen mode Exit fullscreen mode

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay