DEV Community

Simon Green
Simon Green

Posted on

All the ducks. Two twenty two

Weekly Challenge 222

Sorry for no post last week. I was planning to do it while on holiday in the beautiful Coffs Harbour in Northern NSW, Australia. Unfortunately, I got called up on Saturday evening to debug a production issue at work.

challenge, My solution

Task 1: Matching Members

Task

You are given a list of positive integers, @ints.

Write a script to find the total matching members after sorting the list increasing order.

My solution

This is relatively straight forward, I hope. Create a sorted list ints_sorted, and then use list comprehension (Python) and grep (Perl) to count the number of values that are same.

In python we use:

sum(1 for x in range(len(ints)) if ints[x] == ints_sorted[x])
Enter fullscreen mode Exit fullscreen mode

While the Perl solution is:

scalar( grep { $ints[$_] == $ints_sorted[$_] } ( 0 .. $#ints ) )
Enter fullscreen mode Exit fullscreen mode

They both do the same thing. Count from 0 to one less than the length of the array, and compare the value at each position of the list. The pythonic way is to use sum(1.... In Perl, scalar returns in the number of items in a list, while grep will eliminate items that aren't equal.

Examples

$ ./ch-1.py 1 1 4 2 1 3
3

$ ./ch-1.py 5 1 2 3 4
0

$ ./ch-1.py 1 2 3 4 5
5
Enter fullscreen mode Exit fullscreen mode

Task 2: Last Member

Task

You are given an array of positive integers, @ints.

Write a script to find the last member if found otherwise return 0. Each turn pick 2 biggest members (x, y) then decide based on the following conditions, continue this until you are left with 1 member or none.

  1. if x == y then remove both members
  2. if x != y then remove both members and add new member (y-x)

My solution

These are the steps I took

  • Sort the list (array in Perl) ints.
  • Loop while there is more than one item in the list
    • Remove the two last values, called x and y.
    • If x and y are different, add the difference between them to the ints array, and sort it again
  • Print the last number if there is one, otherwise print 0.

Examples

$ ./ch-2.py 2 7 4 1 8 1
1

$ ./ch-2.py 1
1

$ ./ch-2.py 1 1
0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)