Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to merge two vectors in Scala

1 Answer

0 votes
object MergeTwoVectors_Scala {
  def mergeTwoVectorsIntoOne(num1: Vector[Int], num2: Vector[Int]): Vector[Int] = {
    var numbers:Vector[Int] = Vector()
    var i, j = 0

    while (i < num1.length && j < num2.length) {
      if (num1(i) <= num2(j)) {
        numbers = numbers :+ num1(i)
        i += 1
      } else {
        numbers = numbers :+ num2(j)
        j += 1
      }
    }

    while (i < num1.length) {
      numbers = numbers :+ num1(i)
      i += 1
    }

    while (j < num2.length) {
      numbers = numbers :+ num2(j)
      j += 1
    }

    numbers
  }

  def main(args: Array[String]): Unit = {
    val num1 = Vector(7, 3, 2, 9, 1)
    val num2 = Vector(5, 8, 6, 4, 0, 11, 10, 12)

    val numbers = mergeTwoVectorsIntoOne(num1, num2)

    numbers.foreach(num => print(s"$num "))
  }
}




/*
run:

5 7 3 2 8 6 4 0 9 1 11 10 12 

*/

 



answered Oct 9, 2024 by avibootz
...