implement prefix average in recursive way

This commit is contained in:
Raffaele Mignone 2019-03-22 17:40:01 +01:00
parent cc28928e40
commit 2abd5aaa1d
Signed by: norangebit
GPG Key ID: F5255658CB220573
2 changed files with 60 additions and 12 deletions

View File

@ -6,7 +6,7 @@
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* to use, copy, modify, tryMerge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
@ -25,19 +25,29 @@
package it.norangeb.algorithms.exercises
class PrefixAverage {
companion object {
fun prefixAverage(arrayIn: IntArray): IntArray {
object PrefixAverage {
fun prefixAverage(arrayIn: IntArray): IntArray {
val arrayOut = IntArray(arrayIn.size)
var currentSum = 0
val arrayOut = IntArray(arrayIn.size)
var currentSum = 0
for (i in 0 until arrayIn.size) {
currentSum += arrayIn[i]
arrayOut[i] = currentSum / (i + 1)
for (i in 0 until arrayIn.size) {
currentSum += arrayIn[i]
arrayOut[i] = currentSum / (i + 1)
}
return arrayOut
}
fun recursivePrefixAverage(arrayIn: IntArray, position: Int = 0, acc: Int = 0): IntArray {
return when (position) {
arrayIn.size -> IntArray(arrayIn.size)
else -> {
val newAcc = arrayIn[position] + acc
val array = recursivePrefixAverage(arrayIn, position + 1, newAcc)
array[position] = newAcc / (position + 1)
array
}
return arrayOut
}
}
}
}

View File

@ -67,4 +67,42 @@ class PrefixAverageTest {
arrayOut `should equal` intArrayOf(21, 21, 21, 21, 21)
}
@Test
fun testNominalCaseRecursive() {
val arrayIn = intArrayOf(21, 23, 25, 31, 20, 18, 16)
val arrayOut = PrefixAverage.recursivePrefixAverage(arrayIn)
arrayOut `should equal` intArrayOf(
21, 22, 23, 25, 24, 23, 22
)
}
@Test
fun testEmptyArrayRecursive() {
val arrayIn = intArrayOf()
val arrayOut = PrefixAverage.recursivePrefixAverage(arrayIn)
arrayOut `should equal` intArrayOf()
}
@Test
fun testOneElementArrayRecursive() {
val arrayIn = intArrayOf(25)
val arrayOut = PrefixAverage.recursivePrefixAverage(arrayIn)
arrayOut `should equal` intArrayOf(25)
}
@Test
fun testAlwaysSameElementArrayRecursive() {
val arrayIn = intArrayOf(21, 21, 21, 21, 21)
val arrayOut = PrefixAverage.recursivePrefixAverage(arrayIn)
arrayOut `should equal` intArrayOf(21, 21, 21, 21, 21)
}
}