Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I'm currently using Bellman Ford algorithm to find the shortest paths with negative value. Is there any faster algorithm that would outperform Bellman Ford for finding shortest paths with negative values?
A simple improvement is to only check for "active" nodes instead of iterating on all of them as the naive implementation does.
The reason is that if a node didn't lead to improvements on any of its neighbors and didn't change value in last iteration there is no need to redo the computation again (it will still produce no improvements).
Pseudocode (Python, actually):
A = set([seed])
steps = 0
while len(A) > 0 and steps < number_of_nodes:
steps += 1
NA = set()
for node in A:
for nh in neighbours(node):
x = solution[node] + weight(node, nh)
if x < solution[nh]:
# We found an improvement...
solution[nh] = x
pred[nh] = node
NA.add(nh)
A = NA
A is the "active" node set, where an improvement was found on last step and NA is the "next-active" node set that will need to be checked for improvements on next iteration.
Initially the solution is set to +Infinity for all nodes except the seed where the solution is 0. Initially only the seed is in the "active" set.
Note that in case of negative-sum loops reachable from the seed the problem has no "minimum path" because you can get the total as low as you want by simply looping; this is the reason for the limit on the "steps" value.
If when coming out of the loop A is not empty then there is no solution to the minimum cost problem (there is a negative-sum loop and you can lower the cost by simply looping).
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm trying to figure out a good way to write a little "algorithm", which would be able to find a mathematical a range between these two numbers:
Let's suppose maximum number is 1500 and minimum number would be 1;
By performing some sort of mathematical formula, method would be able to determine that best range between these two numbers is lets say 100;
So range would be:
100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500
Other example:
Maximum is 10, minimum 1;
Best range would be (let's say):
2,4,6,8,10
Are there any libraries in c# which offer this kind of solution or is there some neat mathematical formula used to determine this?
P.S. Guys there can be a remainder in the number as well...
I'm guessing I can divide the maximum number into let's say 7 fixed groups, and then just add up the divided number until I get the max value , no ?
Okay guys I've figured out an idea, lets suppose maximum number is a floating point number and is: 1326.44..., while the minimum is 132.5
I'm going to say that maximum range can be 7... So what I can do is divide 1326.44 with 7 and I'll get 189.49
So the first amount in range is:
var ranges = new[] { 132.5, 189.5 ... /*Now I just need to dynamically somehow add the rest of the range elements?*/ };
This is actually super easy. You have a min range value and a max range value, and you want a particular number of items in your range. Therefore, you simply need to calculate a step value, and then add that recursively to the minimum value until you're at the maximum value. For example:
var min = 132.5;
var max = 1326.44;
var count = 7;
var step = (max - min) / count;
var items = new List<double>();
for (var i = min; i <= max; i += step)
{
items.Add(i);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Currently very new to C# and coding , so i will be more than happy if someone will explain me how to display how many digits the number has. For example the number 12345 has 5 digits.the main theme in the class is while loops so the answer probably need to contain while loop.TY
You can either use this
Math.Abs(myint).ToString().Length
and if you absolutely must use a while loop then
number = Math.Abs(number);
int length = 1;
while ((number /= 10) >= 1)
length++;
To test code
string.Trim().Replace("-","").Length
so if you have a number you should make it a string first using ToString()
The Length returns the number of characters that you hold within your string minus your white spaces (Because of the Trim()),i don't see why you would want to use the while loop in the first place.
Edit : if you have a minus number the .Replace() will take care of that.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms.
I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to recommend?
I don't know what "longest common [[chain? substring?]]" has to do with "percent difference", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length).
Ignoring the "longest common" strangeness, and defining "percent difference" as the edit distance between the strings divided by the max length (times 100 of course;-), what about:
def levenshtein_distance(first, second):
"""Find the Levenshtein distance between two strings."""
if len(first) > len(second):
first, second = second, first
if len(second) == 0:
return len(first)
first_length = len(first) + 1
second_length = len(second) + 1
distance_matrix = [[0] * second_length for x in range(first_length)]
for i in range(first_length):
distance_matrix[i][0] = i
for j in range(second_length):
distance_matrix[0][j]=j
for i in xrange(1, first_length):
for j in range(1, second_length):
deletion = distance_matrix[i-1][j] + 1
insertion = distance_matrix[i][j-1] + 1
substitution = distance_matrix[i-1][j-1]
if first[i-1] != second[j-1]:
substitution += 1
distance_matrix[i][j] = min(insertion, deletion, substitution)
return distance_matrix[first_length-1][second_length-1]
def percent_diff(first, second):
return 100*levenshtein_distance(a, b) / float(max(len(a), len(b)))
a = "the quick brown fox"
b = "the quick vrown fox"
print '%.2f' % percent_diff(a, b)
The Levenshtein function is from Stavros' blog. The result in this case would be 5.26 (percent difference).
In addition to difflib and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( http://www.nltk.org/ ) library. You can also compare blobs of natural language text more semantically by using N-Grams ( http://en.wikipedia.org/wiki/N-gram ).
Longest common chain? Perhaps this will help then: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Another area of interest might be the Levenshtein distance described here.
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 9 years ago.
Improve this question
I have a Task to do C#. I need to add two numbers.
The first number contains around 100 digits like "12822429847264872649624264924626466826446692............"
and second number also with 100 digits or more or less
by using this numbers i need task like add/sub/multiply/div
I done this using BigInteger in C#
But do I need to do this using arrays or strings?
Since they are both 100 digits just start with the last digit and in a for loop just add each one, but if the value is > 10 then remember to add one to the next digit.
This is how children learn to add, you just need to follow the same steps, but the answer should be in an array of 101 characters.
UPDATE:
Since you have shown some code now, it helps.
First, don't duplicate the code based on if str1 or str2 is larger, but make a function with that logic and pass in the larger one as the first parameter.
Determine the largest size and make certain the smaller value is also the same size, to make math easier.
The smaller one should have leading zeroes (padding), again to help keep the code simple.
You can also start by looking at the source code for structures such as BigInteger. They would provide you more insight into aspects such as computational efficiency and storage, particularly about multiplication and division. You can take a look at here or here.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to write a c# program that does following:
Takes two parameters: a list of objects and a number
Iterates through the list and find the first set of objects that equals to the number.
Stop iteration if a set is found and the return the set.
So, I have a list of user defined object, say Person as an example. Say, Person object has two fields, Name and age. For example,
MyList
- Person1: John, 10
- Person2: Mary, 25
- Person3: Mike, 35
- Person4: Ann, 20
- Person5: Joe, 5
I want to find a set from the list that equals to the number that I am passing in. If I am passing in above list and 50, I want to return Person2, Person4, Person5 as a list.
This is subset sum problem.
Unfortunately, it is NP-Complete, so there is no known polynomial solution for it.
However, it does have a pseudo-polynomial solution, using Dyanamic Programming, that is using the next recursive function:
f(i,0) = true
f(0,k) = false (k != 0)
f(i,k) = f(i-1,k) or f(i-1,k-weight[i])
Running with f(n,W) yields true if such solution exists, and false otherwise.
The dynamic programming solution fills up a table, after the table is full, you need to "retrace" your steps from table[n][W] back in order to find which items should be included in the set.
More information on getting the actual elements from the table can be found in this thread