The weekly challenge 222 - Task 2: Last Member

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-222/#TASK2
 3 #
 4 # Task 2: Last Member
 5 # ===================
 6 #
 7 # You are given an array of positive integers, @ints.
 8 #
 9 # Write a script to find the last member if found otherwise return 0. Each turn
10 # pick 2 biggest members (x, y) then decide based on the following conditions,
11 # continue this until you are left with 1 member or none.
12 #
13 ###   a) if x == y then remove both members
14 #
15 ###   b) if x != y then remove both members and add new member (y-x)
16 #
17 ## Example 1:
18 ##
19 ## Input: @ints = (2, 7, 4, 1, 8, 1)
20 ## Output: 1
21 ##
22 ## Step 1: pick 7 and 8, we remove both and add new member 1 => (2, 4, 1, 1, 1).
23 ## Step 2: pick 2 and 4, we remove both and add new member 2 => (2, 1, 1, 1).
24 ## Step 3: pick 2 and 1, we remove both and add new member 1 => (1, 1, 1).
25 ## Step 4: pick 1 and 1, we remove both => (1).
26 #
27 ## Example 2:
28 ##
29 ## Input: @ints = (1)
30 ## Output: 1
31 #
32 ## Example 3:
33 ##
34 ## Input: @ints = (1, 1)
35 ## Output: 0
36 ##
37 ## Step 1: pick 1 and 1, we remove both and we left with none.
38 #
39 ############################################################
40 ##
41 ## discussion
42 ##
43 ############################################################
44 #
45 # Since in each step, we remove the two biggest members, we can
46 # also remove the first two members of the list sorted in descending
47 # order. This makes things a bit easier.
48 
49 use strict;
50 use warnings;
51 
52 last_member(2, 7, 4, 1, 8, 1);
53 last_member(1);
54 last_member(1, 1);
55 
56 sub last_member {
57    my @ints = @_;
58    print "Input: (" . join(", ", @ints) . ")\n";
59    my $count = scalar(@ints);
60    while($count > 1) {
61       my ($x, $y);
62       ($x, $y, @ints) = sort { $b <=> $a } @ints;
63       if($x > $y) {
64          push @ints, ($x - $y);
65       }
66       $count = scalar(@ints);
67    }
68    print "Output: $count\n";
69 }