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.
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])
While the Perl solution is:
scalar( grep { $ints[$_] == $ints_sorted[$_] } ( 0 .. $#ints ) )
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
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.
- if
x == ythen remove both members - if
x != ythen 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
xandy. - If
xandyare different, add the difference between them to theintsarray, and sort it again
- Remove the two last values, called
- 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
Top comments (0)