The Weekly Challenge ‐ Perl and Raku

CY's Take on The Weekly Challenge #159

If you want to challenge yourself on programming, especially on Perl and/or Raku, go to https://theweeklychallenge.org, code the latest challenges, submit codes on-time (by GitHub or email).

Do tell me, if I am wrong or you strongly oppose my statements!

It's time for challenges in Week #159 !


Section B of "Use of English" is "Writing".
The complete syllabus of "Use of English" can be found here(pdf, from HKEAA).
Note that the year I was supposed to take the second public exam is 2009.

image info


First of all, what happens...! Why a secondary school (high school) report card long time ago is shown as an accompanying photo on a blogpost related to programming? Are there any subjects on the card directly related to programming?

OK, I admit, that is my school report card in 2008. Mid-year exam. I was the first of my class in "Chinese Language and Culture" and the fourth of my class in "Use of English" (though, it was a science stream class). See, I was the first of English writing in that exam. I did not cheat. And the marker was a native speaker in English. He was called Mr North, by the way. OK... If I love to show off, why don't I spend time to write the TWC challenge tasks in more guest languages?

I often mention my passion towards mathematics. Is it because both tasks this week are related to mathematics? I was the first of "Pure Mathematics" that year ‐ overtook competitors from the other class as well.

In the research field of natural language acquisition, people often mention "use it or lose it". I admit that, in between the memorable secondary school years and the end of my university life, I hadn't written any serious English writing.

Am I making a random reference because Larry Wall, who created Perl, is from a linguistics background?

Since I started blogging or using Twitter (mostly people from a programming background interact with me on Twitter in the current stage), I found myself making lots of grammarical and spelling mistakes. The kind community of programmers does not langh at my English or the embarrassment caused.

I leave the readers to guess my intention. (Reality: I am tired now.) Can we can go back to my usual blogpost style?

I still cannot change my coloring of blogposts.

Two friends have instilled "positive energy" for me last week (4th-10th April). The first one is Eric Cheung, who has been announced as the Champion of TWC this month. He has contributed solutions in Excel VBA and Python (which I used to hate). I gain happiness from good news of friends easily. Another friend, a classmate of math courses in my university, who holds a PhD in Math, has been offered a software engineering position in Taiwan. She also did competitive math in secondary school. I have been happy for her and we had a chat via Facebook messenger.

[translated]
CY: We have been in the "community" for years... Some [scientific] research has addressed that, on average, males have better spatial skills. But I still don't feel [on average / in general] the ability of males are better than the ability of females in STEM.
Friend: ... I don't feel so as well. :P

Well, should we go to study the two programming tasks now?

Task 1: Farey Sequence

Look like an interesting mathematical entity to be studied but I decided not to doodle with math this week. I ran into the algorithmic section on its Wikipedia entry directly.

I did not look on the Python code which is in functional programming style provided on Wikipedia. And I did not study functional programming, therefore my code does not look concise:

use v5.22.0;
use warnings;
use POSIX;

my $N = $ARGV[0] if defined($ARGV[0]);

say farey($N) if defined($ARGV[0]);



sub farey {
    my $n = $_[0];
    die "The parameter should be a positive integer." if $n==0;
    my ($g, $h) = ([0,1], [1, $n]);
    my @terms;
    do {
        push @terms, "".join("/", $g->@*);
        my ($a, $b) = $g->@*;
        my ($c, $d) = $h->@*;
        my ($p, $q) = (
            $c*floor (($n+$b)/$d) - $a,
            $d*floor(($n+$b)/$d) - $b
        );
        ($g, $h) = ($h, [$p, $q]);
    } while (!($h->[0] == 1 && $h->[1] == 1));
    push @terms, join("/", $g->@*), join("/", $h->@*);
    return join(", ",@terms) . ".";
}

Task 2: Moebius Number

I determined to spend most of my programming time on this task. I was a fan of number theory during secondary school. Like the Task 2 in Week 156, Möbius function is closely related to analytic number theory.

Since The Weekly Challenge already got many tasks related to primes recently, I decide to start from the definition: "Möbius function μ(n) is the sum of the primitive nth roots of unity." An obvious obstacle, for programmers, is the floating point issue.

So here is my Perl code:

sub irn {
    my $i = $_[0];
    my $n = $_[1];
    return Math::Complex->make(
        cos 2*PI*$i/$n, sin 2*PI*$i/$n
    );
}

sub mo {
    my $n = $_[0];
    return 1 if $n == 1;
    return -1 if $n == 2;
    my $sum = irn(1, $n);
    for my $i (2..$n-1) {
        next if any { ($i*$_) % $n == 0} (2..$n-1);
        $sum += irn($i, $n);
    }
    # say "# intermediate sum: ", Re($sum), "\n\n";
    return floor(Re($sum)+0.5);
}

Then I coded in Julia. During my search for reference, I find people stating that Julia is a functional programming language. I have been wanted to learn a functional programming language. And as stated previously, the community of Julia looks friendly.

function irn(i,n)
    return cos(2π*i/n)+sin(2π*i/n)im
end

function möbius(n)
    if n==1
        return 1
    end
    if n==2
        return -1
    end
    primitive_roots=Any[]
    push!(primitive_roots, irn(1, n))
    for i in 2:n-1
        for s in 2:n-1
            if (i*s)%n==0
                @goto label1
            end
        end
        push!(primitive_roots, irn(i,n))
        @label label1
    end
    return round(Int,real(sum(primitive_roots)))
end

I have decided to learn Julia properly this year.

Final present: Java. It is easy to contruct a "complex number" class in Java. But for simplicity, I have decided to use the matrix representation of complex numbers to code.

public class Moebius
{
    public static void main(String[] args)
    {
        int N = 1;
        try {
            N = Integer.parseInt(args[0]);
            if (N<=0)
                throw new ArithmeticException();
        } catch (Exception e) {
            System.err.print("Please use a positive integer ");
            System.err.println("as your parameter.");
            System.exit(0);
        }
        double[][] complex1 = new double[][] { {1, 0} , {0, 1} };
        double[][] complex2 = new double[][] { {0, 1} , {-1, 0} };
        System.out.println(Math.round(mu(N)));
    }


    public static double mu(int n)
    {
        double[][] sum = ithRootOfUnityModuloN(1, n);
        LOOP: for (int i=2; i<n; i++)
        {
            for (int s=2; s<n; s++)
            {
                if ( (i*s) % n == 0 )
                    continue LOOP;
            }
            sum = complexAddition(sum, ithRootOfUnityModuloN(i,n));
        }
        return sum[0][0];
    }


    public static double[][] complexAddition(double[][] c1, double[][] c2)
    {
        double a = c1[0][0];
        double b = c1[0][1];
        double c = c1[1][0];
        double d = c1[1][1];
        double e = c2[0][0];
        double f = c2[0][1];
        double g = c2[1][0];
        double h = c2[1][1];
        return new double[][] {{ a+e, b+f }, { c+g, d+h }};
    }



    public static double[][] complexMultiplication(double[][] c1, double[][] c2)
    {
        double a = c1[0][0];
        double b = c1[0][1];
        double c = c1[1][0];
        double d = c1[1][1];
        double e = c2[0][0];
        double f = c2[0][1];
        double g = c2[1][0];
        double h = c2[1][1];
        return new double[][] {{a*e+b*g, a*f+b*h}, {c*e+d*g, c*f+d*h}};
    }



    public static double[][] ithRootOfUnityModuloN(int i , int n)
    {
        double realPart = Math.cos(2*Math.PI*i/n);
        double imaginaryPart = Math.sin(2*Math.PI*i/n);
        double[][] result = new double[][] {
                              {realPart, imaginaryPart},
                              {-imaginaryPart, realPart}
                            };
        return result;
    }
}

At first I wanted to code the task in Dart too. However... Errrrr... "It is better to study four subjects thoroughly than six superficially."[ref. Why bother my university major!?]

I hope the Hong Kong Public Library can retain its service soon so that I can look on Introduction to Analytic Number Theory which I read many years ago... Also to borrow books on programming. Althrough I have digital versions of some books, including Perl Best Practices, I still prefer paperback versions, sometimes. □

I think I would try to stick to UK English for some vocabulary in writing from now on ("high school" => "secondary school"; "college" => "university"). Why? Haha, I am not planning for an immigration by my aged passport. Just because I have been an old-fashion freak, and there are too many slangs in US English.

The photo on this page should not be copied or published on other places, online or offline.

The text content of this blogpost is released under a copyleft spirit. One may share (full or partial) content of this blogpost on other platform if you share it under the free and open content spirit.

link for CY's full codes: ch-1.pl, ch-2.pl, ch-2.jl, Moebius.java


Contact on twitter: @e7_87.

Discuss via GitHub issues: here.

Email: fungcheokyin at gmail.com

Created Date-Time: 11th April, 2022. 05:30 HKT.

Latest Update Before the Official Deadline: 11th April, 2022. 06:24 HKT.

Latest Update: 12th April, 2022. 17:54 HKT.