Peter
Peter Campbell Smith

Evens go first and
untangling the route

Weekly challenge 213 — 17 April 2023

Week 213: 17 Apr 2023

Task 1

Task — Fun sort

You are given a list of positive integers. Write a script to sort the all even integers first then all odds in ascending order.

Analysis

Perhaps not the most efficient way to do it, but:

  • add a million to all the odd numbers,
  • sort the array,
  • subtract a million from the numbers >= a million.

... and that works provided none of the integers is >= a million.

Try it 


Example: 1, 2, 3, 4, 5, 6

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-04-17
use utf8;     # Week 213 task 1 - Fun sort
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

my ($j, @list);

fun_sort([1, 2, 3, 4, 5, 6]);
fun_sort([1, 2]);
fun_sort([1]);

# longer example
for $j (1 .. 50) {
    push @list, int(rand(50) + 1);
}
fun_sort(\@list);

sub fun_sort {
    
    # add a million to all the odd numbers, then
    # sort and then subtract a million from the odd ones
    my @list = map {$_ & 1 ? $_ - 1000000 : $_} 
        sort {$a <=> $b} 
        map {$_ & 1 ? $_ + 1000000 : $_} @{$_[0]};
    
    say qq[\nInput:  \@list = (] . join(', ', @{$_[0]}) . q[)];
    say qq[Output: \@list = (] . join(', ', @list) . q[)];
}

Output


Input:  @list = (1, 2, 3, 4, 5, 6)
Output: @list = (2, 4, 6, 1, 3, 5)

Input:  @list = (1, 2)
Output: @list = (2, 1)

Input:  @list = (1)
Output: @list = (1)

Input:  @list = (11, 28, 14, 7, 38, 48, 43, 14, 34, 42, 47, 22, 47, 32, 36, 36, 14, 2, 9, 29, 40, 11, 20, 23, 12, 15, 40, 12, 43, 35, 39, 43, 27, 37, 29, 4, 41, 49, 9, 25, 27, 39, 5, 17, 21, 7, 17, 10, 39, 42)
Output: @list = (2, 4, 10, 12, 12, 14, 14, 14, 20, 22, 28, 32, 34, 36, 36, 38, 40, 40, 42, 42, 48, 5, 7, 7, 9, 9, 11, 11, 15, 17, 17, 21, 23, 25, 27, 27, 29, 29, 35, 37, 39, 39, 39, 41, 43, 43, 43, 47, 47, 49)

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain