diff options
| author | boblied <boblied@gmail.com> | 2022-12-27 07:36:12 -0600 |
|---|---|---|
| committer | boblied <boblied@gmail.com> | 2022-12-27 07:36:12 -0600 |
| commit | 50942dc9ae4f7cd0221aff1c8ed376fc575d56f3 (patch) | |
| tree | f792e11b0a5a892923a6cc22a8be4872bee325ae | |
| parent | 92ecd89aa4e88ab95c7b38c8d09b6f6a29856d7e (diff) | |
| download | perlweeklychallenge-club-50942dc9ae4f7cd0221aff1c8ed376fc575d56f3.tar.gz perlweeklychallenge-club-50942dc9ae4f7cd0221aff1c8ed376fc575d56f3.tar.bz2 perlweeklychallenge-club-50942dc9ae4f7cd0221aff1c8ed376fc575d56f3.zip | |
Week 197 task 1 bob-lied
| -rw-r--r-- | challenge-197/bob-lied/perl/ch-1.pl | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/challenge-197/bob-lied/perl/ch-1.pl b/challenge-197/bob-lied/perl/ch-1.pl new file mode 100644 index 0000000000..18153180a6 --- /dev/null +++ b/challenge-197/bob-lied/perl/ch-1.pl @@ -0,0 +1,48 @@ +#!/usr/bin/env perl +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# ch-1.pl +#============================================================================= +# Copyright (c) 2022, Bob Lied +#============================================================================= +# Perl Weekly Challenge Week 197, Task 1 Move Zero +# +# You are given a list of integers, @list. +# Write a script to move all zero, if exists, to the end while maintaining +# the relative order of non-zero elements. +# Example 1 Input: @list = (1, 0, 3, 0, 0, 5) +# Output: (1, 3, 5, 0, 0, 0) +# Example 2 Input: @list = (1, 6, 4) +# Output: (1, 6, 4) +# Example 3 Input: @list = (0, 1, 0, 2, 0 +# Output: (1, 2, 0, 0, 0) +# +#============================================================================= + +use v5.36; + +use Getopt::Long; +my $Verbose = 0; +my $DoTest = 0; + +GetOptions("test" => \$DoTest, "verbose" => \$Verbose); +exit(!runTest()) if $DoTest; + +sub moveZero(@list) +{ + my @noZero = grep { $_ != 0 } @list; + return [ @noZero, (0) x ( scalar(@list)-scalar(@noZero) ) ]; +} + +sub runTest +{ + use Test::More; + + is_deeply( moveZero(1,0,3,0,0,5), [1,3,5,0,0,0], "Example 1"); + is_deeply( moveZero(1,6,4 ), [1,6,4 ], "Example 2"); + is_deeply( moveZero(0,1,0,2,0 ), [1,2,0,0,0 ], "Example 3"); + is_deeply( moveZero(0 ), [0 ], "Example 3"); + + done_testing; +} + |
