0

My goal is to combine an array of strings (apple,banana,orange) and an array of ints (4,1,3), then find the smallest int in that 2D array 1, and finally print the matching string to it banana. I tried using minOf and Arrays.deepToString , but they didn´t work together how I intended. If someone knows a better way maybe with pairs (I don´t know a lot about that), any help is appreciated!

fun main(){
    var fruits = arrayOf("apple","banana","orange")
    var ratings = intArrayOf(4,1,3)
    var combined = arrayOf(fruits, ratings)

//did not work
    println(minOf(Arrays.deepToString(combined)))
}
2
  • 2
    Kotlin is an OO language. Don't use two parallel arrays. Use a class Fruit, with a property name (banana, apple, etc.) and a property rating (4, 1, etc.). Create a List<Fruit>. Then use the methods of List to find the fruit which has the minimal rating. Commented Nov 17, 2019 at 8:57
  • But Kotlin is also a functional language, and you're encouraged to even mix functional and OO programming styles. Commented Nov 17, 2019 at 9:19

1 Answer 1

1

You could do something like this to first combine two arrays (you could also use lists, BTW) with zip, then find the minimum among the pairs, and deconstruct the pair fields again:

val fruits = arrayOf("apple", "banana", "orange")
val ratings = arrayOf(4, 1, 3)

val (minFruit, minRating) = fruits.zip(ratings).minBy {
        (_ /* Swallow the fruit as we don't need it here */ , rating) ->
    rating
} ?: throw IllegalArgumentException("Cannot find the minimum of an empty list.")

println(minFruit)
println(minRating)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.