Set

Set is a container with no duplicate values. It supports all data types except functions or handles.

Creating Sets

We can create sets with the function set.

x=set([5,5,3,4]);
x;
// output
set(4,3,5)

y=set(8 9 9 4 6);
y;
// output
set(6,4,9,8)

Set Operations

Intersection (&)

x & y;
// output
set(4)

Union (|)

x | y;
// output
set(8,9,6,5,3,4)

Sub (-)

x-y;
// output
set(3,5)

y-x;
// output
set(6,9,8)

Symmetric Difference (^)

y^x;
// output
set(5,3,6,9,8)
x^y;
// output
set(8,5,3,6,9)

Convert sets to vectors (with keys())

x.keys();
// output
[4,3,5]

Set Operators

Different sets can be compared with each other using set operators:< <=, >, >=, ==, !=, and in.

If X is a subset of Y then X<=Y.

x=set([4, 6]);
x;
// output
set(6,4)
y=set(8 9 9 4 6);
y;
// output
set(6,4,9,8)

x<=y;
// output
1
// x is a subset of y

y>=x;
// output
1

If X and Y have identical elements then X==Y; if they do not have identical elements then X!=Y.

z=set(8 9 4 6);
y==z;
// output
1
// the set y and the set z contain the same elements.

y in z;
// output
[1,1,1,1]

x in z;
// output
[1,1]

x!=z;
// output
1

z>=x;
// output
1

Set modifications

Append a set

y=set(8 9 9 4 6);
y;
// output
set(6,4,9,8)

y.append!(3);
// output
set(3,6,4,9,8)

Remove an element from a set with function erase!.

y.erase!(3);
// output
set(6,4,9,8)

Empty a set with function clear!.

y.clear!();
// output
set()

Search in a set

Since the data form set is implemented as a hash table, searching an element in a set is generally faster than searching an element in a vector. However, it can take a significant amount of time to establish a hash table. Therefore searching in a set makes sense only if we need to do it repeatedly.

x=1..20000000;
shuffle!(x);
// output
[3123455,13242159,6705807,6107095,10703880,14924328,4435139,19888822,11885962,8535552,17956796,7349822,14777562,13918572,8570589,10706038,6508545,12362405,12742059,16485330,14219242,16979158,6060092,18157360,16132016,12510810,14509873,4402923,6277378,11762392...]

timer y=set(x);
// output
Time elapsed: 8101.53 ms
y;
// output
set(14261183,6712062,10066096,14147249,10177467,6928135,15470317,1348143,19503158,9781988,12709425,3357820,7105084,8740796,10555072,15523011,17319678,19672048,5332111,17767151,4598557,10395083,9715094,8630928,12345383,12834953,11278593,2637131,11464014,14018258...)

timer(1000){19884856 in x};
// output
Time elapsed: 1191.52 ms

timer(1000){19884856 in y};
// output
Time elapsed: 0 ms