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
}
CodePudding user response:
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 parts, if less than size, will be returned too, if set to false, it will be omitted.
CodePudding user response:
The sizes you are checking seem arbitrary. Like if the input size is 9, it would crash at amps[9]
. You should be checking >=
multiples of 10 in your if statement since you are grouping chunks of 10.
Also, there doesn't seem much point in using a Map where the keys are consecutive Ints starting from 0. It might as well be a List. If you can return a List, your whole function could be:
return amps.chunked(10, Iterable<Int>::sum)
If you do need a Map, you can do
return amps.chunked(10, Iterable<Int>::sum)
.mapByIndexed { i, list -> i to list }
.toMap()
If you need the option of dropping the last group if it's smaller than 10, then the other answer with windowed
is more appropriate.
If chunked
and windowed
were not available, your code could be shortened using the subList()
function and a loop. For example:
fun getTotal(amps:List<Int>): MutableMap<Int, Int>{
val listEqual = mutableMapOf<Int,Int>()
repeat(5) { chunkIndex ->
if (amps.size >= chunkIndex * 10 10) {
listEqual[chunkIndex] = amps.subList(chunkIndex * 10, chunkIndex * 10 10).sum()
}
}
return listEqual
}