1

Say I have a List of Tuples of Integers

var i = Array(1->3, 5->9, 15->18)

How can I return a Tuple of the highest and lowest values from the above?

So for the above input, 1-> 18 should be returned as 1 is the lowest and 18 is the highest value. Here's the skeleton of the function that takes an Array of Tuples and returns the highest & the lowest values as a Tuple.

    def returnHighest(i: Array[(Int, Int)]): (Int, Int)={

      ....

  }

2 Answers 2

1

Lot's of ways to do this of course. Here is one:

val i = Array(1->3, 5->9, 15->18)
i: Array[(Int, Int)] = Array((1,3), (5,9), (15,18))

scala> val flatI = i.flatMap{case(a,b) => List(a, b)}
flatI: Array[Int] = Array(1, 3, 5, 9, 15, 18)

scala> flatI.min -> flatI.max
res3: (Int, Int) = (1,18)
Sign up to request clarification or add additional context in comments.

Comments

0

You could use foldLeft, but you need to be careful about the start value. What if the array is empty ?

val res4 = Array(1->3, 5->9, 15->18)
res4.foldLeft(res4(0))({
    case (acc, i) =>
      Math.min(acc._1, i._1) -> Math.max(acc._2, i._2)
  }) 
res6: (Int, Int) = (1, 18)

1 Comment

Since order doesn't matter, and you're failing on an empty list anyway, you can just use res4.reduce { (t1, t2) => (Math.min(t1._1, t2._1), Math.max(t1._2, t2._2)) }.

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.