Peter
Peter Campbell Smith

Any more fares, please?

Weekly challenge 219 — 29 May 2023

Week 219: 29 May 2023

Task 1

Task — Sorted squares

You are given a list of numbers. Write a script to square each number in the list and return the sorted list in increasing order.

Analysis

I've said before that I tend to avoid one-liners as they can be hard for anyone following on to understand, but I make an exeption if they are reasonably simple. And I reckon this one is simple: use a map to square the members of the supplied list, and then sort the list.

Try it 

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

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-05-29
use utf8;     # Week 219 task 1 - Sorted squares
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

sorted_squares(-2, -1, 0, 3, 4);
sorted_squares(5, -4, -1, 3, 6);
sorted_squares(5.3, -77.62, 11, 0, 3.14159, 2.1728);

sub sorted_squares {

    # square the list items and then sort them
    say qq[\nInput:  \@list = (] . join(', ', @_) . ')';
    say qq[Output: (] . join (', ', sort { $a <=> $b } map { $_ ** 2 } @_) . ')';
}


Output


Input:  @list = (-2, -1, 0, 3, 4)
Output: (0, 1, 4, 9, 16)

Input:  @list = (5, -4, -1, 3, 6)
Output: (1, 9, 16, 25, 36)

Input:  @list = (5.3, -77.62, 11, 0, 3.14159, 2.1728)
Output: (0, 4.72105984, 9.8695877281, 28.09, 121, 6024.8644)

 

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