From 41e7b585adcb7f0ef5fa34124d1d4a537085242e Mon Sep 17 00:00:00 2001 From: Prateek Machiraju Date: Sun, 12 May 2019 13:31:30 -0400 Subject: [PATCH] Add CircularBuffer --- .../ghrobotics/lib/utils/CircularBuffer.kt | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 core/src/main/kotlin/org/ghrobotics/lib/utils/CircularBuffer.kt diff --git a/core/src/main/kotlin/org/ghrobotics/lib/utils/CircularBuffer.kt b/core/src/main/kotlin/org/ghrobotics/lib/utils/CircularBuffer.kt new file mode 100644 index 00000000..d43d1062 --- /dev/null +++ b/core/src/main/kotlin/org/ghrobotics/lib/utils/CircularBuffer.kt @@ -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 = 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++ + } +}