I have a set of Characters A to Z which are represented by int64 1,2,3…,26 in a set. I want to remove the smallest character A from the set but my code does not work and I could not figure out why
"""
Create a set of 26 alphabets
"""
AlphabetSet = Set{Int64}(1:26)
@inline function elementsofset(S::Set)
return [ element for element in S ]
end
function elementsofsetsorted(S::Set,args...)
return sort(elementsofset(S,args...))
end
arrayofelements = elementsofset(AlphabetSet)
sortedarrayofelements = elementsofsetsorted(AlphabetSet)
function pop_smallest!(S::Set)
temparr = elementsofsetsorted(S)
element = popfirst!(temparr)
S = Set(temparr)
return element
end
z = pop_smallest!(AlphabetSet)
println(length(AlphabetSet))
println(AlphabetSet)
The function, as is, is not very efficient. Getting the smallest element, does not require sorting all the elements. The other big problem is that S = Set(temparr) does not mutate S as intended, it just binds the S name to a different set, leaving the set variable in the calling scope bound to the original set, and thus unchanged.
A working way of implementing this could be:
function pop_smallest!(S::Set)
e = minimum(S)
delete!(S, e)
return e
end
minimum(elementsofset(S)) can be minimum(S) as minimum is defined on sets too. The elementsofset call creates a new vector of set elements which allocates and is wasteful.
If the set is very dynamic, i.e. elements are added and the minimum element removed many times, then you might want to consider a specialized data structure from DataStructures.jl package.