Search code examples
scalascala-3

Scala Sorting With Ex Aqueo


I would like to sort my List[(String, List[Int])] with respect to the second element of the tuple, including ex aqueo elements ( in fp way :) ).

The element w is greater than the element z when:

  1. w.sum> z.sum,
  2. w.sum == z.sum, but w(0) > z(0),
  3. w.sum == z.sum, but w(3) > z(3)

(List always have 3 ints)

For example: val c = List(("hah", List(1,1,4)), ("dd", List(4,3,2)), ("aa", List(1,2,3)), ("qw", List(1,2,3)), ("qe", List(2,1,3)), ("w", List(10,0, -9)))

Output (can be in differetnt form of course) - (Place, Tuple, Sum Of Tuple._2):

  • First - ("dd", List(4,3,2)), 9
  • Second - ("qe", List(2,1,3)), 6
  • Third - ("hah", List(1,1,4)), 6
  • Fourth - ("qw", List(1,2,3)), 6
  • Fourth - ("aa", List(1,2,3)), 6
  • Sixth - ("w", List(10,0,-9)), 1

Thanks in advance!


Solution

  • scala> c.sortBy{ case(_, w) => (w.sum, w(0), w(2)) }.reverse
    val res1: List[(String, List[Int])] = List((dd,List(4, 3, 2)), (qe,List(2, 1, 3)), (hah,List(1, 1, 4)), (qw,List(1, 2, 3)), (aa,List(1, 2, 3)), (w,List(10, 0, -9)))