Java add and set functions - java

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).

Related

Java Vectors : Implementing Pop function using Vectors

What is difference between a.remove(a.size()-1) and a.remove(a.indexOf(a.lastElement())) of Vectors Class in Java? Do they remove the same element?
a.remove(a.indexOf(a.lastElement())) gave me wrong output whereas a.remove(a.size()-1) is giving correct output.
Note: a is a Java Vector declared as
Vector<Integer> a = new Vector<Integer>();
a.remove(a.indexOf(a.lastElement())) is a very roundabout way of achieving roughly the same thing.
It gets the lasts element in the vector, tries to find the index of any element that is equal to it and then removes that element.
That is only roughly the same as a.remove(a.size()-1), because if the vector contains a second object that is equal to the last one (i.e. last.equals(otherElement) returns true), then that item will be removed instead.
a.remove(a.size()-1) is definitely the more correct (and faster) way to remove the last element.

proper mathematics way to explain in a comment that there is no duplicate items in a set

i'm writing some code, and I want my code to be well documented.
there is a part in the code where I'm checking that when there is a try to insert new element E to a list L, the element E will be unique (so there is no other elements in L that equals to him).
I'm having difficult to write a user-friendly mathematics comment, something that will look like the example bellow
the function will change all elements (that in list L) fields E.color to "Black" only if color to black element.size > 10.
so in that case I will write the comment -
[ X.color="Black" | X in L, X.size > 10]
but for the scenario above I couldnt find any satisfied mathmatics comment.
A mathematical set by definition has no duplicates inside it, so perhaps using the a set rather than a list would solve your problem.
However if that's too hard to change now then you could write something like:
[ L.insert(E) | E not in L ]
where E is the element and L is the list.
an exhaustive answer to your question requires two observations:
Best coding practices require you to know collections very well and when to use them. So you want the right collection for the right Job. In this case as advised in other comments, you need to use a Set instead of a list. A Set uses a Map under the hood, having your elements as keys and values as DEFAULT. Every time that you add an element to your Set, the Hash value for it is calculated and compared using equals to the existing elements. So no dups are allowed.
I really appreciate the fact that you want to write good comments, however you don't need to for the following reasons:
List and Sets behaviour is largely documented already, so nobody expects you to comment them;
Books like Refactoring and Clean code, teach us that good code should never be commented as it should be self explaining. That means that your method/class/variable name should tell me what the method is doing.

Add a number to an ArrayList by sorting

Include a method addEventToTimeline that will be passed an Event. When an element is added to the ArrayList of events, it should be put in the correct place in the list. The elements in events should always be in chronological order.
Use similar logic and code to what we used yesterday to add an Event into the
correct place in the list. (Events are compared using compareTo.)
My code looks like this so far. I know it's wrong but I have no idea where to go from here.
public void addEventToTimeline(Event a){
for(int i = 0; i <events.size(); i++){
if(a.compareTo(events.get(i))<0);
events.add(i+1, events.get(i));
events.set(i, a);
}
}
}
Are you forced to use an ArrayList ? I would use a tree for this kind of problem. Here's what you should do with an ArrayList solution:
Find the correct place for the new Event (O(n) if the arrayList is unsorted, Log(n) if it is sorted - using Binary Search
Put the Event in its place, and move all the subsequent Events one position to the right ( O(n) )
I would use a more advanced data structure for this. For example if all you want is the min Event each time use a heap
If you need a global order, use a BST , or even better, a red black tree
This post on StackExchange can also be useful

route in graph with specific length from one point

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.

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.

Categories