How to resolve the algorithm Order two numerical lists step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Order two numerical lists step by step in the Scala programming language

Table of Contents

Problem Statement

Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Order two numerical lists step by step in the Scala programming language

Source code in the scala programming language

def lessThan1(a: List[Int], b: List[Int]): Boolean =
  if (b.isEmpty) false
  else if (a.isEmpty) true
  else if (a.head != b.head) a.head < b.head
  else lessThan1(a.tail, b.tail)


def lessThan2(a: List[Int], b: List[Int]): Boolean = (a, b) match {
  case (_, Nil) => false
  case (Nil, _) => true
  case (a :: _, b :: _) if a != b => a < b
  case _ => lessThan2(a.tail, b.tail)
}


def lessThan3(a: List[Int], b: List[Int]): Boolean =
  a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE)
   .find{case (a, b) => a != b}
   .map{case (a, b) => a < b}
   .getOrElse(false)


val tests = List(
  (List(1, 2, 3), List(1, 2, 3)) -> false,
  (List(3, 2, 1), List(3, 2, 1)) -> false,
  (List(1, 2, 3), List(3, 2, 1)) -> true,
  (List(3, 2, 1), List(1, 2, 3)) -> false,
  (List(1, 2), List(1, 2, 3)) -> true,
  (List(1, 2, 3), List(1, 2)) -> false
)

tests.foreach{case test @ ((a, b), c) =>
  assert(lessThan1(a, b) == c, test)
  assert(lessThan2(a, b) == c, test)
  assert(lessThan3(a, b) == c, test)
}


  

You may also check:How to resolve the algorithm FizzBuzz step by step in the zkl programming language
You may also check:How to resolve the algorithm Multi-dimensional array step by step in the Julia programming language
You may also check:How to resolve the algorithm Machine code step by step in the D programming language
You may also check:How to resolve the algorithm Percentage difference between images step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Exponentiation operator step by step in the J programming language