The weekly challenge 222 - Task 1: Matching Members

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-222/#TASK1
 3 #
 4 # Task 1: Matching Members
 5 # ========================
 6 #
 7 # You are given a list of positive integers, @ints.
 8 #
 9 # Write a script to find the total matching members after sorting the list
10 # increasing order.
11 #
12 ## Example 1
13 ## Input: @ints = (1, 1, 4, 2, 1, 3)
14 ## Output: 3
15 ##
16 ## Original list: (1, 1, 4, 2, 1, 2)
17 ## Sorted list  : (1, 1, 1, 2, 3, 4)
18 ##
19 ## Compare the two lists, we found 3 matching members (1, 1, 2).
20 #
21 ## Example 2
22 ##
23 ## Input: @ints = (5, 1, 2, 3, 4)
24 ## Output: 0
25 ##
26 ## Original list: (5, 1, 2, 3, 4)
27 ## Sorted list  : (1, 2, 3, 4, 5)
28 ##
29 ## Compare the two lists, we found 0 matching members.
30 #
31 ## Example 3
32 ##
33 ## Input: @ints = (1, 2, 3, 4, 5)
34 ## Output: 5
35 ##
36 ## Original list: (1, 2, 3, 4, 5)
37 ## Sorted list  : (1, 2, 3, 4, 5)
38 ##
39 ## Compare the two lists, we found 5 matching members.
40 #
41 ############################################################
42 ##
43 ## discussion
44 ##
45 ############################################################
46 #
47 # create a sorted version of the list and compare one by one
48 
49 use strict;
50 use warnings;
51 
52 matching_members(1, 1, 4, 2, 1, 3);
53 matching_members(5, 1, 2, 3, 4);
54 matching_members(1, 2, 3, 4, 5);
55 
56 sub matching_members {
57    my @ints = @_;
58    print "Input: (" . join(", ", @ints) . ")\n";
59    my @sorted = sort { $a <=> $b } @ints;
60    my $result = 0;
61    foreach my $index (0..$#ints) {
62       $result++ if $ints[$index] == $sorted[$index];
63    }
64    print "Output: $result\n";
65 }
66