Skip to content

Commit

Permalink
Merge pull request #149 from primo-ppcg/merge-sorted
Browse files Browse the repository at this point in the history
Add `merge-sorted`, `merge-sorted-by`
  • Loading branch information
bakpakin authored Aug 23, 2023
2 parents 6e73b5a + 0c192ad commit 354873b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
23 changes: 23 additions & 0 deletions spork/misc.janet
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,29 @@
(array/insert arr (binary-search-by x arr f) x))
arr)

(defn merge-sorted
``Merges two sorted arrays so that the result remains sorted, using an optional comparator.
If no comparator is given, `<` is used.``
[a b &opt <?]
(default <? <)
(def len (+ (length a) (length b)))
(def res (array/new-filled len))
(var [i j] [0 0])
(forv k 0 len
(def [u v] [(get a i) (get b j)])
(cond
(= nil u) (do (put res k v) (++ j))
(= nil v) (do (put res k u) (++ i))
(<? u v) (do (put res k u) (++ i))
(do (put res k v) (++ j))))
res)

(defn merge-sorted-by
``Merges two sorted arrays so that result remains sorted when `f` is called on each element,
comparing the values with `<`.``
[a b f]
(merge-sorted a b |(< (f $0) (f $1))))

(def- id-bytes 10)
(defn make-id
```
Expand Down
20 changes: 20 additions & 0 deletions test/suite0020.janet
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,24 @@
@[1 2 3])
"array/insert-sorted-by 4")

(assert (deep= (misc/merge-sorted @[2 3 6 7] @[1 4 5 8])
@[1 2 3 4 5 6 7 8])
"misc/merge-sorted 1")
(assert (deep= (misc/merge-sorted @[3 2 1] @[8 7 6 5 4] >)
@[8 7 6 5 4 3 2 1])
"misc/merge-sorted 2")
(assert (deep= (misc/merge-sorted @[1 2 3 4 5 6 7 8] @[] |(error "invoked callback needlessly!"))
@[1 2 3 4 5 6 7 8])
"misc/merge-sorted 3")

(assert (deep= (misc/merge-sorted-by @[2 3 6 7] @[1 4 5 8] identity)
@[1 2 3 4 5 6 7 8])
"misc/merge-sorted-by 1")
(assert (deep= (misc/merge-sorted-by @[3 2 1] @[8 7 6 5 4] -)
@[8 7 6 5 4 3 2 1])
"misc/merge-sorted-by 2")
(assert (deep= (misc/merge-sorted-by @[1 2 3 4 5 6 7 8] @[] |(error "invoked callback needlessly!"))
@[1 2 3 4 5 6 7 8])
"misc/merge-sorted-by 3")

(end-suite)

0 comments on commit 354873b

Please sign in to comment.