I’ve been doing the Weekly
Challenges. The
latest
involved string breakdowns and coordinates. (Note that this ends today.)
Task 1: Power String
You are given a string.
Write a script to return the power of the given string.
The power of the string is the maximum length of a non-empty
substring that contains only one unique character.
One could probably do this as a one-liner but I prefer to lay it out.
When I see a new character, set the count to one; when I see the same
character, add one to it. Perl:
sub powerstring($a) {
my $mx = 0;
my $prev = 'A';
my $cur = 0;
foreach my $c (split '', $a) {
if ($cur > 0 && $c eq $prev) {
$cur++;
} else {
$cur = 1;
$prev = $c;
}
$mx = max($mx, $cur);
}
$mx;
}
Task 2: Meeting Point
You are given instruction string made up of U (up), D (down), L (left) and R (right).
Write a script to return true if following the instruction, you meet
the starting point (0,0).
I disagree with example 5: it ends up at (2, 2) and therefore doesn't
get back to (0, 0). Unless the task is meant to be "at any point along
the way" rather than "at the end of the sequence", but that's not
stated and I chose to solve the more interesting version that admits
of a short-cut rather than counting up all the coordinate values. Rust:
use counter::Counter;
fn meetingpoint(a: &str) -> bool {
let c = a.chars().collect::<Counter<_>>();
c[&'U'] == c[&'D'] && c[&'L'] == c[&'R']
}
Here's the solution to the other version, also in Rust:
fn meetingpoint(a: &str) -> bool {
let mut x = 0i32;
let mut y = 0i32;
for c in a.chars() {
match c {
'R' => {
x += 1;
},
'L' => {
x -= 1;
},
'U' => {
y += 1;
},
'D' => {
y -= 1;
},
_ => {}
};
if x == 0 && y == 0 {
return true;
}
}
false
}
Full code on
github.