RogerBW's Blog

The Weekly Challenge 358: Encrypted Max 01 February 2026

I’ve been doing the Weekly Challenges. The latest involved string evaluation with fallback and alphabetic rotation. (Note that this ends today.)

Task 1: Max Str Value

You are given an array of alphanumeric string, @strings.

Write a script to find the max value of alphanumeric string in the given array. The numeric representation of the string, if it comprises of digits only otherwise length of the string.

I did parsing of strings that might or might not be integers (something that varies quite a lot between languages) back in 340 part 2, so I can borrows that code here. Scala:

Build a string to number parser that will return an exception if it fails. (I assume this is the inspiration for Rust's Option type too, or at least that they have common ancestry.)

  def toInt(in: String): Option[Int] = {
    try {
      Some(Integer.parseInt(in.trim))
    } catch {
      case e: NumberFormatException => None
    }
  }

Return the string's value, numeric parse if it works, otherwise length.

  def strvalue(a: String): Int = {
    var n = a.length
    toInt(a) match {
      case Some(x) => {
        n = x
      }
      case _ => { }
    }
    n
  }

Find the maximum of these in the list.

  def maxstrvalue(a: List[String]): Int = {
    return a.map(x => strvalue(x)).max
  }

Task 2: Encrypted String

You are given a string $str and an integer $int.

Write a script to encrypt the string using the algorithm - for each character $char in $str, replace $char with the $int th character after $char in the alphabet, wrapping if needed and return the encrypted string.

What I need first is a Euclidean remainder (i.e. a modulo N operation that constrains its result to the range 0 .. N-1, as opposed to most languages' % operator which can be positive or negative). Some languages provide this, such as Rust's rem_euclid() method, others don't. Raku:

sub posmod($x, $y) {
    my $z = $x % $y;
    while ($z < 0) {
        $z += $y;
    }
    $z;
}

Now a function to rotate an individual character.

sub rotx($a, $offset) {

Squash down the offset to a useful number.

    my $o = posmod($offset, 26);

Get a base character value for upper or lower case.

    my $base;
    if ($a ge 'a' && $a le 'z') {
        $base = ord('a');
    } elsif ($a ge 'A' && $a le 'Z') {
        $base = ord('A');
    } else {

If it wasn't a letter, return the input unmodified.

        return $a;
    }

Calculate the character code, rotate it, and shift it back to a character.

    my $c = posmod(ord($a) - $base + $o, 26) + $base;
    chr($c);
}

Finally, the rotator that does this for a string is just a wrapper round what does it for a character.

sub encryptedstring($a, $offset) {
    $a.comb.map({rotx($_, $offset)}).join('');
}

Full code on github.

Add A Comment

Your Name
Your Email
Your Comment

Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).

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 2300ad 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech bayern 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 disaster 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 essen 2025 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 horrorm science fiction hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo 2025 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 openscad opera parody paul temple perl perl weekly challenge photography podcast poetry politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant review 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 talon television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 typst 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