I’ve been doing the Weekly
Challenges. The
latest
involved string conversion and analysis. (Note that this ends today.)
Task 1: Binary Date
You are given a date in the format YYYY-MM-DD
.
Write a script to convert it into binary date.
This comes apart into:
- break the input string by dashes into a list of decimal strings
- convert each decimal string to a binary string
- join those binary strings with dashes
The obvious way to do step 2, of course, is to parse the decimal
strings into numeric values, then write those out as binary.
Some languages make this a one-liner, like Raku:
sub binarydate($a) {
$a.split('-').map({sprintf('%b', $_)}).join('-');
}
Some need an explcit binary formatter, like Typst:
#let inttobins(n) = {
if n == 0 {
"0"
} else {
let d = ()
let m = n
while m > 0 {
if m.bit-and(1) == 1 {
d.insert(0, "1")
} else {
d.insert(0, "0")
}
m = calc.quo(m, 2)
}
d.join("")
}
}
#let binarydate(a) = {
a.split("-").map(n => inttobins(int(n))).join("-")
}
Task 2: Odd Letters
You are given a string.
Write a script to find out if each letter in the given string
appeared odd number of times.
I've done enough problems where a counter, i.e. a map of values to
their frequency of occurrence, is needed (and in Rust I can use the
counter
crate to do this directly) that I've developed library
functions for generating them automatically (where it's more than
trivial). Then it's just a matter of testing the values, ideally with
an all
operator where it's available. Crystal:
def counterify(a)
cc = Hash(Char, Int32).new(default_value: 0)
a.each do |x|
cc[x] += 1
end
return cc
end
def oddletters(a)
c = counterify(a.chars)
c.values.all? { |v| v % 2 == 1 }
end
Full code on
github.