DEV Community

Discussion on: Daily Coding Puzzles - Nov 11th - Nov 16th

Collapse
 
choroba profile image
E. Choroba

Perl solution. Passes all the tests on HackerRank.

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

{   package Queue;

    use enum qw( LIFO FIFO );

    sub new  { bless [[], []], shift }
    sub Push { push @{ $_[0][LIFO] }, $_[1]; }
    sub Pop  { @{ $_[0][FIFO] } or $_[0]->_restack; pop @{ $_[0][FIFO] }; }
    sub Peek { @{ $_[0][FIFO] } or $_[0]->_restack; say $_[0][FIFO][-1]; }
    sub _restack {
        push @{ $_[0][FIFO] }, pop @{ $_[0][LIFO] } while @{ $_[0][LIFO] };
    }
}

my %dispatch = (
    1 => 'Push',
    2 => 'Pop',
    3 => 'Peek',
);

my $q = 'Queue'->new;

<>;  # skip the 1st line.
while (<>) {
    my ($operation, $argument) = split;
    $q->${\$dispatch{$operation}}($argument);
}