aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-12-13 11:02:09 +0000
committerGitHub <noreply@github.com>2021-12-13 11:02:09 +0000
commitd1b15c284aa4624913f43b3447965dbf46bcf82c (patch)
treea9f5b6bd6d5929cdab380b2a3a99fd360eeda471
parent0f7fdabf6fb91baf184331e7243d17bc9c92d88a (diff)
parentee9a0af0aa503b0a0e5b82e27cf6143d36e4d505 (diff)
downloadperlweeklychallenge-club-d1b15c284aa4624913f43b3447965dbf46bcf82c.tar.gz
perlweeklychallenge-club-d1b15c284aa4624913f43b3447965dbf46bcf82c.tar.bz2
perlweeklychallenge-club-d1b15c284aa4624913f43b3447965dbf46bcf82c.zip
Merge pull request #5368 from Firedrake/rogerbw-challenge-143
Solutions for challenge #143
-rw-r--r--challenge-143/roger-bell-west/kotlin/ch-2.kt53
-rwxr-xr-xchallenge-143/roger-bell-west/perl/ch-1.pl58
-rwxr-xr-xchallenge-143/roger-bell-west/perl/ch-2.pl46
-rw-r--r--challenge-143/roger-bell-west/postscript/ch-2.ps55
-rwxr-xr-xchallenge-143/roger-bell-west/python/ch-1.py57
-rwxr-xr-xchallenge-143/roger-bell-west/python/ch-2.py42
-rwxr-xr-xchallenge-143/roger-bell-west/raku/ch-1.p654
-rwxr-xr-xchallenge-143/roger-bell-west/raku/ch-2.p642
-rwxr-xr-xchallenge-143/roger-bell-west/ruby/ch-1.rb67
-rwxr-xr-xchallenge-143/roger-bell-west/ruby/ch-2.rb53
-rw-r--r--challenge-143/roger-bell-west/rust/ch-1.rs82
-rwxr-xr-xchallenge-143/roger-bell-west/rust/ch-2.rs52
12 files changed, 661 insertions, 0 deletions
diff --git a/challenge-143/roger-bell-west/kotlin/ch-2.kt b/challenge-143/roger-bell-west/kotlin/ch-2.kt
new file mode 100644
index 0000000000..8a57e98251
--- /dev/null
+++ b/challenge-143/roger-bell-west/kotlin/ch-2.kt
@@ -0,0 +1,53 @@
+fun factorpairs(n: Int): ArrayList<Int> {
+ if (n == 1) {
+ return ArrayList(2)
+ }
+ var ff=ArrayList<Int>()
+ var s=Math.sqrt(n.toDouble()).toInt()
+ if (s*s == n) {
+ ff.add(s*2)
+ s--
+ }
+ for (pf in 2..s) {
+ if (n % pf == 0) {
+ ff.add(pf+n/pf)
+ }
+ }
+ ff.add(n+1)
+ return ff
+}
+
+fun is_stealthy(n: Int): Boolean {
+ val p=factorpairs(n)
+ if (p.count() == 1) {
+ return false
+ }
+ for (ix in 0..p.count()-2) {
+ for (iy in ix+1..p.count()-1) {
+ if (Math.abs(p[ix]-p[iy])==1) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+fun main() {
+ if (is_stealthy(36)) {
+ print("Pass")
+ } else {
+ print("FAIL")
+ }
+ print(" ")
+ if (is_stealthy(12)) {
+ print("Pass")
+ } else {
+ print("FAIL")
+ }
+ print(" ")
+ if (!is_stealthy(6)) {
+ println("Pass")
+ } else {
+ println("FAIL")
+ }
+}
diff --git a/challenge-143/roger-bell-west/perl/ch-1.pl b/challenge-143/roger-bell-west/perl/ch-1.pl
new file mode 100755
index 0000000000..78f8966e91
--- /dev/null
+++ b/challenge-143/roger-bell-west/perl/ch-1.pl
@@ -0,0 +1,58 @@
+#! /usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More tests => 3;
+
+is(exval("10 + 20 - 5"),25,'example 1');
+is(exval("(10 + 20 - 5) * 2"),50,'example 2');
+is(exval("10 + 20 - 5 * 2"),20,'example 3');
+
+sub exval {
+ my $expr=shift;
+ my @op=("(",")","+","-","*");
+ my %opp=map {$op[$_] => $_} (0..$#op);
+ my @re=("-?[0-9]+");
+ foreach my $op (@op) {
+ push @re,quotemeta($op);
+ }
+ my $re='('.join('|',@re).')';
+ my @opstack;
+ my @valstack;
+ foreach my $token ($expr =~ /$re/g) {
+ if ($token =~ /^-?[0-9]+$/) {
+ push @valstack,0+$token;
+ } elsif ($token eq '(') {
+ push @opstack,$token;
+ } elsif ($token eq ')') {
+ while ($opstack[-1] ne '(') {
+ push @valstack,operate(pop @opstack,pop @valstack,pop @valstack);
+ }
+ pop @opstack;
+ } elsif (exists $opp{$token}) {
+ while (scalar @opstack > 0 && $opp{$opstack[-1]} >= $opp{$token}) {
+ push @valstack,operate(pop @opstack,pop @valstack,pop @valstack);
+ }
+ push @opstack,$token;
+ } else {
+ die "bad token $token\n";
+ }
+ }
+ while (scalar @opstack > 0) {
+ push @valstack,operate(pop @opstack,pop @valstack,pop @valstack);
+ }
+ return $valstack[0];
+}
+
+sub operate {
+ my ($op,$a,$b)=@_;
+ if ($op eq '+') {
+ return $b+$a;
+ } elsif ($op eq '-') {
+ return $b-$a;
+ } elsif ($op eq '*') {
+ return $b*$a;
+ }
+ die "unknown operator $op\n";
+}
diff --git a/challenge-143/roger-bell-west/perl/ch-2.pl b/challenge-143/roger-bell-west/perl/ch-2.pl
new file mode 100755
index 0000000000..3fbc9bcef6
--- /dev/null
+++ b/challenge-143/roger-bell-west/perl/ch-2.pl
@@ -0,0 +1,46 @@
+#! /usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More tests => 3;
+
+is(is_stealthy(36),1,'example 1');
+is(is_stealthy(12),1,'example 2');
+is(is_stealthy(6),0,'example 3');
+
+sub factorpairs {
+ my $n=shift;
+ if ($n==1) {
+ return [2];
+ }
+ my @ff;
+ my $s=int(sqrt($n));
+ if ($s*$s == $n) {
+ push @ff,$s*2;
+ $s--;
+ }
+ foreach my $pf (2..$s) {
+ if ($n % $pf == 0) {
+ push @ff,$pf+$n/$pf;
+ }
+ }
+ push @ff,1+$n;
+ return \@ff;
+}
+
+sub is_stealthy {
+ my $n=shift;
+ my $p=factorpairs($n);
+ if (scalar @{$p}==1) {
+ return 0;
+ }
+ foreach my $ix (0..scalar @{$p}-2) {
+ foreach my $iy ($ix+1..scalar @{$p}-1) {
+ if (abs($p->[$ix]-$p->[$iy])==1) {
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
diff --git a/challenge-143/roger-bell-west/postscript/ch-2.ps b/challenge-143/roger-bell-west/postscript/ch-2.ps
new file mode 100644
index 0000000000..e1cdbab9b3
--- /dev/null
+++ b/challenge-143/roger-bell-west/postscript/ch-2.ps
@@ -0,0 +1,55 @@
+%!PS
+
+/apush { % [a b] c -> [a b c]
+ /t exch def
+ [ exch aload pop t ]
+} bind def
+
+/factorpairs {
+ /nn exch def
+ nn 1 eq {
+ [ 2 ]
+ } {
+ /ff 0 array def
+ /s nn sqrt cvi def
+ s s mul nn eq {
+ /ff ff s 2 mul apush def
+ /s s 1 sub def
+ } if
+ 2 1 s {
+ /pf exch def
+ nn pf mod 0 eq {
+ /ff ff pf nn pf idiv add apush def
+ } if
+ } for
+ /ff ff 1 nn add apush def
+ ff
+ } ifelse
+} bind def
+
+/is_stealthy {
+ /n exch def
+ /p n factorpairs def
+ /stl false def
+ p length 1 ne {
+ 0 1 p length 2 sub {
+ /ix exch def
+ ix 1 add 1 p length 1 sub {
+ /iy exch def
+ p ix get p iy get sub abs
+ 1 eq {
+ /stl true def
+ exit
+ } if
+ } for
+ stl {
+ exit
+ } if
+ } for
+ } if
+ stl
+} bind def
+
+36 is_stealthy true eq { (Pass) } { (FAIL) } ifelse print ( ) print
+12 is_stealthy true eq { (Pass) } { (FAIL) } ifelse print ( ) print
+6 is_stealthy false eq { (Pass) } { (FAIL) } ifelse =
diff --git a/challenge-143/roger-bell-west/python/ch-1.py b/challenge-143/roger-bell-west/python/ch-1.py
new file mode 100755
index 0000000000..2fa9707527
--- /dev/null
+++ b/challenge-143/roger-bell-west/python/ch-1.py
@@ -0,0 +1,57 @@
+#! /usr/bin/python3
+
+import unittest
+
+import re
+
+def operate(op,a,b):
+ if op == "+":
+ return b+a
+ elif op == "-":
+ return b-a
+ elif op == "*":
+ return b*a
+ print("unknown operator")
+
+def exval(expr):
+ op=["(",")","+","-","*"]
+ opp=dict()
+ rec=[r"-?[0-9]+"]
+ for i,o in enumerate(op):
+ opp[o]=i
+ rec.append("\\" + o)
+ ret=re.compile("(" + "|".join(rec) + ")")
+ ren=re.compile("^" + rec[0] + "$")
+ opstack=[]
+ valstack=[]
+ for token in ret.findall(expr):
+ if ren.match(token):
+ valstack.append(int(token))
+ elif token == "(":
+ opstack.append(token)
+ elif token == ")":
+ while opstack[-1] != "(":
+ valstack.append(operate(opstack.pop(),valstack.pop(),valstack.pop()))
+ opstack.pop()
+ elif token in opp:
+ while len(opstack)>0 and opp[opstack[-1]] >= opp[token]:
+ valstack.append(operate(opstack.pop(),valstack.pop(),valstack.pop()))
+ opstack.append(token)
+ else:
+ print("bad token")
+ while len(opstack)>0:
+ valstack.append(operate(opstack.pop(),valstack.pop(),valstack.pop()))
+ return valstack[0]
+
+class TestExval(unittest.TestCase):
+
+ def test_ex1(self):
+ self.assertEqual(exval("10 + 20 - 5"),25,'example 1')
+
+ def test_ex2(self):
+ self.assertEqual(exval("(10 + 20 - 5) * 2"),50,'example 2')
+
+ def test_ex3(self):
+ self.assertEqual(exval("10 + 20 - 5 * 2"),20,'example 3')
+
+unittest.main()
diff --git a/challenge-143/roger-bell-west/python/ch-2.py b/challenge-143/roger-bell-west/python/ch-2.py
new file mode 100755
index 0000000000..443f52df23
--- /dev/null
+++ b/challenge-143/roger-bell-west/python/ch-2.py
@@ -0,0 +1,42 @@
+#! /usr/bin/python3
+
+import unittest
+
+from math import sqrt
+
+def factorpairs(n):
+ if n==1:
+ return [2]
+ ff=[]
+ s=int(sqrt(n))
+ if s*s==n:
+ ff.append(s*2)
+ s-=1
+ for pf in range(2,s+1):
+ if n % pf == 0:
+ ff.append(pf+int(n/pf))
+ ff.append(n+1)
+ return ff
+
+def is_stealthy(n):
+ p=factorpairs(n)
+ if len(p)==1:
+ return False
+ for ix in range(len(p)-1):
+ for iy in range(ix+1,len(p)):
+ if abs(p[ix]-p[iy])==1:
+ return True
+ return False
+
+class TestIs_Stealthy(unittest.TestCase):
+
+ def test_ex1(self):
+ self.assertEqual(is_stealthy(36),True,'example 1')
+
+ def test_ex2(self):
+ self.assertEqual(is_stealthy(12),True,'example 2')
+
+ def test_ex3(self):
+ self.assertEqual(is_stealthy(6),False,'example 3')
+
+unittest.main()
diff --git a/challenge-143/roger-bell-west/raku/ch-1.p6 b/challenge-143/roger-bell-west/raku/ch-1.p6
new file mode 100755
index 0000000000..b3c6465031
--- /dev/null
+++ b/challenge-143/roger-bell-west/raku/ch-1.p6
@@ -0,0 +1,54 @@
+#! /usr/bin/perl6
+
+use Test;
+plan 3;
+
+is(exval("10 + 20 - 5"),25,'example 1');
+is(exval("(10 + 20 - 5) * 2"),50,'example 2');
+is(exval("10 + 20 - 5 * 2"),20,'example 3');
+
+sub exval($expr) {
+ my @op=("(",")","+","-","*");
+ my %opp=map {@op[$_] => $_},(0..@op.end);
+ my @re=("\\-? <[0..9]>+");
+ for @op -> $op {
+ @re.push('\\' ~ $op);
+ }
+ my $re='(' ~ join('|',@re) ~ ')';
+ my @opstack;
+ my @valstack;
+ for ($expr ~~ m:g/<$re>/) -> $token {
+ if ($token ~~ /^ '-'? <[0..9]>+ /) {
+ push @valstack,0+$token;
+ } elsif ($token eq '(') {
+ push @opstack,$token;
+ } elsif ($token eq ')') {
+ while (@opstack[*-1] ne '(') {
+ push @valstack,operate(@opstack.pop,@valstack.pop,@valstack.pop);
+ }
+ pop @opstack;
+ } elsif (%opp{$token}:exists) {
+ while (@opstack.elems > 0 && %opp{@opstack[*-1]} >= %opp{$token}) {
+ push @valstack,operate(@opstack.pop,@valstack.pop,@valstack.pop);
+ }
+ push @opstack,$token;
+ } else {
+ die "bad token $token\n";
+ }
+ }
+ while (@opstack.elems > 0) {
+ push @valstack,operate(@opstack.pop,@valstack.pop,@valstack.pop);
+ }
+ return @valstack[0];
+}
+
+sub operate($op,$a,$b) {
+ if ($op eq '+') {
+ return $b+$a;
+ } elsif ($op eq '-') {
+ return $b-$a;
+ } elsif ($op eq '*') {
+ return $b*$a;
+ }
+ die "unknown operator $op\n";
+}
diff --git a/challenge-143/roger-bell-west/raku/ch-2.p6 b/challenge-143/roger-bell-west/raku/ch-2.p6
new file mode 100755
index 0000000000..4047fd9d52
--- /dev/null
+++ b/challenge-143/roger-bell-west/raku/ch-2.p6
@@ -0,0 +1,42 @@
+#! /usr/bin/perl6
+
+use Test;
+plan 3;
+
+is(is_stealthy(36),True,'example 1');
+is(is_stealthy(12),True,'example 2');
+is(is_stealthy(6),False,'example 3');
+
+sub factorpairs($n) {
+ if ($n==1) {
+ return [2];
+ }
+ my @ff;
+ my $s=floor(sqrt($n));
+ if ($s*$s == $n) {
+ push @ff,$s*2;
+ $s--;
+ }
+ for (2..$s) -> $pf {
+ if ($n % $pf == 0) {
+ push @ff,$pf+($n div $pf);
+ }
+ }
+ push @ff,1+$n;
+ return @ff;
+}
+
+sub is_stealthy($n) {
+ my @p=factorpairs($n);
+ if (@p.elems==1) {
+ return False;
+ }
+ for (0..@p.end-1) -> $ix {
+ for ($ix+1..@p.end) -> $iy {
+ if (abs(@p[$ix]-@p[$iy])==1) {
+ return True;
+ }
+ }
+ }
+ return False;
+}
diff --git a/challenge-143/roger-bell-west/ruby/ch-1.rb b/challenge-143/roger-bell-west/ruby/ch-1.rb
new file mode 100755
index 0000000000..0b54123208
--- /dev/null
+++ b/challenge-143/roger-bell-west/ruby/ch-1.rb
@@ -0,0 +1,67 @@
+#! /usr/bin/ruby
+
+def operate(op,a,b)
+ if op=="+" then
+ return b+a
+ elsif op=="-" then
+ return b-a
+ elsif op=="*" then
+ return b*a
+ end
+end
+
+def exval(expr)
+ op=["(",")","+","-","*"]
+ opp=Hash.new
+ rec=["-?[0-9]+"]
+ op.each_with_index do |o,i|
+ opp[o]=i
+ rec.push('\\' + o)
+ end
+ ret=Regexp.new("(" + rec.join("|") + ")")
+ ren=Regexp.new("^" + rec[0] + "$")
+ opstack=[]
+ valstack=[]
+ expr.scan(ret).each do |ta|
+ token=ta[0]
+ if token.match(ren) then
+ valstack.push(token.to_i())
+ elsif token == "(" then
+ opstack.push(token)
+ elsif token == ")" then
+ while opstack[-1] != "(" do
+ valstack.push(operate(opstack.pop(),valstack.pop(),valstack.pop()))
+ end
+ opstack.pop()
+ elsif opp.has_key?(token) then
+ while opstack.length>0 && opp[opstack[-1]] >= opp[token] do
+ valstack.push(operate(opstack.pop(),valstack.pop(),valstack.pop()))
+ end
+ opstack.push(token)
+ else
+ print("bad token")
+ end
+ end
+ while opstack.length>0 do
+ valstack.push(operate(opstack.pop(),valstack.pop(),valstack.pop()))
+ end
+ return valstack[0]
+end
+
+require 'test/unit'
+
+class TestExval < Test::Unit::TestCase
+
+ def test_ex1
+ assert_equal(25,exval("10 + 20 - 5"))
+ end
+
+ def test_ex2
+ assert_equal(50,exval("(10 + 20 - 5) * 2"))
+ end
+
+ def test_ex3
+ assert_equal(20,exval("10 + 20 - 5 * 2"))
+ end
+
+end
diff --git a/challenge-143/roger-bell-west/ruby/ch-2.rb b/challenge-143/roger-bell-west/ruby/ch-2.rb
new file mode 100755
index 0000000000..552bdd2a8c
--- /dev/null
+++ b/challenge-143/roger-bell-west/ruby/ch-2.rb
@@ -0,0 +1,53 @@
+#! /usr/bin/ruby
+
+def factorpairs(n)
+ if n==1 then
+ return [2]
+ end
+ ff=[]
+ s=Math.sqrt(n).floor
+ if s*s==n then
+ ff.push(s*2)
+ s-=1
+ end
+ 2.upto(s) do |pf|
+ if n % pf == 0 then
+ ff.push(n/pf+pf)
+ end
+ end
+ ff.push(1+n)
+ return ff
+end
+
+def is_stealthy(n)
+ p=factorpairs(n)
+ if p.length()==1 then
+ return false
+ end
+ 0.upto(p.length()-2) do |ix|
+ ix.upto(p.length()-1) do |iy|
+ if (p[ix]-p[iy]).abs==1 then
+ return true
+ end
+ end
+ end
+ return false
+end
+
+require 'test/unit'
+
+class TestIs_Stealthy < Test::Unit::TestCase
+
+ def test_ex1
+ assert_equal(true,is_stealthy(36))
+ end
+
+ def test_ex2
+ assert_equal(true,is_stealthy(12))
+ end
+
+ def test_ex3
+ assert_equal(false,is_stealthy(6))
+ end
+
+end
diff --git a/challenge-143/roger-bell-west/rust/ch-1.rs b/challenge-143/roger-bell-west/rust/ch-1.rs
new file mode 100644
index 0000000000..91f3b08a5e
--- /dev/null
+++ b/challenge-143/roger-bell-west/rust/ch-1.rs
@@ -0,0 +1,82 @@
+use regex::Regex;
+use std::collections::HashMap;
+
+#[test]
+fn test_ex1() {
+ assert_eq!(exval("10 + 20 - 5"), 25);
+}
+
+#[test]
+fn test_ex2() {
+ assert_eq!(exval("(10 + 20 - 5) * 2"), 50);
+}
+
+#[test]
+fn test_ex3() {
+ assert_eq!(exval("10 + 20 - 5 * 2"), 20);
+}
+
+fn operate(op: char, a: i32, b: i32) -> i32 {
+ if op == '+' {
+ return b + a;
+ } else if op == '-' {
+ return b - a;
+ } else if op == '*' {
+ return b * a;
+ }
+ println!("Invalid operator {}", op);
+ 0
+}
+
+fn exval(expr: &str) -> i32 {
+ let op = ['(', ')', '+', '-', '*'];
+ let mut opp: HashMap<char, usize> = HashMap::new();
+ let mut rec = vec!["-?[0-9]+".to_string()];
+ for (i, o) in op.iter().enumerate() {
+ opp.insert(*o, i);
+ let ss = "\\".to_string() + &o.to_string();
+ rec.push(ss);
+ }
+ let ret =
+ Regex::new(&("(".to_string() + &rec.join("|") + &")".to_string()))
+ .unwrap();
+ let ren =
+ Regex::new(&("^".to_string() + &rec[0] + &"$".to_string())).unwrap();
+ let mut opstack: Vec<char> = vec![];
+ let mut valstack: Vec<i32> = vec![];
+ for tm in ret.find_iter(expr) {
+ let token = tm.as_str();
+ let tokchar = token.chars().nth(0).unwrap();
+ if ren.is_match(token) {
+ valstack.push(token.parse::<i32>().unwrap());
+ println!("{:?}", valstack);
+ } else if token == "(" {
+ opstack.push('(');
+ } else if token == ")" {
+ while opstack[opstack.len() - 1] != '(' {
+ let a=valstack.pop().unwrap();
+ let b=valstack.pop().unwrap();
+ valstack.push(operate(opstack.pop().unwrap(),a,b));
+ }
+ opstack.pop().unwrap();
+ } else if opp.contains_key(&tokchar) {
+ while opstack.len() > 0
+ && opp.get(&opstack[opstack.len() - 1]).unwrap()
+ >= opp.get(&tokchar).unwrap()
+ {
+ let a=valstack.pop().unwrap();
+ let b=valstack.pop().unwrap();
+ valstack.push(operate(opstack.pop().unwrap(),a,b));
+ }
+ opstack.push(tokchar);
+ } else {
+ println!("Bad token");
+ }
+ }
+ while opstack.len() > 0 {
+ let a=valstack.pop().unwrap();
+ let b=valstack.pop().unwrap();
+ valstack.push(operate(opstack.pop().unwrap(),a,b));
+ }
+ valstack[0]
+}
diff --git a/challenge-143/roger-bell-west/rust/ch-2.rs b/challenge-143/roger-bell-west/rust/ch-2.rs
new file mode 100755
index 0000000000..74de3e1044
--- /dev/null
+++ b/challenge-143/roger-bell-west/rust/ch-2.rs
@@ -0,0 +1,52 @@
+#! /bin/sh
+//usr/bin/env rustc --test $0 -o ${0}x && ./${0}x; rm -f ${0}x ; exit
+
+#[test]
+fn test_ex1() {
+ assert_eq!(is_stealthy(36), true);
+}
+
+#[test]
+fn test_ex2() {
+ assert_eq!(is_stealthy(12), true);
+}
+
+#[test]
+fn test_ex3() {
+ assert_eq!(is_stealthy(6), false);
+}
+
+fn factorpairs(n: i32) -> Vec<i32> {
+ let mut ff = vec![];
+ if n == 1 {
+ ff.push(2);
+ return ff;
+ }
+ let mut s = (n as f64).sqrt() as i32;
+ if s * s == n {
+ ff.push(s * 2);
+ s -= 1;
+ }
+ for pf in 2..=s {
+ if n % pf == 0 {
+ ff.push(pf + n / pf);
+ }
+ }
+ ff.push(1 + n);
+ ff
+}
+
+fn is_stealthy(n: i32) -> bool {
+ let p = factorpairs(n);
+ if p.len() == 1 {
+ return false;
+ }
+ for ix in 0..p.len() - 1 {
+ for iy in ix + 1..p.len() {
+ if (p[ix] - p[iy]).abs() == 1 {
+ return true;
+ }
+ }
+ }
+ false
+}