blob: 3a302e61978bd6670229c1f8ef9708a60a877f32 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
#!/usr/bin/env perl
# Task 2: Ascending Numbers
# Submitted by: Mohammad Sajid Anwar
#
# You are given a string, $str, is a list of tokens separated by a single space. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.
# Write a script to check if all the numbers in the given string are strictly increasing from left to right.
#
# Example 1
# Input: $str = "The cat has 3 kittens 7 toys 10 beds"
# Output: true
#
# Numbers 3, 7, 10 - strictly increasing.
#
# Example 2
# Input: $str = 'Alice bought 5 apples 2 oranges 9 bananas'
# Output: false
#
# Example 3
# Input: $str = 'I ran 1 mile 2 days 3 weeks 4 months'
# Output: true
#
# Example 4
# Input: $str = 'Bob has 10 cars 10 bikes'
# Output: false
#
# Example 5
# Input: $str = 'Zero is 0 one is 1 two is 2'
# Output: true
use strict;
use warnings;
my $str = "The cat has 3 kittens 7 toys 10 beds";
ascending_numbers( $str );
$str = 'Alice bought 5 apples 2 oranges 9 bananas';
ascending_numbers( $str );
$str = 'I ran 1 mile 2 days 3 weeks 4 months';
ascending_numbers( $str );
$str = 'Bob has 10 cars 10 bikes';
ascending_numbers( $str );
$str = 'Zero is 0 one is 1 two is 2';
ascending_numbers( $str );
exit 0;
sub ascending_numbers {
my $str = shift;
my @numbers = ($str =~ /\d+/g);
my $sorted = 1;
if (scalar @numbers > 0) {
my $curr = shift @numbers;
foreach $_ (@numbers) {
if ($curr >= $_) {
$sorted = 0;
last;
}
$curr = $_
}
}
printf "'%s' -> %s\n", $str, $sorted
? 'true'
: 'false';
}
|