aboutsummaryrefslogtreecommitdiff
path: root/challenge-003
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2019-04-12 15:46:51 +0100
committerGitHub <noreply@github.com>2019-04-12 15:46:51 +0100
commit3c6f7b78c9ea86187549c3ef5a6c03431f2fe637 (patch)
tree254848144fcaa3ec9e4584b90a33b7aaf6b7283a /challenge-003
parent6663c20a1ef2f63e1adf78de6f8b29a54a90539f (diff)
parent2b600f4df613ed8830773979650d9fe550ab51d5 (diff)
downloadperlweeklychallenge-club-3c6f7b78c9ea86187549c3ef5a6c03431f2fe637.tar.gz
perlweeklychallenge-club-3c6f7b78c9ea86187549c3ef5a6c03431f2fe637.tar.bz2
perlweeklychallenge-club-3c6f7b78c9ea86187549c3ef5a6c03431f2fe637.zip
Merge pull request #43 from dmanto/daniel-mantovani-challenge3-branch
for ch-003 ch-1.pl
Diffstat (limited to 'challenge-003')
-rw-r--r--challenge-003/daniel-mantovani/perl5/ch1-pl38
1 files changed, 38 insertions, 0 deletions
diff --git a/challenge-003/daniel-mantovani/perl5/ch1-pl b/challenge-003/daniel-mantovani/perl5/ch1-pl
new file mode 100644
index 0000000000..fa23ce0075
--- /dev/null
+++ b/challenge-003/daniel-mantovani/perl5/ch1-pl
@@ -0,0 +1,38 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+use v5.10;
+
+my $q = $ARGV[0];
+
+die
+ "Usage: perl $0 <n>\n\nwhere <n> is the (integer) quantity of hamming numbers you ask"
+ unless $q && $q =~ /^\d+$/;
+
+my @primes = (2, 3, 5);
+
+# for each prime, we will define one vector (array), whith just one element [1]
+# note that [1] will be first hamming code inside each array!
+
+my %vec;
+$vec{$_} = [1] for @primes;
+
+for my $i (1 .. $q) {
+
+# just look for the min value from the head of v2, v3 or v5
+# (without using List::Util, as the challenge encourages no to use external modules)
+ my $h;
+ map { $h = $vec{$_}[0] unless $h && $h < $vec{$_}[0] } @primes;
+
+ # and we just got the next hamming number!
+ say "$i\t", $h;
+
+ for my $f (@primes) { # now for every prime factor
+ # remove this value on each vector where it is present
+ shift @{$vec{$f}} if $vec{$f}[0] == $h;
+
+ # and finally calculate and insert new values to each vector
+ # note that new pushed value is higer than any previous value in each vector
+ push @{$vec{$f}}, $h * $f;
+ }
+}