The weekly challenge 228 - Task 2: Empty Array

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-228/#TASK2
 3 #
 4 # Task 2: Empty Array
 5 # ===================
 6 #
 7 # You are given an array of integers in which all elements are unique.
 8 #
 9 # Write a script to perform the following operations until the array is
10 # empty and return the total count of operations.
11 #
12 ## If the first element is the smallest then remove it otherwise move it to
13 ## the end.
14 #
15 ## Example 1
16 ##
17 ## Input: @int = (3, 4, 2)
18 ## Ouput: 5
19 ##
20 ## Operation 1: move 3 to the end: (4, 2, 3)
21 ## Operation 2: move 4 to the end: (2, 3, 4)
22 ## Operation 3: remove element 2: (3, 4)
23 ## Operation 4: remove element 3: (4)
24 ## Operation 5: remove element 4: ()
25 #
26 ## Example 2
27 ##
28 ## Input: @int = (1, 2, 3)
29 ## Ouput: 3
30 ##
31 ## Operation 1: remove element 1: (2, 3)
32 ## Operation 2: remove element 2: (3)
33 ## Operation 3: remove element 3: ()
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # As long as there are elements in the array, we take the first
42 # element. If it is the smallest element, we're done. Otherwise
43 # we add the element back at the end of the array. Just count
44 # the steps we're doing.
45 
46 use strict;
47 use warnings;
48 
49 empty_array(3, 4, 2);
50 empty_array(1, 2, 3);
51 
52 sub empty_array {
53    my @int = @_;
54    print "Input: (" . join(", ", @int) . ")\n";
55    my $steps = 0;
56    while(@int) {
57       $steps++;
58       my $min = min(@int);
59       my $first = shift @int;
60       if($min != $first) {
61          push @int, $first;
62       }
63    }
64    print "Output: $steps\n";
65 }
66 
67 sub min {
68    my @array = @_;
69    my $min = $array[0];
70    foreach my $elem (@array) {
71       $min = $elem if $elem < $min;
72    }
73    return $min;
74 }