RogerBW's Blog

The Weekly Challenge 185: Big MAC and Mask 06 October 2022

I’ve been doing the Weekly Challenges. The latest involved various string manipulations. (Note that this is open until 9 October 2022.)

Task 1: MAC address

You are given MAC address in the form i.e. hhhh.hhhh.hhhh.

Write a script to convert the address in the form hh:hh:hh:hh:hh:hh.

I'm not required to validate it. So my basic approach here is to scan the string, accepting only hex digits and ignoring everything else, and inserting colons where appropriate based on the count of valid characters. Rust's match does this very neatly:

fn recomposemac(inp: &str) -> String {
    let mut out = String::new();
    let mut count: u8 = 0;
    for c in inp.chars() {
        match c {
            '0'..='9' | 'a'..='f' => {
                if count == 2 {
                    out.push(':');
                    count = 0;
                }
                count += 1;
                out.push(c);
            }
            _ => {}
        }
    }
    out
}

In PostScript, I build the output as an array of characters, then convert it to a string at the end.

/recomposemac {
    6 dict begin
    /zero (0) 0 get def
    /nine (9) 0 get def
    /a (a) 0 get def
    /f (f) 0 get def
    /colon (:) 0 get def
    /ct 0 def
    [ exch
      {
          /c exch def
          c zero ge c nine le and
          c a ge c f le and or {
              ct 2 eq {
                  colon
                  /ct 0 def
              } if
              /ct ct 1 add def
              c
          } if
      } forall
    ] a2s
    end
} bind def

Task 2: Mask Code

You are given a list of codes in many random format.

Write a script to mask first four characters (a-z,0-9) and keep the rest as it is.

In other words, change the first four alphanumeric characters to "x" characters. This is conceptually very similar to part 1 (with the slight extra complication of having to process a whole list of strings rather than just one), and indeed both of them are quite similar to last week's task 2.

Raku:

sub recomposemaskcode(@list) {
    my @out;
    for @list -> $ins {
        my $count = 0;
        my $os = '';
        for $ins.comb -> $c {
            if (($c ge '0' && $c le '9') || ($c ge 'a' && $c le 'z')) {
                if ($count < 4) {
                    $count++;
                    $os ~= 'x';
                } else {
                    $os ~= $c;
                }
            } else {
                $os ~= $c;
            }
        }
        @out.push($os);
    }
    return @out;
}

Probably one should avoid the two occurrences of appending $c, for example with a nextafter the $os ~= 'x', and I'd probably do this in production code – but not all languages can do it cleanly.

Full code on github.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

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 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 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