From 5b4368ba63e19e06841d04e96896db1ab3a65e63 Mon Sep 17 00:00:00 2001 From: Ben Scholar Date: Wed, 30 Jan 2019 17:49:08 -0800 Subject: [PATCH] Added Circular Buffers for Convenience (#26) * circular buffers * fix * Update build.gradle --- build.gradle | 2 +- .../team5499/monkeyLib/util/CircularBuffer.kt | 29 +++++++++++++++++++ .../monkeyLib/util/CircularDoubleBuffer.kt | 18 ++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/org/team5499/monkeyLib/util/CircularBuffer.kt create mode 100644 src/main/kotlin/org/team5499/monkeyLib/util/CircularDoubleBuffer.kt diff --git a/build.gradle b/build.gradle index 437124e..50b5f3d 100644 --- a/build.gradle +++ b/build.gradle @@ -32,7 +32,7 @@ dependencies { } group = 'org.team5499' -version = '2.2.1' +version = '2.3.0' task sourcesJar(type: Jar) { from sourceSets.main.allJava diff --git a/src/main/kotlin/org/team5499/monkeyLib/util/CircularBuffer.kt b/src/main/kotlin/org/team5499/monkeyLib/util/CircularBuffer.kt new file mode 100644 index 0000000..f4cd0d6 --- /dev/null +++ b/src/main/kotlin/org/team5499/monkeyLib/util/CircularBuffer.kt @@ -0,0 +1,29 @@ +package org.team5499.monkeyLib.util + +public open class CircularBuffer(maxSize: Int) { + + private val mMaxSize: Int + + public val elements: MutableList + + init { + mMaxSize = maxSize + if (mMaxSize <= 0) { + throw IllegalArgumentException("maxSize must be a positive integer.") + } + elements = mutableListOf() + } + + public fun add(element: T): T? { + elements.add(element) + if (elements.size > mMaxSize) { + val poppedValue = elements.removeAt(0) + return poppedValue + } + return null + } + + public fun clear() { + elements.clear() + } +} diff --git a/src/main/kotlin/org/team5499/monkeyLib/util/CircularDoubleBuffer.kt b/src/main/kotlin/org/team5499/monkeyLib/util/CircularDoubleBuffer.kt new file mode 100644 index 0000000..c5a244d --- /dev/null +++ b/src/main/kotlin/org/team5499/monkeyLib/util/CircularDoubleBuffer.kt @@ -0,0 +1,18 @@ +package org.team5499.monkeyLib.util + +public class CircularDoubleBuffer(maxSize: Int) : CircularBuffer(maxSize) { + + public val sum: Double + get() { + var total = 0.0 + for (num in super.elements) { + total += num + } + return total + } + + public val average: Double + get() { + return sum / super.elements.size.toDouble() + } +}