Ojalgo: Defining whether a matrix is stable in Java - java

I'm trying to solve M (NxN) linear systems (Ax = B, B = [b1,b2,...bM]) using Ojalgo. Thanks to apete's counsel, I successfully managed to check if A (A, B are objects of type PrimitiveMatrix) is singular but it seems that sometimes it's also unstable..
It would be really useful for me to determine if this matrix is stable or not.
Any help would be most appreciated. Thank you!

You should find the condition number of your matrix. I believe getCondition() gives you the condition number of a matrix. Bigger the number is less stable the matrices are.

Related

Dynamic Programming (how to send a message in the most efficient way)

I'm having a hard time with dynamic programming, I'm new in this, so I hope you could help me with anything you can, the problem is this:
As the Communications Officer of the IKS B'Moth Klingon battle cruiser, your duty is to manage communications in the most efficient way. Assume you need to transmit a message S= s1...sm given as a string of m symbols. For this purpose, you have r different codes. Let b(ij) be the number of bits needed to enconde the i-th symbol of your message in the j-th code. Initially, the bridge transmitter is set to code #1, but you can freely change the code at any point within the message and as many times as you want. To do so, you need to send a control code which is composed of C(ij) bits if you want to switch from current code i to any other code j. Your goal is to determine how to send thee message in the most efficient way (using the least number of bits).
A) Prove the problem exhibits optimal substructure.
B) find a recurrence for the optimal number of bits required.
C) Build a bottom up dynamic programming algorithm to solve the problem and indicate its complexity.
You can make a 3 dimensional array, and use previousCode, newCode, and ithSymbol as indices. The array will store the least number of bits while scanned upto ithSymbol and when it switches code from previousCode to newCode.
The recursive formula will be:
dp(ithSymbol, previousCode, newCode)=min_(i=1 to r)(dp(ithSymbol-1,i,previousCode))+C(previousCode, newCode)+b(ithSymbol,newCode);
(Assumed, C(i,i)=0 for all i)
Now you can write the code for yourself.
N.B. This is a naive approach. You can further make it efficient by making the array 2-D as only ithSymbol-1 is used in any step.

Efficient Intersection and Union of Lists of Strings

I need to efficiently find the ratio of (intersection size / union size) for pairs of Lists of strings. The lists are small (mostly about 3 to 10 items), but I have a huge number of them (~300K) and have to do this on every pair, so I need this actual computation to be as efficient as possible. The strings themselves are short unicode strings -- averaging around 5-10 unicode characters.
The accepted answer here Efficiently compute Intersection of two Sets in Java? looked extremely helpful but (likely because my sets are small (?)) I haven't gotten much improvement by using the approach suggested in the accepted answer.
Here's what I have so far:
protected double uuEdgeWeight(UVertex u1, UVertex u2) {
Set<String> u1Tokens = new HashSet<String>(u1.getTokenlist());
List<String> u2Tokens = u2.getTokenlist();
int intersection = 0;
int union = u1Tokens.size();
for (String s:u2Tokens) {
if (u1Tokens.contains(s)) {
intersection++;
} else {
union++;
}
}
return ((double) intersection / union);
My question is, is there anything I can do to improve this, given that I'm working with Strings which may be more time consuming to check equality than other data types.
I think because I'm comparing multiple u2's against the same u1, I could get some improvement by doing the cloning of u2 into a HashSet outside of the loop (which isn't shown -- meaning I'd pass in the HashSet instead of the object from which I could pull the list and then clone into a set)
Anything else I can do to squeak out even a small improvement here?
Thanks in advance!
Update
I've updated the numeric specifics of my problem above. Also, due to the nature of the data, most (90%?) of the intersections are going to be empty. My initial attempt at this used the clone the set and then retainAll the items in the other set approach to find the intersection, and then shortcuts out before doing the clone and addAll to find the union. That was about as efficient as the code posted above, presumably because of the trade of between it being a slower algorithm overall versus being able to shortcut out a lot of the time. So, I'm thinking about ways to take advantage of the infrequency of overlapping sets, and would appreciate any suggestions in that regard.
Thanks in advance!
You would get a large improvement by moving the HashSet outside of the loop.
If the HashSet really has only got a few entries in it then you are probably actually just as fast to use an Array - since traversing an array is much simpler/faster. I'm not sure where the threshold would lie but I'd measure both - and be sure that you do the measurements correctly. (i.e. warm up loops before timed loops, etc).
One thing to try might be using a sorted array for the things to compare against. Scan until you go past current and you can immediately abort the search. That will improve processor branch prediction and reduce the number of comparisons a bit.
If you want to optimize for this function (not sure if it actually works in your context) you could assign each unique String an Int value, when the String is added to the UVertex set that Int as a bit in a BitSet.
This function should then become a set.or(otherset) and a set.and(otherset). Depending on the number of unique Strings that could be efficient.

A* search Java - TSP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Implementation of A Star (A*) Algorithm in Java
For an assignment I have to implement some search algorithms in order to solve the travelling salesman problem, I understand the problem and I understand how the algorithm works, I simply don't know how to implement it (my Java isn't great) but this should really be the easy part but unfortunately my knowledge of Java isn't good enough to apply what I know about the algorithm.
I was therefore wondering if anyone could provide some hints or tips on how to get started with this or maybe even some good links to read up on, I also have to implement some other algorithms too if there's an easier one to start with id be happy to go with that one! I've had a look on here already but can't seem to find anything which is relevant :/
Any help is much appreciated! Thank you
I'm not an expert, but I don't think the A* can be used to solve the Traveling Salesman Problem. I'm sure you know the TSP is NP-hard, so exact solutions are quite complex and don't exist for every case. The easiest way I know of (and have used) to approximate a solution is whats called 'Simulated Annealing', which is a stochastic method (i.e. random!).
The idea is very simple. You organise the points into a list, which represents a path between all the nodes (this is called a 'tour'). Calculate how long the tour is and save the length. You then pick a random sub-list and simply reverse it. Calculate the new length. If the new list is shorter then keep it, otherwise discard it. Simply repeat these steps 100/1,000/10,000,000 times (depending on the number of points) and you'll have a reasonable approximation.
Example, imagine there are 5 points (pseudocode)...
List tour = [e, b, a, d, c]
int len = tourLength(tour)
List newTour = [e, b] + [d, a] + [c] // a and d have been reversed
int newLen = tourLength(newTour)
if(newLen < len) {
tour = newTour
}
For 10 points, 100 iterations should yield a good result.

find the longest intersection of two integer arrays

I have this problem but don't know what's best way to solve it in term of time complexity and space complexity.
Suppose I have two integer arrays
a={1,2,3,4,5}
b={2,3,4,5,6}
and of course they not necessarily to be sorted.
So the question is how to find 2,3,4,5? It better to have some code. Thanks in advance
why do we need DP here? question says find the longest intersection, not any intersection. am i missing a point?
There are lot of solutions to this.
int [] a = {...}; // n elements
int [] b = {...}; // m elements
You can store one array in a dictionary and for each element in the other array check the dictionary. That O(n). THis will cost you more space due to dictionary. and it s not in-place
Another solution would be for each element in a, you can do a linear search on b. which is O(n.m)
Another would be ;if you sort both of the arrays. Then for each element in one array do a binary search in another array. You will find the intersection of two. and this will be mlogn + nlogn or nlogm + mlogm
do we really need DP here?
This is actually a pretty popular programming problem. There is a dynamic programming approach to solving it. You can check out more about it at http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
I hope this link will solve your problem.
You have to write a common function which will display common numbers in two arrays.
And it use only one for loop .Thats why its complexity will be just O(N).
Find common numbers.
Code is in C . But i hope you can understand the logic.
At first we should sort our arrays, at second we should use binary search to finde a intersection of thise arrays.
Why? Because if we semple will searching intersection, without sort, our algorithm laboriousness will be N^2, but if we sort array before searching, totaly we will have [log_2(N)N + ( N(log_2(N)) up to N^2 )].
My method is useful for majority of samples

Need algorithm for Sequence calculation

I am trying to find the solution for a problem where i have something like
A > B
B > C
B > D
C > D
And I should get the answer as A > B > C > D.
Conditions for this problem
The output will involve all the elements.
The problem will not have any bogus inputs.
for example, (A>B) (C>D) is a bogus input, since we cannot determine the output.
The inputs can be of any size but never bogus and there will always be a solution to the problem.
I need to find a solution for this optimally using Java Collections. Any tips/hints are welcome.
Thanks in advance!
It's called a Topological Sort. http://en.wikipedia.org/wiki/Topological_sorting
Given that, you should be able to complete your homework on your own.
I'm betting you recently covered graphs in this class...
How do you think a graph could be applied here ?
Can you think of a structure which one would build on the basis of the problem inputs (A>B>, A>D, C>A etc.)? Maybe some kind of directed graph...
Once the problem is expressed in such a graph, the solution would involve navigating this graph...
You start putting them in a List. The list will be sorted, so for the nth pair (a, b), you look up a, using a binary search. If it exists already skip, if not you insert in at proper point. Since a > b, you do that again with b in the remaining part of the List. Hope this help.
You can do this with a Map of the inputs and a recursive method that adds it's answer to a returned List (or just prints each node as it descends the tree.) If you are returning the answer then pre-pending to the returned list will prevent the answer from being reversed D->C->B->A when complete (or you can just .reverse() the list at the end.) Don't forget to test for a break condition when recursing. (hint: key not found)

Categories

Resources