Peter
Peter Campbell Smith

Sorted text and hot days

Weekly challenge 181 — 5 September 2022

Week 181 - 5 Sep 2022

Task 1

Task — Sentence order

You are given a paragraph. Write a script to order each sentence alphanumerically and print the whole paragraph.

Examples


Example
Input:
    All he could think about was how it would all end. There was
    still a bit of uncertainty in the equation, but the basics
    were there for anyone to see. No matter how much he tried to
    see the positive, it wasn't anywhere to be seen. The end was
    coming and it wasn't going to be pretty.
Output:
    about All all could end he how it think was would. a anyone
    basics bit but equation, for in of see still the the There
    there to uncertainty was were. anywhere be he how it matter
    much No positive, see seen the to to tried wasn't. and be
    coming end going it pretty The to was wasn't.

Analysis

Why would you ever want to do this? Only Mohammad knows. The obvious logic, and the way I did it was:

  • Split the text into sentences
  • Split each sentence into an array of words
  • Sort the array
  • Print it out

In order to match Mohammad's sample output I limited the length of each output line to 60 chars, which adds a couple of lines to the script.

Try it 

Try running the script with any input:



example: You are given a paragraph. Write a script to order each sentence alphanumerically and print the whole paragraph.

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-09-05
# PWC 181 task 1

use v5.26;
use utf8;
use warnings;

my ($input, $sentence, @words, $line_length, $word, $paragraph);

$input = q[All he could think about was how it would all end. There was
    still a bit of uncertainty in the equation, but the basics
    were there for anyone to see. No matter how much he tried to
    see the positive, it wasn't anywhere to be seen. The end was
    coming and it wasn't going to be pretty.];
    
# loop over sentences
$line_length = 0;
while ($input =~ m|(.+?)\.|gs) {
    $sentence = $1;
    
    # extract words in next sentence and sort them
    @words = ();
    while ($sentence =~ m|([a-z']+)|gi) {
        push(@words, $1);
    }
    @words = sort {lc($a) cmp lc($b)} @words;
    
    # output the words with line breaks to keep lines under 60 characters
    for $word (@words) {
        if ($line_length + length($word) > 59) {
            $paragraph .= qq[\n];
            $line_length = 0;
        }           
        $paragraph .= $word . ' ';
        $line_length += length($word) + 1;
    }
    $paragraph =~ s| $|. |;
}

# and print the result
say $paragraph;
    

Output

about All all could end he how it think was would. a anyone 
basics bit but equation for in of see still the the There 
there to uncertainty was were. anywhere be he how it matter 
much No positive see seen the to to tried wasn't. and be 
coming end going it pretty The to was wasn't.