Skip to content

Commit

Permalink
Add CircularBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
prateekma committed May 12, 2019
1 parent 45a3e4a commit 41e7b58
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions core/src/main/kotlin/org/ghrobotics/lib/utils/CircularBuffer.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2018 FRC Team 5190
* Ryan Segerstrom, Prateek Machiraju
*/

package org.ghrobotics.lib.utils

import java.util.*

class CircularBuffer(private val size: Int) {

private val buffer: ArrayList<Double> = ArrayList(size)

private var numElements = 0
private var sum = 0.0

// Gets average of all elements
val average: Double
get() {
return if (numElements == 0)
0.0
else
sum / numElements
}

// Adds an element to the list
fun add(element: Double) {
if (numElements > size - 1) {
sum -= buffer[size - 1]
buffer.removeAt(size - 1)
numElements--
}
sum += element
buffer.add(0, element)
numElements++
}
}

0 comments on commit 41e7b58

Please sign in to comment.