I have the following algorithm, presented here in a simplified version in Rusty pseudocode:
fn foo<T>(elements: list<T>, weights: list<float>, offset: float) -> Option<T> {
for i in 0..elements.length() {
offset -= weights[i];
if (offset <= 0) {
return Some(elements[i]);
}
}
return None;
}
in other words, given elements=["a", "b", "c"] and weights=[1, 3, 2], illustrated here as laying out the elements in a row as regions on a one-dimensional axis with their widths given by weights, and using offset as the point on the axis from which we pick the
region it's part of:
We'd expect:
foo(elements, weights, 0.9) == Some("a")
foo(elements, weights, 1.2) == Some("b")
foo(elements, weights, 2.5) == Some("b")
foo(elements, weights, 4.0) == Some("c")
foo(elements, weights, 5.0) == Some("c")
Or indeed, that foo(elements, weights, offset) returns "a" for any offset in [0.0, 1.0), "b" for any offset in [1.0, 4.0), "c" for any offset in [4.0, 6.0), and None otherwise.
This feels like a very common and basic algorithm and so I feel like it probably has a canonical name, but I don't know one and have not been successful in searching for one online. Does this algorithm have a common name?
![An illustration of the elements ["a", "b", "c"] with weights [1, 3, 2] laid out on an axis](https://i.stack.imgur.com/OQLpJ.png)