I have a String array and I need to find what is the length of the shortest string. For example, for this string array ["abc", "ab", "a"]
I should get value 1
.
I wrote method that gets a string array and returns int value
val minLength = fun(strs: Array<String>): Int {
var minLength = strs[0].length
for (index in 1..strs.size - 1) {
val elemLen = strs[index].length
if (minLength > elemLen) {
minLength = elemLen
}
}
return minLength
}
Another approach is to use reduce
method
val minLengthReduce = strs.reduce ({
str1, str2 ->
if (str1.length < str2.length) str1 else str2
}).length
Is it possible to get int value directly from reduce()
method instead string value?
I found this question about reduce
and fold
methods.
Should I use fold method instead reduce?