Holochain Forum

New "stacked average" pattern for cost-effective average calculation in frequently updated entries

Hello community, as you know, data mining is a complicated subject when taking about holochain. We do not want to make an excessive number of petitions and we want every app to be able to run in any basic device. That’s why I’m looking for a way to make the computation of averages fast and efficient.

That’s when the “stacked average” (just came up with that name, suggestions are open) pattern comes in. Consider the following scenario:

We have a variable inside an entry of which we want to know the average value, let’s say:

struct TennisMatch {
    duration: u64
}

We could always get all of the tennis matches ever played and calculate the average every time we need it or we could do this:

struct TennisMatch {
    duration: u64
}
struct TennisMatchHistory {
    average_duration: u64
}

Great! but how are we going to know how to change the average_duration after every match? Well, we can add a helper variable that takes care of that:

struct TennisMatch {
    duration: u64
}
struct TennisMatchHistory {
    average_duration: u64,
    number_of_games: u32
}

And after every match, we could do this:

let new_history = TennisMatchHistory {
    average_duration: (
            previous_history.average_duration * previous_history.number_of_games +
            new_match.duration
        ) / (previous_history.number_of_games + 1),
    number_of_games : previous_history.number_of_games + 1
}

update_history(new_history)

This way, the latest history entry will always have an updated average. What do you think? Is this pattern viable?