route in graph with specific length from one point - java

I have a method "connection(int n)" which gives me all the cells number that have relation with cell number "n" now I want a method which gives me all the routes with a specific length "myLength" that start from cell number "start" and just in one direction (as it's usual) I mean we are not allowed to pass some cells more than one time
thanks in advance for your help
P.S. I can't use map tools, graph tools,... with basic tools please

You are looking for BFS.
Model your problem as a graph G = (V,E) such that V = {1,...,n} [all possible values] and E = { (u,v) | connection(u) returns v } [there is a connection between u and v using your connection() method]
In addition to the standard BFS, you will need to add another stop condition when you reached the limited length.
EDIT:
Note that this solution assumes you are looking for a path up-to length, and not exactly length.
BFS doesn't work here for the counter example of a clique if you want exactly of length.
To get all vertices that have a simple path of exactly length - You will probably need a DFS that avoids loops [can be done by maintaining a set that is modified each iteration], but can explore each vertex more then once.

Related

How to Implement Kirchoff Rules

1.What data structure to use for electric circuit representation
for Kirchoff Rules computation purposes
how to differentiate between different types of electric components
how to 'recognize' wire inter-connections between them
2.how to implement Kirchoff Rules
how to obtain current and voltage loops
how to store and evaluate Kirchoff equations
[original question text]
Specifically, how would the program recognize something is in series and parallel and how will it differentiate between a battery, resistor, capacitor, inductors, etc..
Java's an object-oriented language. Start thinking about how you'd model your system as objects.
You have a few object candidates already:
Battery
Resistor
Capacitor
Inductor
These would have input and output nodes. The output from one is the input to the next.
What about transistors? You'll have more than one input. What then? Those are non-linear. How do you model those?
You'll build in the proper behavior for each one and wire them together.
You'll have some kind of transient forcing function here. Input current or voltage waveforms. Output is current and voltage at each node versus time.
This is the electrical engineer's equivalent of finite element analysis.
These are really transient ODE, right? How do you plan to solve them? Numerical integration?
agree with duffymo's answer just some things to add (I am C++ friendly so I stick to it)
first some data to represent components
struct pin
{
char name[]; // name id for pin ("C","B","E"...
int part_ix,pin_ix; // connected to patrs[part_ix].pins[pin_ix]
double i,u; // actual: current,voltage
int direction; // in,out,bidirectional
};
struct part
{
char name[]; // name id for part ("resistor","diode",...
pin pins[n]; // n pins of the part (resistor has 2 , transistor has 3, ...)
// here add all values you need for simulation like:
double R,H21E,...
// or even better do a matrix for it so when you multiply it by input currents and voltages
// of every pin you get the correct currents and voltages
double m[n][n+n];
};
also you can add list of pins connections instead of part_ix,pin_ix to save some processing time.
circuit
part parts[];
simple dynamic list of components the interconnections are inside it
loops
you have to extract closed circuit loop from interconnections for current equations and get nodes that connect current loops for voltage equations. This would lead you to system of equations. Nodes have more that 2 connections and closed current loops are just sequence of connections leads back to itself. Look here:
https://stackoverflow.com/a/21884021/2521214
it is one of my answers where part of the code finds closed loops
evaluation
can use gauss elimination for that. Problematic are non linear components like diodes, transistors ... so may be you will need to add more matrices (approximate to polynomial with bigger degree) then you will need to multiply by all currents and voltages powered by (0,1,2,3,...). I think ^3 will be enough for most components and do not forget that some non linear component also need to remember their states (or last current,voltage,... ...).
Also sometimes is better to use symbolic expressions instead of matrix approach but for that you will need expression evaluation engine. I use this approach a lot for self resizing geometry in CAD/CAM meshes.

Solving a non linear system in java (using optim toolbox)

I have a system of nonlinear dynamics which I which to solve to optimality. I know how to do this in MATLAB, but I wish to implement this in JAVA. I'm for some reason lost in how to do it in Java.
What I have is following:
z(t) which returns states in a dynamic system.
z(t) = [state1(t),...,state10(t)]
The rate of change of this dynamic system is given by:
z'(t) = f(z(t),u(t),d(t)) = [dstate1(t)/dt,...,dstate10(t)/dt]
where u(t) and d(t) is some external variables that I know the value of.
In addition I have a function, lets denote that g(t) which is defined from a state variable:
g(t) = state4(t)/c1
where c1 is some constant.
Now I wish to solve the following unconstrained nonlinear system numerically:
g(t) - c2 = 0
f(z(t),u(t),0)= 0
where c2 is some constant. Above system can be seen as a simple f'(x) = 0 problem consisting of 11 equations and 1 unkowns and if I where supposed to solve this in MATLAB I would do following:
[output] = fsolve(#myDerivatives, someInitialGuess);
I am aware of the fact that JAVA doesn't come with any build-in solvers. So as I see it there are two options in solving the above mentioned problem:
Option 1: Do it my-self: I could use numerical methods as e.g. Gauss newton or similar to solve this system of nonlinear equations. However, I will start by using a java toolbox first, and then move to a numerical method afterwards.
Option 2: Solvers (e.g. commons optim) This solution is what I am would like to look into. I have been looking into this toolbox, however, I have failed to find an exact example of how to actually use the MultiVariateFunction evaluater and the numerical optimizer. Does any of you have any experience in doing so?
Please let me know if you have any ideas or suggestions for solving this problem.
Thanks!
Please compare what your original problem looks like:
A global optimization problem
minimize f(y)
is solved by looking for solutions of the derivatives system
0=grad f(y) or 0=df/dy (partial derivatives)
(the gradient is the column vector containing all partial derivatives), that is, you are computing the "flat" or horizontal points of f(y).
For optimization under constraints
minimize f(y,u) such that g(y,u)=0
one builds the Lagrangian functional
L(y,p,u) = f(y,u)+p*g(y,u) (scalar product)
and then compute the flat points of that system, that is
g(y,u)=0, dL/dy(y,p,u)=0, dL/du(y,p,u)=0
After that, as also in the global optimization case, you have to determine what the type of the flat point is, maximum, minimun or saddle point.
Optimal control problems have the structure (one of several equivalent variants)
minimize integral(0,T) f(t,y(t),u(t)) dt
such that y'(t)=g(t,y(t),u(t)), y(0)=y0 and h(T,y(T))=0
To solve it, one considers the Hamiltonian
H(t,y,p,u)=f(t,y,u)-p*g(t,y,u)
and obtained the transformed problem
y' = -dH/dp = g, (partial derivatives, gradient)
p' = dH/dy,
with boundary conditions
y(0)=y0, p(T)= something with dh/dy(T,y(T))
u(t) realizes the minimum in v -> H(t,y(t),p(t),v)

Java add and set functions

I'm a python programmer, but currently I'm reading through Java code to get some ideas. I have no programming experience at all with Java and I don't know how it's possible, but I couldn't get any information using Google about these functions.
if(pv.size() -2 < j)
pv.add(j+1, localpv.get(j));
else
pv.set(j+1, localpv.get(j));
This is the piece of code I need to decypher. pv and localpv are both vectors (I believe they are equivalent to lists in python?), and something is added to them. I can guess that one of them is adding them to a vector at a certain position (j+1), but then I have no idea what the other one does.
Can you please explain those two lines for me and maybe telling what are they equivalent to in python?
add inserts the specified element at the specified position
set replaces the element at the specified position
Checkout JavaDocs http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html
add inserts an object at a position moving all other objects one back. set overwrites current object at that location.
You can look up the definitions of all Java methods in the API reference.
Vector.add(int index, E element)
Inserts the specified element at the specified position in this Vector.
Vector.set(int index, E element)
Replaces the element at the specified position in this Vector with the specified element.
The equivalent Python code would be
if len(pv) - 2 < j:
pv.insert(j+1, localpv[j])
else:
pv[j+1] = localpv[j]
The first one adds a new element on j+1'st position, the other one sets the value of existing j+1'st position with a given value.
I guess the author wanted to make sure he doesn't try to set a value of a non existing element of the list (vector).

Java - Recover the original order of a list after its elements had been randomized

The Title is self explanatory. This was an interview question. In java, List is an interface. So it should be initialized by some collection.
I feel that this is a tricky question to confuse. Am I correct or not? How to answer this question?
Assuming you don't have a copy of the original List, and the randomizing algorithm is truly random, then no, you cannot restore the original List.
The explanation is far more important on this type of question than the answer. To be able to explain it fully, you need to describe it using the mathematical definitions of Function and Map (not the Java class definitions).
A Function is a Map of Elements in one Domain to another Domain. In our example, the first domain is the "order" in the first list, and the second domain is the "order" in the second list. Any way that can get from the first domain to the second domain, where each element in the first domain only goes to one of the elements in the second domain is a Function.
What they want is to know if there is an Inverse Function, or a corresponding function that can "back map" the elements from the second domain to the elements in the first domain. Some functions (squaring a number, or F(x) = x*x ) cannot be reversed because one element in the second domain might map back to multiple (or none) elements in the first domain. In the squaring a number example
F(x) = x * x
F(3) = 9 or ( 3 -> 9)
F(12) = 144 or ( 12 -> 144)
F(-11) = 121 or (-11 -> 121)
F(-3) = 9 or ( -3 -> 9)
attempting the inverse function, we need a function where
9 maps to 3
144 maps to 12
121 maps to -11
9 maps to -3
Since 9 must map to 3 and -3, and a Map must have only one destination for every origin, constructing an inverse function of x*x is not possible; that's why mathematicians fudge with the square root operator and say (plus or minus).
Going back to our randomized list. If you know that the map is truly random, then you know that the output value is truly independent of the input value. Thus if you attempted to create the inverse function, you would run into the delimma. Knowledge that the function is random tells you that the input cannot be calculated from the output, so even though you "know" the function, you cannot make any assumptions about the input even if you have the output.
Unless, it is pseudo-random (just appears to be random) and you can gather enough information to reverse the now-not-truly random function.
If you have not kept some external order information (this includes things like JVM trickery with ghost copies), and the items are not implicitly ordered, you cannot recover the original ordering.
When information is lost, it is lost. If the structure of the list is the only place recording the order you want, and you disturb that order, it's gone for good.
There's a user's view, and there's internals. There's the question as understood and the question as can be interpreted.
The user's view is that list items are blocks of memory, and that the pointer to the next item is a set of (4?8? they keep changing the numbers:) bytes inside this memory. So when the list is randomized and the pointer to the next item is changed, that area of memory is overriden and can't be recovered.
The question as understood is that you are given a list after it had been randomized.
Internals - I'm not a Java or an OS guy, but you should look into situations where the manner in which the process is executed differs from the naive view: Maybe Java randomizes lists by copying all the cells, so the old list is still kept in memory somewhere? Maybe it keeps backup values of pointers? Maybe the pointers are kept at an external table, separate from the list, and can be reconstructed? Maybe. Internals.
Understanding - Who says you haven't got an access to the list before it was randomized? You could have just printed it out! Or maybe you have a trace of the execution? Or who said you're using Java's built it list? Maybe you are using your own version controlled list? Or maybe you're using your own reversable-randomize method?
Edwin Buck's answer is great but it all depends what the interviewer was looking for.

Java Algorithm for finding the largest set of independent nodes in a binary tree

By independent nodes, I mean that the returned set can not contain nodes that are in immediate relations, parent and child cannot both be included. I tried to use Google, with no success. I don't think I have the right search words.
A link, any help would be very much appreciated. Just started on this now.
I need to return the actual set of independent nodes, not just the amount.
You can compute this recursive function with dynamic programming (memoization):
MaxSet(node) = 1 if "node" is a leaf
MaxSet(node) = Max(1 + Sum{ i=0..3: MaxSet(node.Grandchildren[i]) },
Sum{ i=0..1: MaxSet(node.Children[i]) })
The idea is, you can pick a node or choose not to pick it. If you pick it, you can't pick its direct children but you can pick the maximum set from its grandchildren. If you don't pick it, you can pick maximum set from the direct children.
If you need the set itself, you just have to store how you selected "Max" for each node. It's similar to the LCS algorithm.
This algorithm is O(n). It works on trees in general, not just binary trees.
I would take-and-remove all leaves first while marking their parents as not-to-take, then remove all leaves that are marked until no such leaves are left, then recurse until the tree is empty. I don't have a proof that this always produces the largest possible set, but I believe it should.
I've provided an answer to a question for the same problem, although the solution is in python, the explanation, algorithm, and test cases could be applicable.

Categories