Skip to content

Instantly share code, notes, and snippets.

@michaellwest
Created July 11, 2020 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaellwest/d7712f97bd3fba6109ea2369e50347c6 to your computer and use it in GitHub Desktop.
Save michaellwest/d7712f97bd3fba6109ea2369e50347c6 to your computer and use it in GitHub Desktop.
A calculator to return the average of the last number of x items. This can be useful when you want to estimate time remaining.
# Converted from this answer: https://stackoverflow.com/a/44318312/1277533
class AverageCalculator {
[System.Collections.Queue]$Queue
[long]$Total
[int]$Size
AverageCalculator([int]$Size) {
$this.Queue = New-Object System.Collections.Queue
$this.Size = [Math]::Max($Size, 1)
}
[int]CalculateAverage($num) {
$this.Total += $num
$this.Queue.Enqueue($num)
if($this.Queue.Count -gt $this.Size) {
$this.Total -= $this.Queue.Dequeue()
}
$average = $this.Total / $this.Queue.Count
return $average
}
}
$calculator = New-Object AverageCalculator 7
1..1000 | % {
$num = Get-Random -Minimum 0 -Maximum 4
$average = $calculator.CalculateAverage($num)
$left = $average * (1000 - $_)
Write-Host $left
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment