I have a list of strings as follows,
`|Country A|City A|Street A| => Foo
|Country A|City B|Street A| => Bar
|Country C|City B|Street B| => Gee
|Country A|*|Street E| => Unkown`
Each country, city and street represent a value like Foo.
Sometimes, the Country|City|State can be a wildcard(*) and then it represents a value Unkown.
Is there a data structure that I could use to represent this input.
As a user, when I enter a country|city|street combo, I expect to get a value. If it is not there, then it returns empty.
I guess I should use some sort of tree strucutre to store this data. But I am not sure how it would be structured.
Why do you want to use a data structure. Try encapsulating this in a class and then creating methods that do your calculations for you. It will make things simpler for you and anyone else who works on your code if you abstract things into separate classes and perform functions/methods objects.
In this example you could create a method that does your comparison and create a class that houses country/city/state.
Related
I need to get some values for a hash but, I don't know how can I do it!
My data:
data = {
name: "Pedro Álvares",
age: 35,
sensitive_data: {
cpf_cnpj=>27046645678,
fantasy_name: "I have the power"
}
}
I search for ruby methods and find the method values_at, but this method gets only the first_data like name, age.
If I use:
name = data.values_at(:name)
the field returned is Pedro Álvares
but if I try use:
fantasy_name = data.values_at(:fantasy_name)
the data returned is nil.
How can I get the field without using data[:sensitive_data][:fantasy_name]?
Because you know the correct structure of the hash you should write:
data[:sensitive_data][:fantasy_name]
#=> "I have the power"
You should not use dig here. Why? Suppose you accidently wrote
data.dig(:sesnitive_data, :fantasy_name)
The would return nil (because data has no key :sesnitive). Depending on the context the error might not surface until sometime later, making debugging more difficult than is necessary.
By contrast, if you wrote
data[:sesnitive_data][:fantasy_name]
data[:sesnitive_data] would return nil (because data has no key :sesnitive_data) and then nil[:sesnitive_data] would raise an exception, informing you that nil has no method []. That is precisely what you want to happen: you want to be notified of the error immediately, and have the reason for it it pinpointed, so you can easily correct your code.
Hash#dig, Array#dig and Struct#dig (which call each other) have their uses (when you do not know the structures of objects in advance--a hash's keys, for example), but those methods should not be used when an object's structure is known.
You could get the nested value by dig method:
data.dig(:sensitive_data, :fantasy_name) # => "I have the power"
I am attempting to populate an array of tuples in a for-loop. The array needs to be predefined.
I am trying to do something along the following lines:
for class in keys(classes)
arr[class]=pmap(y->func(arg,y),1:length(arg1),batch_size=Int(round(length(arg)/nworkers())))
end
In the specific case, classes is a dictionary of type Dict{String,Tuple{Int64,Int64}}. For e.g. classes=Dict("Item1" => (5000,10000), "Item2" => (5000,10000))
The type-definition of broadcasting operation pmap(...) when class is Item1 is an Array{Tuple{Float64,Float64,Float64,Array{Float64,1}},1}. What is an appropriate way of preallocating arr?
arr[Item1] will be of type Array{Tuple{Float64,Float64,Float64,Array{Float64,1}},1}. So, I presume arr would have to defined as an Array{Array{Tuple{Float64,Float64,Float64,Array{Float64,1}},1}}, or something to this extent. But, I couldn't come up with the right notation for defining this.
It seems like I have overthought this; defining arr as a Dict{String,Array{Tuple{Float64,Float64,Float64,Array{Float64,1}},1}} was helpful.
In Java, the equals/hash functions can be customised simply by overriding/implementing methods on a class.
This is very useful when you want to customise uniqueness of your class - so that you can check for 'duplicates' in a set easily.
How would you do the same thing in Elixir, specifically with ETS?
One way to do what I need to do is by making a unique hash function (that can return any type). There should only be one unique output of this hash function per unique input.
Then you can store the {hash, val} tuples:
table = :ets.create(:table, [])
:ets.insert(table, {hash(val), val})
:ets.lookup(table, hash(val))
In a previous question I asked how I could show the contents of a Dictionary in a GUI. I started from this idea to build a GUI with a slightly better look and feel. It mainly consists of RectangleMorphs glued together in columns and rows (cfr. the accepted answer in my previous question).
The problem now is that I would like my table to be updated when elements are added/removed/edited in my dictionary. I managed to write some Morph that consists of columns of CellMorphs, which inherit from RectangleMorph and have model and message as instance variables with the following update message:
update
" update the contents of this cell "
| value |
self removeAllMorphs.
(model = nil or: message = nil)
ifTrue: [ value := '' ]
ifFalse: [ value := model perform: message ].
self addMorph: value asMorph.
As can be seen, the CellMorph is a container for a Morph containing the actual content of the cell. This works great for displaying the size of the dictionary for instance:
d := Dictionary new.
d at: 'foo' put: 100.
d at: 'bar' put: 200.
cell := CellMorph new
model: d;
message: #size;
color: Color white.
cell openInWorld.
d at: 'boo' put: 300. " cell will be updated "
but I don't seem to get something similar working for the contents of the dictionary, because I can't find a way to access single keys or values with a message. The only solution I can think of is to create new columns with new cells every time, but this is so expensive and I can't imagine that this is a good idea...
Therefore my question:
Is there a way to update my Morph displaying the dictionary without creating billions of my CellMorphs or should I forget about my idea and rather work with rows of CellMorphs for instance in order to group the entries in the dictionary?
for completeness: the model: message in CellMorph looks like:
model: newModel
"change the model behind this cell"
model ifNotNil: [ model removeDependent: self ].
newModel ifNotNil: [newModel addDependent: self].
model := newModel.
self update.
update: aParameter does nothing more than call update. and I also added self changed. in all messages of Dictionary that I want the interface to be notified of (at: put:, removeKey:, etc.).
In the instance variable named 'message' you could have a Message object, instead of having only the selector.
An instance of Message has the receiver, selector and arguments. So, you could configure it with the dictionary keys sorted asArray in the receiver, the selector #at: and an index, to get a specific key. Accessing the value would be getting the value at: that key in the dictionary.
I think that a Message is not executed with object perform: message, you should check. message perform should work because it already has the receiver.
In any case, this complexity may show that having only (one) model and (one) message is not enough to get the model in th granularity you want, and you can possibly specialize a bit more, using the knowledge that the model is a dictionary. For instance, having an instance variable for key or for keyIndex.
Some side notes about the code:
(model = nil or: message = nil)
has comparisons with nil, that can be replaced by #isNil message or, if you want to stick with equality, use the faster == to compare identity, since nil is unique.
#or: is used to get the benefits of partial evaluation (the argument is evaluated only if the receiver is false). But that only works if you have a block as argument, otherwise the expression is evaluated before, to get the argument for the message in the stack.
So I have two model objects who hold similar data yet have different attribute names for them. I'll simplify the list for brevity and clarity. I want to actually make a temporary object with the info, compare the objects, and then update one if some of the data has changed. I'm open to suggestions about how to better accomplish this (please keep in mind that there are a lot more attributes then I'm showing)
Member object has the attributes employeenumber, employeefirstname and employeelastname
Censusitem object has the attributes employee_id, employee_fn, employee_ln
I have a has with the fields mapped over that I thought would simplify this:
maps={
employeenumber: :employee_id,
employeefirstname: :employee_fn,
employeelastname: :employee_ln
}
I thought I could then loop them and assign them somehow, but I'm obviously not even close:
def clean_member(censusitem, maps)
tempmember=Member.new
maps.each do |mname,ciname|
tempmember.i[o]=censusitem.i[1]
end
return tempmember
end
Feel like I'm missing something big, which is very normal for me;-) Any help would be greatly appreciated!
Mark
I believe this should work:
def clean_member(censusitem, maps)
tempmember=Member.new
maps.each do |mname,ciname|
tempmember.send("#{mname}=", censusitem.send(ciname))
end
return tempmember
end