1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-213/#TASK1
 3 #
 4 # Task 1: Fun Sort
 5 # ================
 6 #
 7 # You are given a list of positive integers.
 8 #
 9 # Write a script to sort the all even integers first then all odds in ascending order.
10 #
11 ## Example 1
12 ##
13 ## Input: @list = (1,2,3,4,5,6)
14 ## Output: (2,4,6,1,3,5)
15 #
16 ## Example 2
17 ##
18 ## Input: @list = (1,2)
19 ## Output: (2,1)
20 #
21 ## Example 3
22 ##
23 ## Input: @list = (1)
24 ## Output: (1)
25 #
26 ############################################################
27 ##
28 ## discussion
29 ##
30 ############################################################
31 #
32 # This just requires the right sort function. It has to sort
33 # even numbers first and odd numbers last, and inside those
34 # sort by size. The former we can get by comparing the
35 # numbers modulo 2, the latter by comparing the numbers
36 # directly, so the sort function becomes really short.
37 
38 use strict;
39 use warnings;
40 
41 fun_sort(1,2,3,4,5,6);
42 fun_sort(1,2);
43 fun_sort(1);
44 
45 sub fun_sort {
46    my @list = @_;
47    print "Input: (" . join(",", @list) . ")\n";
48    my @sorted_list = sort { ($a % 2) <=> ($b % 2)  ||  $a <=> $b } @list;
49    print "Output: (" . join(",", @sorted_list) . ")\n";
50 }