RogerBW's Blog

The Weekly Challenge 290: Double Luhn 13 October 2024

I’ve been doing the Weekly Challenges. The latest involved list analysis and Luhn's checksum algorithm. (Note that this ends today.)

Task 1: Double Exist

You are given an array of integers, @ints.

Write a script to find if there exist two indices $i and $j such that:

* 1) $i != $j

* 2) 0 <= ($i, $j) < scalar @ints

* 3) $ints[$i] == 2 * $ints[$j]

Where the language had a built-in combination function (Ruby, Crystal, Raku) I used it, but althrough I've written combination generators for the other languages nested loops seemed just as viable.

PostScript:

/doubleexist {
    0 dict begin
    /a exch def

The default return value is false.

    false

Run the i index from 0 to the last-but-one element;

    0 1 a length 2 sub {
        /i exch def

Then the j index from i+1 to the end. This gives us each pair once.

        i 1 a length 1 sub {
            /j exch def

Get the pair out of the array, then check for a[i] being twice a[j] or vice versa. If so, flip the answer to true and exit.

            a i get a j get
            2 copy
            2 mul eq
            3 1 roll
            exch 2 mul eq or {
                pop true
                exit
            } if
        } for
        dup {
            exit
        } if
    } for
    end
} bind def

With combinations, in Ruby, it's rather less verbose:

def doubleexist(a)
  a.combination(2).each do |i|
    if i[0] == 2 * i[1] || i[1] == 2 * i[0]
      return true
    end
  end
  false
end

Task 2: Luhn's Algorithm

You are given a string $str containing digits (and possibly other characters which can be ignored). The last digit is the payload; consider it separately. Counting from the right, double the value of the first, third, etc. of the remaining digits.

For each value now greater than 9, sum its digits.

The correct check digit is that which, added to the sum of all values, would bring the total mod 10 to zero.

Return true if and only if the payload is equal to the correct check digit.

I decided to do this piecewise as laid out in the specification. There might be efficiency gains to be had by taking a single pass through the digit list, amending the value if appropriate, and adding it to a running sum.

To demonstrate how trivial it is, all my code will ignore non-numeric characters. I still see web sites today that insist on having, or on not having, the cosmetic spaces in a credit card or telephone number.

Raku:

sub luhnalgorithm($a) {

Each digit becomes a list entry.

    my @digits = $a.comb.grep(/\d/);

Last digit is the payload; reverse the rest for convenience.

    my $payload = @digits.pop;
    @digits = @digits.reverse;

Double and if necessary reduce every second digit.

    loop (my $i = 0; $i < @digits.elems; $i += 2) {
        @digits[$i] *= 2;
        if (@digits[$i] > 9) {
            @digits[$i] -= 9;
        }
    }

Calculate and verify the checksum.

    10 - (@digits.sum % 10) == $payload;
}

Full code on github.

Add A Comment

Your Name
Your Email
Your Comment

Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 essen 2024 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1