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 * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * 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 * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
@ -25,8 +25,7 @@
package it.norangeb.algorithms.exercises package it.norangeb.algorithms.exercises
class PrefixAverage { object PrefixAverage {
companion object {
fun prefixAverage(arrayIn: IntArray): IntArray { fun prefixAverage(arrayIn: IntArray): IntArray {
val arrayOut = IntArray(arrayIn.size) val arrayOut = IntArray(arrayIn.size)
@ -39,5 +38,16 @@ class PrefixAverage {
return arrayOut 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
}
}
} }
} }

View File

@ -67,4 +67,42 @@ class PrefixAverageTest {
arrayOut `should equal` intArrayOf(21, 21, 21, 21, 21) 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)
}
} }