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 next
after 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.