Skip to content

Commit 557035e

Browse files
committed
feat: added MovingAverageQueue
1 parent ab39bb6 commit 557035e

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* FXGL - JavaFX Game Library. The MIT License (MIT).
3+
* Copyright (c) AlmasB (almaslvl@gmail.com).
4+
* See LICENSE for details.
5+
*/
6+
7+
package com.almasb.fxgl.core.collection
8+
9+
/**
10+
* A "buffer" queue that keeps track of the moving average based on all elements.
11+
*
12+
* @author Almas Baimagambetov (almaslvl@gmail.com)
13+
*/
14+
class MovingAverageQueue(private val maxSize: Int) {
15+
16+
private var sum = 0.0
17+
18+
var average = 0.0
19+
private set
20+
21+
private val queue = ArrayDeque<Double>(maxSize)
22+
23+
fun put(item: Double) {
24+
if (queue.size == maxSize) {
25+
val oldItem = queue.removeFirst()
26+
27+
sum -= oldItem
28+
}
29+
30+
queue.addLast(item)
31+
32+
sum += item
33+
average = sum / queue.size
34+
}
35+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* FXGL - JavaFX Game Library. The MIT License (MIT).
3+
* Copyright (c) AlmasB (almaslvl@gmail.com).
4+
* See LICENSE for details.
5+
*/
6+
@file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE")
7+
package com.almasb.fxgl.core.collection
8+
9+
import org.hamcrest.MatcherAssert.assertThat
10+
import org.hamcrest.Matchers
11+
import org.junit.jupiter.api.BeforeEach
12+
import org.junit.jupiter.api.Test
13+
14+
/**
15+
*
16+
* @author Almas Baimagambetov (almaslvl@gmail.com)
17+
*/
18+
class MovingAverageQueueTest {
19+
20+
private lateinit var queue: MovingAverageQueue
21+
22+
@BeforeEach
23+
fun setUp() {
24+
queue = MovingAverageQueue(100)
25+
}
26+
27+
@Test
28+
fun `Average`() {
29+
repeat(50) {
30+
queue.put(25.0)
31+
}
32+
33+
assertThat(queue.average, Matchers.closeTo(25.0, 0.0001))
34+
35+
repeat(10) {
36+
queue.put(27.0)
37+
}
38+
39+
assertThat(queue.average, Matchers.closeTo(25.33, 0.01))
40+
41+
repeat(40) {
42+
queue.put(27.0)
43+
}
44+
45+
assertThat(queue.average, Matchers.closeTo(26.0, 0.0001))
46+
47+
repeat(100) {
48+
queue.put(30.0)
49+
}
50+
51+
assertThat(queue.average, Matchers.closeTo(30.0, 0.0001))
52+
}
53+
}

0 commit comments

Comments
 (0)