DEV Community

Simon Green
Simon Green

Posted on

Unique Differences

Weekly Challenge 183

Challenge, My solutions

Back after a short break :)

Task 1: Unique Array

Task

You are given list of arrayrefs.

Write a script to remove the duplicate arrayrefs from the given list.

My solutions

The logic in the Python and Perl solutions is basically the same. For each item in the outer list, see if it has appeared earlier in the list. In Python comparing two lists works as expected. I don't believe there is a way to do this in Perl, so I wrote an function called same_array to see if two arrays are the same.

Examples

$ ./ch-1.py "[[1,2], [3,4], [5,6], [1,2]]"
[1, 2], [3, 4], [5, 6]

$ ./ch-1.py "[[9,1], [3,7], [2,5], [2,5]]"
[9, 1], [3, 7], [2, 5]
Enter fullscreen mode Exit fullscreen mode

Task 2: Date Difference

Task

You are given two dates, $date1 and $date2 in the format YYYY-MM-DD.

Write a script to find the difference between the given dates in terms on years and days only.

My solutions

This is a little tricky. Date math is never fun. So off the bat, I'll note this is not time zone aware. That really would only be an issue for the few countries that skipped a day in December 2011.

The basic logic goes as follows:

  1. Make sure that date2 is later than date1. The challenge does not mention in what order the date is specified.
  2. Subtract the difference in the calendar years between date2 and date1, and store it as years.
  3. If date2 is earlier in the year than date1, then subtract 1 from the years value.
  4. Calculate the number of days between date2 - $years year(s) and date1. For Python, this is done using the dateutils module. In Perl, I use the Date::Calc module.
  5. Print the result. I'm having a bit of a brain fart on how to do this the correct way. I'm sure after I submit my pull request, I'll figure this out :)

Examples

$ ./ch-2.py 2019-02-10 2022-11-01
3 years 264 days

$ ./ch-2.py 2020-09-15 2022-03-29
1 year 195 days

$ ./ch-2.py 2019-12-31 2020-01-01
1 day

$ ./ch-2.py 2019-12-31 2019-12-01
30 days
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)