Here's a ubiquitous data structure in, say, game and UX programming:
- there're a fixed number of items (say, "5")
- they're all "zero" to begin with
- you can put one in on the "left" (FWIW I usually call it something like shove to distinguish from the usual meaning of push)
- once there are 5, each time you put a new one in on the left, the one on the "right" falls out and is gone
- in fact, it's not possible to / there's no need to access any individual item, ever
- you can get the total at any time
Here's a trivial naturalistic example. (Obviously, there're several ways to do it.)
I've always wondered if there's a common term for this.
I sometimes call it a "piece of pipe" (imagine a short piece of pipe that you can push tennis balls through from one end).
///A "pipe" ongoing sum. First in is first thrown-away.
class Pipe {
private var r: [Whatever] = []
private var i: Int = 0
private var k: Int = 0
///Start fresh, with a given fixed length.
public func begin(with: Int) {
k = with
r = Array(repeating: .zero, count: k)
i = 0
}
///Add one on the left
public func shove(p: CGPoint) {
r[i] = p
i = (i + 1) % k
}
///Supply the current value at this moment.
public var sum: CGPoint {
return r.reduce(.zero, +) / CGFloat(k)
}
///Debugging string.
public var say: String {
return r.reduce("pipe: "){ a,b in "\(a) .. \(b.say)"} + " t " + sum.say
}
}