DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 138

Challenge, My solutions

TASK #1 › Workdays

Task

You are given a year, $year in 4-digits form. Write a script to calculate the total number of workdays in the given year. For the task, we consider Monday - Friday as workdays.

My solution

This expands on last weeks task. Unlike last week, I'm taking a short cut by using the excellent Date::Calc module to calculate the day of week of January 1st, and whether it is a leap year.

With those two pieces of information, we can deduce the following facts (for all years after 1752):

  • January 1st to December 30th (or 29th in a leap year) will always be exactly 260 work days (52 weeks × 5 days).
  • December 31st (or 30th in a leap year) will be the same day of week as January 1st. Therefore is January 1st is a work day, we add one more work day for the 31st (or 30th in a leap year).
  • In a leap year, December 31st will be the day of week after January 1st. If January 1st is not a Friday or Saturday (meaning December 31st is not a Saturday or Sunday), we add an additional work day for December 31st.

Examples

 ./ch-1.pl 2020
262

$ ./ch-1.pl 2021
261
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Split Number

Task

You are given a perfect square.

Write a script to figure out if the square root the given number is same as sum of 2 or more splits of the given number.

My solution

I had two cracks at this as my first method worked in my head, but was harder to implement. It involved using a binary operator to decide whether to join two digits or put a plus sign in between them (thus resulting in 2length($n)-1 permutations).

In the end I went to use a recursive function, as I often do with these tasks. Like usual, I'll be interested to see how other Team PWC members tackled this challenge.

My recursive function is called _can_split and takes three values:

  1. The target we are trying to reach (the square root of the input)
  2. The numbers we have used so far (an array)
  3. The pool of digits remaining (starts with the provided number)

For each iteration, we take from 1 to the length of the pool digits from the pool and place them in an array, and call the subroutine again with the new remaining value. The exception is the first value, where we won't check the possibility of not splitting the numbers. This is because the task states that the number must be split two or more times.

Examples

$ ./ch-2.pl 81
1

$ ./ch-2.pl 9801
1

$ ./ch-2.pl 36
0

$ ./ch-2.pl 1
0

Enter fullscreen mode Exit fullscreen mode

Top comments (0)