this is a dynamic programming pseudocode for TSP (Travelling Salesman Problem). i understood its optimal substructure but i can't figure out what the code in red brackets do.
i am not asking anyone to write the actual code, i just need explanation on what is happening so i can write my own.... thanks:)
here is a link for the pseudocode, i couln't uploaded over here.
http://www.imagechicken.com/viewpic.php?p=1266328410025325200&x=jpg
Here is some less mathematical pseudo-code. I don't know if this will explain what's happening, but it may help you read it. This isn't a functional algorithm (lots of := all over), so I'm going to use Python pseudo-code.
# I have no idea where 'i' comes from. It's not defined anywhere
for k in range(2,n):
C[set(i,k), k] = d(1,k)
shortest_path = VERY_LARGE_NUMBER
# I have to assume that n is the number of nodes in the graph G
# other things that are not defined:
# d_i,j -- I will assume it's the distance from i to j in G
for subset_size in range(3,n):
for index_subset in subsets_of_size(subset_size, range(1,n)):
for k in index_subset:
C[S,k] = argmin(lambda m: C[S-k,m] + d(G,m,k), S - k)
shortest_path = argmin(lambda k: C[set(range(1,n)),k] + d(G,1,k), range(2,n))
return shortest_path
# also needed....
def d(G, i, j):
return G[i][j]
def subsets_of_size(n, s): # returns a list of sets
# complicated code goes here
pass
def argmin(f, l):
best = l[0]
bestVal = f(best)
for x in l[1:]:
newVal = f(x)
if newVal < bestVal:
best = x
bestVal = newVal
return best
Some notes:
The source algorithm is not complete. At least, its formatting is weird in the inner loop, and it rebinds k in the second argmin. So the whole thing is probably wrong; I've not tried to run this code.
arguments to range should probably all be increased by 1 since Python counts from 0, not 1. (and in general counting from 1 is a bad idea).
I assume that G is a dictionary of type { from : { to : length } }. In other words, an adjacency list representation.
I inferred that C is a dictionary of type { (set(int),int) : int }. I could be wrong.
I use a set as keys to C. In real Python, you must convert to a frozen_set first. The conversion is just busywork so I left it out.
I can't remember the set operators in Python. I seem to remember it uses | and & instead of + and -.
I didn't write subsets_of_size. It's fairly complicated.
Related
I hate that ranges include the end. Here is an example where I've deliberately removed the end of the range.
N = 100
for x in 0.0 : 2*pi/N : 2*pi*(N-1)/N
println(x)
end
Is there any way to avoid the ugliness of this for loop?
Yes, there is
N = 100
for x in range(0; step=2π/N, length=N)
println(x)
end
Maybe not the most elegant way... take the first n-1 elements
r = 0.0 : 2*pi/N : 2*pi
r = Iterators.take(r,length(r)-1)
Unfortunately, inclusive ranges (and 1-based indexing) is baked into the idioms of Julia at a fundamental level.
However, for this specific case, do note that stepping with floating point values can be problematic, as adding N values might be less than, equal to, or greater than the final value, giving different results for the for loop. Although julia tries really hard, there's no way to quite do the right thing in all circumstances. As a bonus, working in integer values only for the ranges simplifies things. You might want to consider:
for ix in 0:N-1
x = ix * 2 * pi / N
println(x)
end
Alternatively, the range() function has a form with a len parameter:
for x in range(0, 2*pi*(N-1)/N, length=n)
println(x)
end
Or indeed, combining this with the other answer of only taking (N-1) could work.
You could actually define your own operator such as:
▷(a,b) = a:b-1
Now you can write:
julia> 3▷6
3:5
Julia also natively supports custom indices for arrays. There is a package CustomUnitRanges that is maybe an overkill here.
I'm trying to make a recursive function with Ocaml, but I keep getting the same error code.
let rec get x =
if x > 7 then
get x-7;;
And I get the very useful error message of:
Error: This expression has type int but an expression was expected of
type unit
I'm a complete beginner at OCaml, and studying it for a module at university.
And this is one of my assignments, and I'm a bit stuck!
I originally wanted to do it by a while loop, (as I'm a predominantly imperative programmer), but I couldn't get that to work, so I thought I'd try recursive!
Thanks
There's two problems with this code. First, the spacing of x-7 indicates that you would like to pass x - 7 to get, but it will actually be parsed as (get x) - 7. That's easily fixed with parentheses:
let rec get x =
if x > 7 then get (x - 7)
The second problem is that you don't have a second arm for the if, so the function doesn't have much of a chance of returning anything. (One arm if is taken to be of type unit, only useful for effects.)
You probably want to return something if x is less than 7, maybe:
let rec get x =
if x > 7 then get (x - 7) else x
Writing this with a while loop is possible, but you should understand that variables in OCaml are not mutable locations, only names. You'll have to introduce and manipulate mutable places explicitly:
let get x =
let y = ref x in
while !y > 7 do
y := !y - 7;
done;
!y
Hope that helps.
so I have a few questions on recursions. I am in a class and I am reviewing my notes and text and getting a little confused:
1) Am I getting this correct? Iterators and recursion seem so similar.
Recursion = a function that refers to itself and has a base case to get to the end of the problem.
Iterator: Using ++ or -- to go through all the data to get a piece of information.
2) What is recursive descent ? Is it getting closer to the base case? Then what is recursive ascent?
3) We are given this sample of recursion and it is confusing me:
Product of Positive Integer from 1 to n
Denoted by n! => n! = 1.2.3....(n-2).(n-1).n
0! = 1 , 5! = 1.2.3.4.5 = 120, 6! = 5! . 6 = 720
n! = n . ( n – 1 )!
Definition
– If n = 0 then n! = 1
– If n > 0, then n! = n. (n-1) !
Why is there an exclamation point after (n-1)? What are these dots, like n.(n-1)?
Recursion and iteration are not the same. You can iterate without recursion, and recursion means no iteration.
Let's leave recursive descent for now. That has to do with parsers.
The example is the mathematical operation of taking a factorial. The exclamation point means "factorial". The dot means multiplication.
Remember?
0! = 1
1! = 1
2! = 2*1
3! = 3*2*1 = 3*2!
4! = 4*3*2*1 = 4*3!
and so on.
This is a classic problem to illustrate recursion to undergrads seeing it for the first time:
function factorial_recursion(n) {
if (n <= 1) {
return 1;
} else {
return n*factorial(n-1);
}
}
You can write the same thing without recursion by iterating:
function factorial_iter(n) {
var value = 1;
if (n > 1) {
for (i = 1; i <= n; ++i) {
value *= i;
}
}
return value;
}
Well the dots are multiplication. It is confusing to use dots, but we know 5! = 1*2*3*4*5 so the dots must be multiplication. Also, the ! is the symbol to denote factorial. 5! = 5 * 4!
Yes, iteration and recursion are somehow similar, and it is known that any recursive solution has an equivalent iterative solution and vice versa. However, many problems are much simpler to solve in one of these approaches rather than in the other. The factorial example is easily solvable in both approaches.
Whenever you see how a problem can be reduced to one or more occurrences of the same problem on smaller magnitudes, you can easily proceed with a recursive solution.
I suppose that recursive descent is diving into deeper levels of the recursion, while ascent is the opposite: returning from a call and getting closer to the top level call.
The dots stand for multiplication.
We all know the program for this
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
But what is not clear to me is how the inner thing is happening?
How is it calculating 5*4*3*2*1 (if n is 5)
Please give a clear explanation on this.
Thanks.....
Mathematically, the recursive definition of factorial can be expressed recursively like so (from Wikipedia):
Consider how this works for n = 3, using == to mean equivalence:
3! == 2! * 3 == (1! * 2) * 3 == ((1) * 2) * 3
This can be derived purely symbolically by repeatedly applying the recursive rule.
What this definition does is first expand out a given factorial into an equivalent series of multiplications. It then performs the actual multiplications. The C code you have performs the exact same way.
What might help to understand it, is that when you are recursively calling the function, the new "cycle" will use N-1, not N.
This way, once you get to N==0, the last function you called will return a 1. At this point all the stack of functions are waiting for the return of the nested function. That is how now you exactly multiply the results of each of the functions on the stack.
In other words, you factorize the number given as input.
I have a five-dimensional rootfinding problem I'd like to solve from within a Sage notebook, but the functions I wish to solve depend on other parameters that shouldn't be varied during the rootfinding. Figuring out how to set up a call to, say, scipy.optimize.newton_krylov has got me stumped. So let's say I have (with a,b,c,d,e the parameters I want to vary, F1,F2,F3,F4,F5 the five expressions I which to solve to be equal to F1Val,F2Val,F3Val,F4Val,F5Val, values I already know, and posVal another known parameter)
def func(a, b, c, d, e, F1Val, F2Val, F3Val, F4Val, F5Val, posVal):
F1.subs(x1=a,x2=b,x3=c,x4=d,x5=e,position=posVal)
F2.subs(x1=a,x2=b,x3=c,x4=d,x5=e,position=posVal)
F3.subs(x1=a,x2=b,x3=c,x4=d,x5=e,position=posVal)
F4.subs(x1=a,x2=b,x3=c,x4=d,x5=e,position=posVal)
F5.subs(x1=a,x2=b,x3=c,x4=d,x5=e,position=posVal)
return (F1-F1Val, F2-F2Val, F3-F3Val, F4-F4Val, F5-F5Val)
and now I want to pass this to a rootfinding function to yield func = (0,0,0,0,0). I want to pass an initial guess (a0, b0, c0, d0, e0) vector and a set of arguments (F1Val, F2Val, F3Val, F4Val, F5Val, posVal) for the evaluation, but I can't figure out how to do this. Is there a standard technique for this sort of thing? The multidimensional rootfinders in scipy seem to be lacking the args=() variable that the 1D rootfinders offer.
Best,
-user2275987
Well, I'm still not sure how to actually employ the Newton-Raphson method here, but using fsolve works, for functions that accept a vector of variables and a vector of constant arguments. I'm reproducing my proof of concept here
def tstfunc(xIn, constIn):
x = xIn[0]
y = xIn[1]
a = constIn[0]
b = constIn[1]
out = [x+2*y+a]
out.append(a*x*y+b)
return out
from scipy.optimize import fsolve
ans = fsolve(tstfunc, x0=[1,1], args=[0.3, 2.1])
print ans