RabbitFarm

2021-01-17

Perl Weekly Challenge 095

The examples used here are from the weekly challenge problem statement and demonstrate the working solution.

Part 1

You are given a number $N. Write a script to figure out if the given number is a Palindrome. Print 1 if true, otherwise 0.

Solution


use strict;
use warnings;

use boolean;

sub is_palindrome{
    my($n) = @_;
    return false if $n < 0;
    my @digits = split(//, $n);
    if(@digits % 2 == 0){
        do{
            my $a = shift @digits;
            my $b = pop @digits;
            return false if $a != $b;
        }while(@digits);
        return true;
    }
    while(@digits != 1){
        my $a = shift @digits;
        my $b = pop @digits;
        return false if $a != $b;
    };
    return true;
}

MAIN:{
    print is_palindrome(1221);
    print "\n";
    print is_palindrome(-101);
    print "\n";
    print is_palindrome(90);
    print "\n";
}

Sample Run


$ perl perl/ch-1.pl
1
0
0

Notes

One assumption is made and that is that the input is a valid integer.

My approach here is straightforward iteration and matches what one might do manually: work inwards from both ends and if at any point there is not a match of the two elements being compared then return false. If we make it all the way to the middle then return true. Here the middle is either an empty array, in the case of an even number of elements or, in the case of an odd number of elements, an array of length 1.

The case of a single digit has no special handling, if the number has an odd number of digits but that odd number happens to be 1 then the loop is not entered and we just return true.

Part 2

Write a script to demonstrate Stack operations.

Solution


use strict;
use warnings;

use Stack;

my $stack = new Stack();
$stack->push(2);
$stack->push(-1);
$stack->push(0);
$stack->pop;       
print $stack->top . "\n"; 
$stack->push(0);
print $stack->min . "\n"; 

The Stack module used is of my own making. The next listing is that code.


use strict;
use warnings;
package Stack{
    use boolean;
    use Class::Struct;

    struct(
        data => q/@/
    );

    sub push{
        my($self, $n) = @_;
        push @{$self->data()}, $n;
    }

    sub pop{
        my($self, $n) = @_;
        pop @{$self->data()};
    }

    sub top{
        my($self, $n) = @_;
        @{$self->data()}[@{$self->data()} - 1];
    }
    
    sub min{
        my($self, $n) = @_;
        my @sorted = sort {$a <=> $b} @{$self->data()};
        return $sorted[0];
    }
    true;
}  

Sample Run


$ perl -Iperl perl/ch-2.pl
-1
-1

Notes

Like last week’s LinkedList module I use Class::Struct to create the Stack module.

Class::Struct creates accessors for all the class variables automatically. In this way, by calling $self->data(), we get a reference to the internal array data and perform the required Stack operations.

posted at: 14:49 by: Adam Russell | path: /perl | permanent link to this entry