Making Room for Both Hands
My first attempt at coordinating both hands on an accordion sounded like a small argument between a piano and a cupboard. The bellows needed attention, the bass buttons were hiding from my fingers, and every note seemed to demand the same moment.
Suppose a beginner wants to practise one hand motion at a time. Given a collection of possible motions, each with a start and end beat, how many can fit without overlapping? This is the interval scheduling problem: choose the motion that finishes earliest, then repeat with whatever still fits. A motion may start on the beat another one ends.
motions = [(0, 3, "melody"), (1, 2, "bass"),
(2, 4, "chord"), (3, 5, "melody")]
end = 0
for start, finish, name in sorted(motions, key=lambda m: m[1]):
if start >= end:
print(f"{name}: {start}-{finish}")
end = finish
The result is bass: 1-2, followed by chord: 2-4. Picking the earliest start instead would take the first melody and leave room for only one more motion in this example. More generally, finishing earliest leaves at least as much room for later choices as any other first pick, which is why the greedy rule finds a maximum-size selection.
Zig makes the record and comparison explicit, while following the same little score:
const std = @import("std");
const Motion = struct { start: u8, end: u8, name: []const u8 };
fn earlier(_: void, a: Motion, b: Motion) bool { return a.end < b.end; }
pub fn main() void {
var motions = [_]Motion{
.{ .start = 0, .end = 3, .name = "melody" },
.{ .start = 1, .end = 2, .name = "bass" },
.{ .start = 2, .end = 4, .name = "chord" },
.{ .start = 3, .end = 5, .name = "melody" },
};
std.mem.sort(Motion, &motions, {}, earlier);
var end: u8 = 0;
for (motions) |m| if (m.start >= end) {
std.debug.print("{s}: {d}-{d}\n", .{ m.name, m.start, m.end });
end = m.end;
};
}
Sorting costs O(n log n); the selection pass is linear. The rule maximizes the number of motions, not their musical value: it might discard a long, lovely melody for several short bass notes. Real accordion playing also welcomes simultaneous hands. For a first practice plan, though, giving each motion its own space leaves a little more attention for the bellows.