Skip to content

Instantly share code, notes, and snippets.

@adamcrussell
Created July 7, 2019 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrussell/104d482b3e89d7f00454adfeda81d47d to your computer and use it in GitHub Desktop.
Save adamcrussell/104d482b3e89d7f00454adfeda81d47d to your computer and use it in GitHub Desktop.
Perl Weekly Challenge 015
use strict;
use warnings;
##
# Write a script to generate first 10 strong and weak prime numbers.
##
use boolean;
use LWP::UserAgent;
use constant PRIME_URL => "http://primes.utm.edu/lists/small/100000.txt";
sub get_primes{
my @primes;
my $ua = new LWP::UserAgent(
ssl_opts => {verify_hostname => 0}
);
my $response = $ua->get(PRIME_URL);
my @lines = split(/\n/,$response->decoded_content);
foreach my $line (@lines){
my @p = split(/\s+/, $line);
unless(@p < 10){
push @primes, @p[1..(@p - 1)];
}
}
return @primes;
}
sub find_strong_prime{
my($n_prev, $n, $n_next) = @_;
if($n > (($n_prev + $n_next) / 2)){
return true;
}
return false;
}
sub find_weak_prime{
my($n_prev, $n, $n_next) = @_;
if($n < (($n_prev + $n_next) / 2)){
return true;
}
return false;
}
##
# Main
##
my(@weak, @strong);
my @primes = get_primes();
my @test;
push @test, shift @primes;
push @test, shift @primes;
while((@weak < 10 || @strong < 10) && @primes > 3){
push @test, shift @primes;
if(find_strong_prime(@test) && @strong < 10){
push @strong, $test[1];
}
if(find_weak_prime(@test) && @weak < 10){
push @weak, $test[1];
}
shift @test;
}
if(@weak == 10 && @strong == 10){
print "\tStrong\t\tWeak\n";
print "\t======\t\t====\n";
foreach my $i (0..9){
print "$i:\t$strong[$i]\t\t$weak[$i]\n";
}
}
else{
print "Ten strong/weak primes were not found in the first 100,000 primes.\n";
}
use strict;
use warnings;
##
# Write a script to implement Vigenère cipher.
# The script should be able to encode and decode.
##
use constant KEYWORD => "perl";
sub encode{
my($plaintext) = @_;
my $encrypted = "";
my @characters = split(//, $plaintext);
my @key = split(//, KEYWORD x ((length($plaintext) / length(KEYWORD)) + 1));
foreach my $c (@characters){
my $e = ((ord(lc($c)) - ord("a")) + (ord(shift @key) - ord("a"))) % 26;
$encrypted .= chr($e + ord("a"));
}
return $encrypted;
}
sub decode{
my($encrypted) = @_;
my $plaintext = "";
my @characters = split(//, $encrypted);
my @key = split(//, KEYWORD x ((length($encrypted) / length(KEYWORD)) + 1));
foreach my $c (@characters){
my $e = ((ord(lc($c)) - ord("a")) - (ord(shift @key) - ord("a"))) % 26;
$plaintext .= chr($e + ord("a"));
}
return $plaintext;
}
##
# Main
##
print "ATTACKATDAWN is encoded as " . encode("ATTACKATDAWN") . "\n";
print "PXKLRORESENY is decoded as " . decode("PXKLRORESENY") . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment