Peter
Peter Campbell Smith

Aesthetics and a
fast-growing sequence

Weekly challenge 173 — 11 July 2022

Week 173 - 11 Jul 2022

Task 1

Task — Esthetic number

You are given a positive integer, $n. Write a script to find out if the given number is an esthetic number. An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.

Examples


Example 1:
5456 is an esthetic number as |5 - 4| = |4 - 5| = 
   |5 - 6| = 1

Example 2:
120 is not an esthetic number as |1 - 2| != |2 - 0| != 1

Analysis

We may deduce:

  • Esthetic numbers were named by an American
  • The digits may differ by ±1

There seems little option but to start at one end and compare each digit to the next one. The evidence from past challenges is that substr() is faster than pulling them out with a regular expression, so let's use that.

We can comply with the instruction by declaring a number un(a)esthetic as soon as we find two consecutive digits which do not differ by 1. If we treat the given number as a string, we don't need to worry about exceeding Perl's maximum integer: we're only doing arithmetic on 0 .. 9.

Try it 

Try running the script with any input:



example: 123454321

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-07-11
# PWC 173 task 1

use v5.28;
use strict;
use warnings;
use utf8;
binmode(STDOUT, ':utf8');

my (@tests, $test, $not, $j, $digit, $next, $as);

@tests = (1234, 1235, 123345, 7654, 3210, 8642, 1345, 9090, 11111,
    '7654567898765432123456789', '7654567898765432123456788');

# loop over tests
for $test (@tests) {
    
    # loop over 2nd to last digits, comparing them with the preceding one
    $digit = substr($test, 0, 1);
    for $j (1 .. length($test) - 1) {
        $next = substr($test, $j, 1);
        
        # test for being esthetic and quit if not
        $not = abs($digit - $next) == 1 ? '' : ' not';
        last if $not;       
        $digit = $next;
    }
    
    # report result
    $as = $not ? qq[ as |$digit - $next| != 1] : '';
    say qq[\nInput:  $test];
    say qq[Output: ... is$not an esthetic number$as];
}

Output


Input:  1234
Output: ... is an esthetic number

Input:  1235
Output: ... is not an esthetic number as |3 - 5| != 1

Input:  123345
Output: ... is not an esthetic number as |3 - 3| != 1

Input:  7654
Output: ... is an esthetic number

Input:  3210
Output: ... is an esthetic number

Input:  8642
Output: ... is not an esthetic number as |8 - 6| != 1

Input:  1345
Output: ... is not an esthetic number as |1 - 3| != 1

Input:  9090
Output: ... is not an esthetic number as |9 - 0| != 1

Input:  11111
Output: ... is not an esthetic number as |1 - 1| != 1

Input:  7654567898765432123456789
Output: ... is an esthetic number

Input:  7654567898765432123456788
Output: ... is not an esthetic number as |8 - 8| != 1