Recursive dynamic programming approach for the travelling salesman [closed] - c++

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I was hoping someone could explain how the code on this page works: TSP-Recursive
The pseudocode is hard to interpret, and the dynamic programming approach makes it particularly difficult to understand. Why is the bit shift needed? How can this approach be generalized (for example, given coordinates for locations, can we adapt this approach to solve that problem)?

The bit shifting is because the code is using an int to represent a set, specially the set of visited cities. If you have 32-bit integers then an int can represent a set of up to 32 items.
The basic operations are
// add n to set
set |= 1 << n;
// remove n from set
set &= ~(1 << n);
// test set for n
if ((set&(1 << n)) != 0)
...

The variable graph is a map (in the mathematical sense). Given two cities, A and B, graph[A][B] is the distance from A to B.
The variable dp is another map. Given a set of cities S, and a city A, dp[S][A] is the shortest journey visiting each city in S and ending at A.
Once graph has been filled in and the final city has been chosen, the function init fills in some of the distances in dp: for each city A, the shortest journey starting at A and visiting only B is obviously just graph[A][B].
The function TSP( S, X ) gives the length of the shortest journey visiting every city in S and ending at X. If that distance is already listed in dp, return that. Otherwise, for each city A in S, calculate the length of the shortest journey that visits every other city in S, then A, then X. The shortest of those is the answer, so the function records it in dp and also returns it.

Related

Reason for using bit manipulation in array size [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have recently got a basic idea of bit manipulation, and I was going through a problem where I found this C++ statement:
int popcount[1<<16];
I do have a basic idea of left/right Bit shift, but I would like to know why it is used in array size place.
Unless you find a comment in the code and unless you find out what the intent of popcount is, one can just guess why one writes 1 << 16 instead of, for example, 65536.
A common case could be that you want to count the number of occurrences of a particular id in, for example, a file. If the range of such an id where 16 bits, then such code could look as follows. The [1<<16] then expresses that you expect a range of not more than 16 bits:
int popcounts[1<<16] = { 0 };
int main() {
uint16_t id;
while (myfile >> id) {
popcounts[id]++;
}
}
Note that this is more accurate than writing int popcounts[UINT_MAX], because UINT_MAX is guaranteed to be equal or greater than 65536, and it is not guaranteed to be exactly 65536.
1<<16 is a common way to write 2 ** 16, which is easier to verify and modify than the "magic number" 65536. You may also encounter things like 1000 * 1000 instead of 1000000 for the same reason (although C++14 allows for 1000'000).

Generating normal distribution weighing constants in a range [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have some results whose relevance decreases with distance. I want to weight the result array elements with constants whose distribution is close to normal or folded normal. At start I want to generate an array with N constants starting from 1 to 0.01 by a function.
The result should be something like the following, ending with a number close to 0.01.
const double normalDistWeight[] = {
1.000, 0.997, 0.994, 0.989, 0.984, 0.977, 0.970, 0.961, 0.951, 0.939,
0.926, 0.910, 0.893, 0.874, 0.853, 0.830, 0.805, 0.778, 0.750, 0.719,
0.687, 0.654, 0.619, 0.584, 0.548, 0.512, 0.476, 0.440, 0.405, 0.370,
0.337, 0.305, 0.274, 0.246, 0.219, 0.194, 0.171, 0.150, 0.131, 0.114,
0.098, 0.085, 0.073, 0.063, 0.054, 0.047, 0.040, 0.035, 0.030, 0.027
};
Unfortunately I can't use any third party libraries or C++11 features, only plain C++.
Edit: Oh, I was over-thinking it... It's just a simple Gaussian error, so exp(-x^2) should work.
It appears to me that all you want is an array of values of the Gaussian function corresponding to uniformly spaced points on the positive half-axis, up to a point where the value is about 0.01.
This is straight-forward. The Gaussian function is f(x) = exp(−x2), like this:
In the chosen expression, we already have f(0) = 1, so all that remains is to find the final point x where we have f(x) = 0.01. Invert: x = √−log(0.01) &approx; 2.15.
So all you need to do is evaluate f on uniformly spaced points on the interval [0, 2.15].

C++ program for power but without using pow function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm a newbee in C++ and I'm writing a C++ program that asks the user to input two integers and then it raises the first integer to the power specified by the second integer. For example, if the user enters 5 and 8, the result will be 5 subscript 8, i.e., number five will be raised to the eighth power. The program must not use any pre-defined C++ functions (like pow function) for this task. The program should allow the user to perform another calculation if they so desire. Can anyone help
I'm not going to give you any code, because that won't allow you to truly explore this concept. Rather, you should use this pseudo code to implement something on your own.
Create a function which accepts two inputs, the base and the exponent.
Now there are several ways to go about doing this. You can use efficient bit shifting, but let's start simple, shall we?
answer = base
i = 1
while i is less than or equal to exponent
answer = answer * base
return answer
Simply loop through multiplying the base by itself.
There are other ways that focus on efficiency. Look here to see something that you may want to attempt: are 2^n exponent calculations really less efficient than bit-shifts?
The program must not use any pre-defined C++ functions (like pow function) for this task
You can use some piece of c++ code like follows, to compute xy, without using any predefined function:
int x = 5;
int y = 3;
int result = 1;
for(int i = 0; i < y; ++i)
{
result *= x;
}
cout << result << endl;
Output:
125
See a working sample here.

OpenGL: Draw line with point and directon vector [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I had seen OpenGL statement to draw a line using two points. However, my requirement is to draw a line using the following detail
a point on a line
Direction Vector
Im developing function in c++ using openGL library.
Any help is most appreciated.
The answer depends on the semantics of what you've termed a direction vector.
In the computer graphics context I would normally take that term to mean a unit vector facing in the specified direction. Whereas in a mathematics context you might simply mean the relative vector that results from subtracting the two points' coordinates.
[Using P1 and P2 to represent the required two points, and V for the vector].
In the former case, you also need a specify a length for the vector, so you'll need:
P2 = P1 + n * V
whereas in the latter case, it's just trivially
P2 = P1 + V
Just make that two-point line a very long one, say 10000 to each direction from your point-on-a-line:
void drawLinePointDirection(Point P, Vector D) {
Point A = P + 10000*D;
Point B = P - 10000*D
drawLineTwoPoints(A, B);
}
assuming D is unit length.

Branch Prediction - Global Share Implementation Explanation [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm working on an assignment in my Computer Architecture class where we have to implement a branch prediction algorithm in C++ (for the Alpha 21264 microprocessor architecture).
There is a solution provided as an example. This solution is an implementation of a Global Share Predictor.
I am simply trying to understand the given solution, specifically what is going on in:
*predict (branch_info &b) {...}
specifically,
if (b.br_flags & BR_CONDITIONAL) {...}
Can anyone provide me with an explanation? Thank you.
I think the following paper by Scott McFarling provides the detailed answer:
http://www.hpl.hp.com/techreports/Compaq-DEC/WRL-TN-36.pdf
Let me use your code to explain.
unsigned char tab[1<<TABLE_BITS];
is the Pattern History Table. Each entry in the tab keeps a 2-bit saturating counter. The direction of the conditional branch is finally determined by the MSB of the counter:
u.direction_prediction (tab[u.index] >> 1);
The reason why we use a counter of two or more bits instead of just one bit is to make the pattern less sensitive to reduce misprediction. For example,
for( int i = 0; i < m; i++ )
{
for( int j = 0; j < n; j++ )
{
...
}
}
when the inner loop is executed for the next time, one bit counter will mispredict the branch while 2-bit counter can prevent it.
The next is how to find the correct pattern in the Pattern History Table.
The naive way is to use branch address as index. But it ignores the correlation between different branches. That is why Global Branch History is introduced (For more details, please refer to http://www.eecg.utoronto.ca/~moshovos/ACA06/readings/two-level-bpred.pdf).
In your code,
unsigned int history;
is the Branch History Register which stores the Global Branch History.
Then some guys have found that combining Global Branch History and Branch Address as index can lead to more accurate prediction than just using one of them. The reason is that both Global Branch History and Branch Address affect the branch pattern.
If ignoring one of them, different branch pattern may be hashed to the same position of the Pattern History Table, thus causing collision problem.
Before Gshare is proposed, there is a solution called Gselect, which uses concatenation of Global Branch History and Branch Address as index of Pattern History Table.
The solution provided by Gshare is the hash function of
index = branch_addr XOR branch_history
This is what exactly what the following code means:
u.index = (history << (TABLE_BITS - HISTORY_LENGTH)) ^ (b.address & ((1<<TABLE_BITS)-1));
Scott McFarling's paper provides a good example to show how Gshare works better than Gselect:
Branch Address=1111_1111 Global Branch History=0000_0000
Branch Address=1111_1111 Global Branch History=1000_0000
Assume that we use the following Gselect strategy to prevent bias:
index = { {branch_addr[7:4]}, {branch_history[3:0]} }
Then Gselect will produce 1111_0000 for both cases while Gshare can distinguish the different patterns.
As far as I know, Gshare turns out to be the best solution by far to remove the collision.