perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 340 - Task 2: Ascending Numbers

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-340/#TASK2
 3 #
 4 # Task 2: Ascending Numbers
 5 # =========================
 6 #
 7 # You are given a string, $str, is a list of tokens separated by a single
 8 # space. Every token is either a positive number consisting of digits 0-9 with
 9 # no leading zeros, or a word consisting of lowercase English letters.
10 #
11 # Write a script to check if all the numbers in the given string are strictly
12 # increasing from left to right.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "The cat has 3 kittens 7 toys 10 beds"
17 ## Output: true
18 ##
19 ## Numbers 3, 7, 10 - strictly increasing.
20 #
21 #
22 ## Example 2
23 ##
24 ## Input: $str = 'Alice bought 5 apples 2 oranges 9 bananas'
25 ## Output: false
26 #
27 #
28 ## Example 3
29 ##
30 ## Input: $str = 'I ran 1 mile 2 days 3 weeks 4 months'
31 ## Output: true
32 #
33 #
34 ## Example 4
35 ##
36 ## Input: $str = 'Bob has 10 cars 10 bikes'
37 ## Output: false
38 #
39 #
40 ## Example 5
41 ##
42 ## Input: $str = 'Zero is 0 one is 1 two is 2'
43 ## Output: true
44 #
45 ############################################################
46 ##
47 ## discussion
48 ##
49 ############################################################
50 #
51 # We collect all numbers in an array. Then we just start at the
52 # beginning and check if each one is less than or equal than the
53 # previous one: If it is, we can return false. In the end, we can
54 # return true as all numbers were bigger than the previous one.
55 
56 use v5.36;
57 
58 ascending_numbers("The cat has 3 kittens 7 toys 10 beds");
59 ascending_numbers('Alice bought 5 apples 2 oranges 9 bananas');
60 ascending_numbers('I ran 1 mile 2 days 3 weeks 4 months');
61 ascending_numbers('Bob has 10 cars 10 bikes');
62 ascending_numbers('Zero is 0 one is 1 two is 2');
63 
64 sub ascending_numbers($str) {
65     say "Input: $str";
66     my @numbers = grep { /^[0-9]+$/ } split / /, $str;
67     my $start = -1;
68     my $result = "true";
69     foreach my $n (@numbers) {
70         if($n <=  $start) {
71             $result = "false";
72             last;
73         }
74         $start = $n;
75     }
76     say "Output: $result";
77 }