The weekly challenge 307 - Task 1: Check Order
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-307/#TASK1 3 # 4 # Task 1: Check Order 5 # =================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to re-arrange the given array in an increasing order and 10 # return the indices where it differs from the original array. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (5, 2, 4, 3, 1) 15 ## Output: (0, 2, 3, 4) 16 ## 17 ## Before: (5, 2, 4, 3, 1) 18 ## After : (1, 2, 3, 4, 5) 19 ## 20 ## Difference at indices: (0, 2, 3, 4) 21 # 22 ## Example 2 23 ## 24 ## Input: @ints = (1, 2, 1, 1, 3) 25 ## Output: (1, 3) 26 ## 27 ## Before: (1, 2, 1, 1, 3) 28 ## After : (1, 1, 1, 2, 3) 29 ## 30 ## Difference at indices: (1, 3) 31 # 32 ## Example 3 33 ## 34 ## Input: @ints = (3, 1, 3, 2, 3) 35 ## Output: (0, 1, 3) 36 ## 37 ## Before: (3, 1, 3, 2, 3) 38 ## After : (1, 2, 3, 3, 3) 39 ## 40 ## Difference at indices: (0, 1, 3) 41 # 42 ############################################################ 43 ## 44 ## discussion 45 ## 46 ############################################################ 47 # 48 # Create the sorted array, then comapre the two arrays by index. 49 # Remember all positions where the two arrays differ. 50 51 use v5.36; 52 53 check_order(5, 2, 4, 3, 1); 54 check_order(1, 2, 1, 1, 3); 55 check_order(3, 1, 3, 2, 3); 56 57 sub check_order { 58 my @ints = @_; 59 say "Input: (" . join(", ", @ints) . ")"; 60 my @sorted = sort {$a<=>$b} @ints; 61 my @result = (); 62 foreach my $i (0..$#ints) { 63 push @result, $i if $ints[$i] != $sorted[$i]; 64 } 65 say "Output: (" . join(", ", @result) . ")"; 66 }