The most elegant way to remove certain numbers from a vector?

Assume I have this vector:

amounts [
15679
245672
345671
445676
541677
544673
546676
648672
749679
941679
]

Assume I want to remove the numbers under 544673. Can anyone suggest what would be elegant? I realize I can do a loop or a reduce but I assume there might be something more elegant?

Use filterv.

That’s great. This does what I need:

(filterv #(> % 10022) amounts)

Works really well. I used this:

(filterv #(not= 3 %) [1 2 4 3 3 5 3 6])
;; [1 2 4 5 6]

If they are sorted in ascending order

(->> amounts (take-while #(< % 544673)) vec)

;;or, slightly more efficient using transducer + transient behind the scene

(into [] (take-while #(< % 544673)) amounts)

There are even more efficient ways, depending on performance considerations. You could binary search for the index of the last entry < 5446773, then use subvec to derive a vector slice in o(1) time. So derive a “new” vector in O (log(n)) (original would still be referenced transitively though…).

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.