Issue
I'm trying to generate a list with several values that add up to the total value. The list works properly, but I still want to ask if there are possibilities to optimize this better. I have tried several attempts with different functionalities but unfortunately this does not give the exact result.
I don't need the exact solution just a step in the right direction will help me a lot.
This is how the code looks right now.
fun getTotal(amps:List<Int>): MutableMap<Int, Int>{
val listEqual = mutableMapOf<Int,Int>()
if(amps.size > 8) {
listEqual[0] = listOf(
amps[0],
amps[1],
amps[2],
amps[3],
amps[4],
amps[5],
amps[6],
amps[7],
amps[8],
amps[9]
).sum()
if(amps.size > 18) {
listEqual[1] = listOf(
amps[10],
amps[11],
amps[12],
amps[13],
amps[14],
amps[15],
amps[16],
amps[17],
amps[18],
amps[19]
).sum()
if(amps.size > 28) {
listEqual[2] = listOf(
amps[20],
amps[21],
amps[22],
amps[23],
amps[24],
amps[25],
amps[26],
amps[27],
amps[28],
amps[29]
).sum()
if(amps.size > 38) {
listEqual[3] = listOf(
amps[30],
amps[31],
amps[32],
amps[33],
amps[34],
amps[35],
amps[36],
amps[37],
amps[38],
amps[39]
).sum()
if(amps.size > 47) {
listEqual[4] = listOf(
amps[40],
amps[41],
amps[42],
amps[43],
amps[44],
amps[45],
amps[46],
amps[47],
amps[48]
).sum()
}
}
}
}
}
return listEqual
}
Solution
fun getTotal(amps: List<Int>): Map<Int, Int> {
return amps
.windowed(10, 10, true)
.mapIndexed { index: Int, ints: List<Int> -> index to ints.sum() }
.toMap()
}
The part with windowed() looks likes this with named arguments:
.windowed(size = 10, step = 10, partialWindows = true)
It 'slides' over a list by step and returns size elements. If partialWindows is set to true, the last part, if less than size, will be returned too, if set to false, it will be omitted.
Answered By - lukas.j
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.