Algorithm for visiting nodes only once - algorithm

Let's say I have an array of N elements. I call a recursive function somehow like this: (no specific language here, just pseudocode)
recursive(myArray){
// do something awesome and provide base case etc
// also get mySecondArray based on myArray
for(i=0;i<mySecondArray.length;i++){
recursive(mySecondArray[i];
}
}
As you can see I need to call this function on every element of another array created inside based on some conditions and other functions called on myArray.
The problem I am having is that mySecondArray always has some of the elements that were already in myArray. I do not want to call recursion again on those elements.
Q: What would be the best algorithm approach to solve this?
If you need more info just let me know (I didn't get into details since it gets more complicated)
Thanks

You can have a hashmap/set/dictionary/whatever-you-call-it to look up the elements.
Python solution:
def recursive(myArray, mySet = None):
if mySet is None:
mySet = { myArray }
else:
mySet.add(myArray)
for mySecondArray in myArray:
if mySecondArray not in mySet:
recursive(myArray, mySet)
By the way writing recursive functions like that is a very bad idea in general. You should use a single function and a stack of the arguments if possible.
P.S.: Your code was incomplete by the way but the idea is the same.

Related

Mlrose TSPOpt Genetic Algorithm own cost function

I want to program my own cost function for my own TSP problem. I do not want to use the mlrose one, because I want to optimize real coords with time.
First of all, I created a coords_List which looks like this: [(49.321,8.213),[50.321,9.124]...)
Then I created my own fitness function which accepts the guess array and returns a float.
fitnessF = mlrose.CustomFitness(coords_list)
Now I set up mlRose:
problem_fit = mlrose.TSPOpt(length = len(coords_list),fitness_fn =fitnessF, maximize=False)
best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state = 2)
This returns:
Exception: fitness_fn must have problem type 'tsp'.
Now I set up the code like this:
fitnessF = mlrose.TravellingSales(check_fitness)
Now it will return:
object of type 'function' has no len()
Thanks in advance
Ps: I would also be ready to share my notebook over Email
I could figure out where the problem was. It is right that I have to define my custom fitness function, but for TSP I have to add the problem type:
fitnessF = mlrose.CustomFitness(coords_list,"tsp")
Now it will work.

Ruby method for values from all associations

This method works, but I'm sure the performance could be greatly improved. Also, I'm realizing how fun and awesome it is to take smelly code like this, and rubify it. But I need a little more help to get my Ruby skills to the level to refactor something like this.
An objective can have "preassign" objectives. These are pre-requisites that must be completed before the a student can try the objective in question.
ObjectiveStudent is the join model between an objective and a student. It has a method called "points_all_time" that finds the student's best score on that objective.
The check_if_ready method is the one that I'm trying to refactor in this question. It also belong to the ObjectiveStudent model.
It needs to check whether the student has passed ALL of the preassigns for a given objective. If so, return true. Return false if the student has a less-than-passing score on any of the preassigns.
def check_if_ready
self.objective.preassigns.each do |preassign|
obj_stud = self.user.objective_students.find_by(objective_id: preassign.id)
return false if obj_stud.points_all_time < 7
end
return true
end
Right now I suspect this method is making too many calls to the database. What I'm really hoping to find is some way to look at the scores for the pre-reqs with a single db call.
Thank you in advance for any insight.
The following should work for you:
def is_ready?
user.objective_students
.where(objective_id: objective.preassigns.select(:id))
.none? { |obj_stud| obj_stud.points_all_time < 7 }
end
We collect all the objective_students for the user where the objective_id is in the list of objective.preassigns ids. This results in one 1 query being executed.
Then we use Enumerable#none? to make sure that none of the objective_students have points_all_time less than 7.
You could also use the inverse .all? { |obj_stud| obj_stud.points_all_time >= 7 } if you wanted
One way you could "rubify" this method is to rewrite the signature as:
def is_ready?
It is common practice to append ? to functions that return a boolean value in Ruby. (Note: I also don't really see a reason to have the word 'check' in the declaration, but that's just an opinion).
Furthermore, if objective_id is the primary key for the objective_students model, you can simply write objective_students.find(preassign.id) instead of the find_by method.
I would also suggest having a separate method for returning a student's points (especially since I suspect you will need to get a student's points more than just once) :
def getPoints(preAssignId)
return self.user.objective_students.find_by(objective_id: preAssignId).points_all_time
end
Then your main method can be written in a more clear, self-describing manner as:
def is_ready?
self.objective.preassigns.each {|preassign| return false if getPoints(preassign) < 7 }
return true
end

Is there a shorthand for Ruby Blocks?

I find myself annoyed with the following verbose writing in Ruby:
polys.each { |poly| poly.edges.each {|edge| draw edge.start, edge.end } }
(polys is an Array of Polygons, edges is a method of Polygon returning an Array of Edges)
Ideally I would like to shorten this to something like this:
polys.each.edges.each { draw _.start, _.end }
More specifically I would like to know:
How could we write a method_missing hack as with the first each? (Upon being called with a missing method, the enumerator could call this method on each item returned from the enumeration)
Is there a way to get rid of the |x| using any symbol or default name?
No. Closest you can do would be:
polys.flat_map(&:edges).each { |_| draw _.start, _.end }
flat_map will convert an array in another array and flatten it to a single dimension array. If the inside of a block is calling a single method with no parameters, you can use the &:edges shortcut.
This being said, I would probably keep it closer to your initial proposal, as it's more readable:
polys.each do |poly|
poly.edges.each {|edge| draw edge.start, edge.end }
end
Remember, you write code once but it's read a lot, so readability trumps terseness.

Using Ruby to solve a quiz

So I found this quiz on a website that I was excited to solve with my newly acquired Ruby skills (CodeAcademy, not quite finished yet).
What I want to do is make an array with 100 entries, all set to "open". Then, I planned to create a method containing a for loop that iterates through every nth entry of the array and changes it to either "open" or "closed", based on what it was before. In the for loop, n should be increased from 1 to 100.
What I have so far is this:
change_state = Proc.new { |element| element == "open" ? element = "closed" : element = "open" }
def janitor(array,n)
for i in 1..n
array.each { |element| if array.index(element) % i == 0 then element.change_state end }
end
end
lockers = [*1..100]
lockers = lockers.map{ |element| element = "closed" }
result = janitor(lockers,100)
When trying to execute I receive an error saying:
undefined method `change_state' for "closed":String (NoMethodError)
Anybody an idea what is wrong here? I kinda think I'm calling the "change_state" proc incorrectly on the current array element.
If you know the quiz, no spoilers please!
As you have implemented change_state, it is not a method of any class, and definitely not one attached to any of the individual elements of the array, despite you using the same variable name element. So you cannot call it as element.change_state.
Instead, it is a variable pointing to a Proc object.
To call the code in a Proc object, you would use the call method, and syntax like proc_obj.call( params ) - in your case change_state.call( element )
If you just drop in that change, your error message will change to:
NameError: undefined local variable or method `change_state' for main:Object
That's because the change_state variable is not in scope inside the method, in order to be called. There are lots of ways to make it available. One option would be to pass it in as a parameter, so your definition for janitor becomes
def janitor(array,n,state_proc)
(use the variable name state_proc inside your routine instead of change_state - I am suggesting you change the name to avoid confusing yourself)
You could then call it like this:
result = janitor(lockers,100,change_state)
Although your example does not really need this structure, this is one way in which Ruby code can provide a generic "outer" function - working through the elements of an array, say - and have the user of that code provide a small internal custom part of it. A more common way to achieve the same result as your example is to use a Ruby block and the yield method, but Procs also have their uses, because you can treat them like data as well as code - so you can pass them around, put them into hashes or arrays to decide which one to call etc.
There may be other issues to address in your code, but this is the cause of the error message in the question.

Which closure implementation is faster between two examples

I'm writing some training material for the Groovy language and I'm preparing an example which would explain Closures.
The example is a simple caching closure for "expensive" methods, withCache
def expensiveMethod( Long a ) {
withCache (a) {
sleep(rnd())
a*5
}
}
So, now my question is: which of the two following implementations would be the fastest and more idiomatic in Groovy?
def withCache = {key, Closure operation ->
if (!cacheMap.containsKey(key)) {
cacheMap.put(key, operation())
}
cacheMap.get(key)
}
or
def withCache = {key, Closure operation ->
def cached = cacheMap.get(key)
if (cached) return cached
def res = operation()
cacheMap.put(key, res)
res
}
I prefer the first example, as it doesn't use any variable but I wonder if accessing the get method of the Map is slower than returning the variable containing the computed result.
Obviously the answer is "it depends on the size of the Map" but, out of curiosity, I would like to have the opinion of the community.
Thanks!
Firstly I agree with OverZealous, that worrying about two get operations is a premature optimization. The second exmaple is also not equal to the first. The first allows null for example, while the second on uses Groovy-Truth in the if, which means that null evals to false, as does for example an empty list/array/map. So if you want to show calling Closure I would go with the first one. If you want something more idiomatic I would do this instead for your case:
def expensiveMethod( Long a ) {
sleep(rnd())
a*5
}
def cache = [:].withDefault this.&expensiveMethod

Resources