I want to build an array of unique numbers that are being generated by a process.

In Ruby it would look something like this:

  arry << num unless arry.include? num

Is the following the fastest Nim way.

  if not (num in arry): arry.add(num)

2018-04-17 16:28:38

Or in Ruby, I can just keep adding numbers to the array and then return a unique array at the end.

a = [1,3,4,5,6,7,4,3,9,10,11,12,5]

a.uniq! => a = [1,3,4,5,6,7,9,10,11,12]

2018-04-17 17:03:59

if num notin arry: arry.add(num)

Please note that you should use notin instead of negating the in operator. This is the preferred way. It should also be the fastest. The only thing that the in operator does is call the contains proc on the given array, so there should be no more overhead than necessary (notin is simply a template which evaluates to something similar to what you wrote, but since templates are evaluated at compile-time they have no run-time cost).

That said, if you want something like Ruby's uniq, have a look at deduplicate. You can find it here, with lost of other Ruby-like procs for functional programming.

2018-04-17 17:16:39

amalek, I think "not (a in b)" is fine and the same as "a notin b". So notin keyword just saves the bracket.

And all in/contains operations on arrays should be O(N) of course, so will be not that fast for large arrays. So we may prefer to use sets or hashsets for data which should be unique. There was a thread about related topic once:

https://forum.nim-lang.org/t/2611#16168

2018-04-17 17:47:31
Hey thanks @amalek. I'll test and see what works best for my case. 2018-04-17 17:47:34

an array of unique numbers

use sets / HashSets?

2018-04-17 17:49:08

So @miran|@Stefan_Salewski using sets is faster than deduplicating an array in Nim?

Also, I ultimately want to sort the array. Will sets give me this automatically, or do I need to manually do this?

2018-04-17 17:55:28
jzakiya, when you have to sort, you may need a seq/array indeed. I think sorted sets only preserve insertion order. O(N) may be fast if N is small of course. See the reply of cblake to my above mentioned thread -- I think I used that approach once. 2018-04-17 18:10:37

Also, I ultimately want to sort the array. Will sets give me this automatically, or do I need to manually do this?

You need a seq for that. Sets aren't guaranteed to be ordered (even though they seem to remember insertion oreder, in practice, so if you want to rely on implementation-specific behaviour you could do it). Also, sets only accept a limited number of types. See here.

2018-04-17 18:15:24
Hey @Stefan, I did an import macros, srtutils but I get a undeclared identifier: 'deduplicate' compiler error.
2018-04-17 18:16:33
<<<••12••>>>