RabbitFarm
2021-11-21
Jort Sort the First Five Long Primes
The examples used here are from The Weekly Challenge problem statement and demonstrate the working solution.
Part 1
You are given a list of numbers. Write a script to implement JortSort. It should return true/false depending if the given list of numbers are already sorted.
Solution
use strict;
use warnings;
use boolean;
sub jort_sort{
for(my $i=0; $i < @_ - 1; $i++){
return false if $_[$i + 1] < $_[$i];
}
return true;
}
MAIN:{
print jort_sort(1, 2, 3, 4, 5) . "\n";
print jort_sort(1, 3, 2, 4, 5) . "\n";
}
Sample Run
$ perl perl/ch-1.pl
1
0
Notes
Apparently Jort Sort is a joke sort started by somebody in the JavaScript community. I didn't find it all that funny, but the code to implement it only took a quick minute.
Part 2
Write a script to generate the first 5 Long Primes.
Solution
use strict;
use warnings;
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 divide{
my($n, $d) = @_;
my @remainders;
my $q = (int($n / $d)) . ".";
my $r = $n % $d;
push @remainders, $r;
my @a;
for (0 .. $d){
$q .= int($r*10 / $d);
$r = $r*10 % $d;
@a = grep { $remainders[$_] == $r } (0 .. @remainders - 1);
last if(@a);
push @remainders, $r;
}
my $r_i = $a[0];
my $i = index($q, ".");
my $decimal_part = substr($q, $i+1);
return substr($q, 0, $i + 1) . substr($decimal_part, 0, $r_i) . "(" . substr($q, $i + $r_i + 1) . ")";
}
sub long_primes_five{
my @long_primes;
my @primes = get_primes();
do{
my $prime = shift @primes;
my $max_repetend = $prime - 1;
my $repeats = true if($prime != 2 && $prime != 5);
if($repeats){
my $x = divide(1, $prime, [], []);
$x =~ m/\((\d+)\)/;
my $repetend = $1;
push @long_primes, [$prime, $x] if length($repetend) == $prime - 1;
}
}while(@long_primes < 5);
return @long_primes;
}
MAIN:{
for my $p (long_primes_five()){
print $p->[0] . "\t" . $p->[1] . "\n";
}
}
Sample Run
$ perl perl/ch-2.pl
7 0.(142857)
17 0.(0588235294117647)
19 0.(052631578947368421)
23 0.(0434782608695652173913)
29 0.(0344827586206896551724137931)
Notes
This second part of the challenge was much more fun! Maybe my favorite part was that it largely re-used code from challenge 106 and also Challenge 015. Here we grab a list of pre-computed primes and then check each one for the desired property. After we find five, as required, we're done.
References
posted at: 16:34 by: Adam Russell | path: /perl | permanent link to this entry