Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two arrays using functional style

I was looking at one of the questions How to merge two sorted arrays, and trying hard to convert the solution using Java 8 streams. But still no success. Actually, nothing useful that I can share here.

There has to be a way to handle such loops using indexes in functional programming. How would this been done in other languages, like Scala, Clojure, without changing the time complexity? May be then I can just try to copy it in Java.

Edit: The code mentioned the question is the most efficient, and I don't want to compromise on it.

like image 511
sidgate Avatar asked Aug 10 '16 07:08

sidgate


People also ask

How do I combine two arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

Which function method can be used to combine two arrays?

concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do I combine arrays I already created?

concat(array1, array2) to merge 2 or more arrays. These approaches are immutable because the merge result is stored in a new array. If you'd like to perform a mutable merge, i.e. merge into an array without creating a new one, then you can use array1.

How do I merge two arrays in TypeScript?

The Array. concat() is an inbuilt TypeScript function which is used to merge two or more arrays together. Parameter: This method accepts a single parameter multiple time as mentioned above and described below: valueN : These parameters are arrays and/or values to concatenate.


1 Answers

in fact there is the same approach everywhere: you recur over two collections, adding least of collections' heads to the result, and recurring with the rest, until one of collections (or both) is empty. In clojure:

(defn merge-sorted [pred coll1 coll2]
  (loop [coll1 coll1 coll2 coll2 res []]
    (cond (or (empty? coll1) (empty? coll2)) (concat res coll1 coll2)
          (pred (first coll1) (first coll2)) (recur (rest coll1)
                                                    coll2
                                                    (conj res (first coll1)))
          :else (recur coll1 (rest coll2) (conj res (first coll2))))))

user> (merge-sorted < [1 3 5 6 7 8 9 40 50] [1 2 5 10 100])
(1 1 2 3 5 5 6 7 8 9 10 40 50 100)
like image 138
leetwinski Avatar answered Oct 20 '22 01:10

leetwinski