diff options
| author | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2020-11-18 20:19:27 +0000 |
|---|---|---|
| committer | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2020-11-18 20:19:27 +0000 |
| commit | cd0a455239b4087598534b4e54dcaab33a96a03d (patch) | |
| tree | 3c22493a077342901e67221bc9f76c5386fc00a0 /challenge-048/duane-powell/perl5/ch-1.pl | |
| parent | 3e386e736b3c53f8723ef6b731fb732395e502e4 (diff) | |
| parent | 0d9e7c2c5551e2ab26da70fb1a07f40a06d8e5ba (diff) | |
| download | perlweeklychallenge-club-cd0a455239b4087598534b4e54dcaab33a96a03d.tar.gz perlweeklychallenge-club-cd0a455239b4087598534b4e54dcaab33a96a03d.tar.bz2 perlweeklychallenge-club-cd0a455239b4087598534b4e54dcaab33a96a03d.zip | |
Merge branch 'duanepowell-new-branch'
Diffstat (limited to 'challenge-048/duane-powell/perl5/ch-1.pl')
| -rwxr-xr-x | challenge-048/duane-powell/perl5/ch-1.pl | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/challenge-048/duane-powell/perl5/ch-1.pl b/challenge-048/duane-powell/perl5/ch-1.pl new file mode 100755 index 0000000000..8ab2eb41d0 --- /dev/null +++ b/challenge-048/duane-powell/perl5/ch-1.pl @@ -0,0 +1,57 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature 'say'; + +# Problem: https://perlweeklychallenge.org/blog/perl-weekly-challenge-048/ Task #1 + +my $SWORDSMAN = shift || 50; + +# These constants are not needed but it could be fun to add more weapons and rules +use constant { + NO_SWORD => 0, + SWORD => 1, +}; + +# Swordsman constructor +sub new_swordsman { + my $name = shift; + my $armed = shift; + return {name => $name, armed => $armed, next => undef}; +} + +# Create n swordsman and arrange them in a cirle +my $first_swordsman = new_swordsman(1, SWORD); +my $swordsman = $first_swordsman; +foreach my $s (2 .. $SWORDSMAN) { + my $next = new_swordsman($s, NO_SWORD); + # expand the circle and continue + $swordsman->{next} = $next; + $swordsman = $next; +} +$swordsman->{next} = $first_swordsman; + +# Execute man to your right and pass the sword until there is +# only one man standing, i.e. the next swordsman is yourself +$swordsman = $first_swordsman; +until ($swordsman->{next} == $swordsman) { + my $condemned = $swordsman->{next}; # ID the condemned + my $next = $condemned->{next}; # ID who gets the SWORD next + $condemned = undef; # execute the condemned + $swordsman->{armed} = NO_SWORD; # pass the sword + $next->{armed} = SWORD; + # contract the circle and continue + $swordsman->{next} = $next; + $swordsman = $next; +} + +say "$SWORDSMAN Swordsman arranged in a circle, the last man standing is Swordsman " . $swordsman->{name}; + +__END__ + +./ch-1.pl +50 Swordsman arranged in a circle, the last man standing is Swordsman 37 + +./ch-1.pl 3 +3 Swordsman arranged in a circle, the last man standing is Swordsman 3 + |
