Fibonacci Heap for Dijkstra via Java - java

I want to implement Fibonacci Heap on Dijkstra Algorithm. I use this code for Fibonacci heap.
http://keithschwarz.com/interesting/code/?dir=fibonacci-heap
The problem is how to call the method: decreaseKey? It always give me the hint that (entry,double). But how to write an entry? The following is a simple example, how to fill the question mark?
FibonacciHeap<Integer> aa = new FibonacciHeap<>();
aa.enqueue(10, 1.01);
aa.enqueue(10, .2);
aa.enqueue(12, 3.2);
aa.enqueue(13, 3.4);
aa.decreaseKey(??????, newPriority);

decreaseKey() expects the first argument to be of type FibonacciHeap.Entry. 3 methods in the class return the Entrys of the heap:
public Entry<T> enqueue(T value, double priority);
public Entry<T> min();
public Entry<T> dequeueMin();
Each of the 3 methods return a different element, and modify the heap in their own way. Depending on your use case, you can store these Entrys in a variable and pass it to decreaseKey().
One such case would be storing the Entry while enqueuing it. Whenever you enqueue() something to the heap, it returns its corresponding Entry. From its documentation:
/**
* Inserts the specified element into the Fibonacci heap with the specified
* priority.
* ...
* #return An Entry representing that element in the tree.
*/
public Entry<T> enqueue(T value, double priority);
You can store it, and pass it to decreaseKey().
FibonacciHeap<Integer> aa = new FibonacciHeap<>();
FibonacciHeap.Entry entry = aa.enqueue(10, 1.01);
// ...
aa.decreaseKey(entry, newPriority);

Related

how to set one value for all elements of data structure in one action(simultaneously)

I got one interview question.
Write class UnlimitedArrayInt containing the following methods. Each method should be of O[1] complexity:
* void setAll(int number) – all integer numbers are set to the given number;
* int get(int index) – returns number at the given index. An index may be any positive integer value;
* void set(int index, int number) - sets number at the given index. Array isn’t limited so it may be any positive integer value; number may be any integer value.
As they told me solution not based on regular array.
So could anyone explain me what data structure better for use, and how to implement the method setAll with complexity O(1), because for my opinion it's always complexity O(n) cause we need to iterate over all indices for setting new value of all elements of any data structure.
You need to use Map and one common value that you would use in set. Map would act as an override in case if user sets the value.
Something around below:
public class UnlimitedArrayInt {
Map<Integer, Integer> values;
int commonValue;//default value to return if not found
public UnlimitedArrayInt() {
values = new HashMap<>();
commonValue = -1;
}
/**
use common value that you are going to use and at the same time reset all the instance of map (GC would clear all the reference at the back and this is a trade off of clear vs new instance that am making). Runs in O(1) time.
*/
public void setAll(int number) {
commonValue = number;
values = new HashMap<>();
}
/**
return if value was set else return the common value across your data structure if any was used. Else return -1. Runs in O(1) time.
*/
public int get(int index) {
return values.getOrDefault(index, commonValue);
}
/**
Override the existing common value which would take the priority over common value. Runs in O(1) time.
*/
public set(int index, int number) {
return values.put(index, number);
}
}

java.util.Random and recursion in Java

I'd like to start off by saying this is a little more of a general question; not one pertaining to the specific examples that I have given, but simply a conceptual topic.
Example #1:
I'm creating a truly random string with UUID.java. Let's say I never want to have the same UUID generated, ever. Here's an idea of the circumstance:
(Let's assume that I'm saving/loading the List at the top- that's not the point)
Gist URL (I'm new to StackExchange- sorry!)
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Example {
/**
* A final List<String> of all previous UUIDs generated with
* generateUniqueID(), turned into a string with uuid.toString();
*/
private static final List<String> PREVIOUS = new ArrayList<String>();
/**
* Generates a truly unique UUID.
*
* #param previous
* A List<String> of previous UUIDs, converted into a string with
* uuid.toString();
* #return a UUID generated with UUID.randomUUID(); that is not included in
* the given List<String>.
*/
public static UUID generateUniqueID(List<String> previous) {
UUID u = UUID.randomUUID();
if (previous.contains(u.toString())) {
return generateUniqueID(previous);
}
return u;
}
/**
* Generates a truly unique UUID using the final List<String> PREVIOUS
* variable defined at the top of the class.
*
* #return A truly random UUID created with generateUniqueID(List<String>
* previous);
*/
public static UUID generateUniqueID() {
UUID u = generateUniqueID(PREVIOUS);
PREVIOUS.add(u.toString());
return u;
}
}
Example #2: Okay, maybe UUID was a bad example, so let's use Random and a double. Here's another example:
Gist URL
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Example2 {
/**
* A final List<Double> of all previous double generated with
* generateUniqueDouble(), turned into a string with Double.valueOf(d);
*/
private static final List<Double> PREVIOUS = new ArrayList<Double>();
/**
* The RANDOM variable used in the class.
*/
private static final Random RANDOM = new Random();
/**
* Generates a truly unique double.
*
* #param previous
* A List<Double> of previous doubles, converted into a Double
* with Double.valueOf(d);
* #return a UUID generated with UUID.randomUUID(); that is not included in
* the given List<Double>.
*/
public static double generateUniqueDouble(List<Double> previous) {
double d = RANDOM.nextDouble();
if (previous.contains(Double.valueOf(d))) {
return generateUniqueDouble(previous);
}
return d;
}
/**
* Generates a truly unique double using the final List<Double> PREVIOUS
* variable defined at the top of the class.
*
* #return A truly random double created with generateUnique(List<Double>
* previous);
*/
public static double generateUnique() {
double d = RANDOM.nextDouble();
PREVIOUS.add(Double.valueOf(d));
return d;
}
}
The point: Is this the most efficient method of doing something like this? Keep in mind I gave you examples, so they're pretty vague. Preferrably I wouldn't like to use any libraries for this, but if they really are a substantial difference in efficency please let me know about them.
Please let me know what you think in the responses :)
I suggest you make the generated IDs sequential numbers instead of doubles or uuids. If you want them to appear random to end users, display the sha1 of the number in base64.
Some points have already been discussed in the comments. To summarize and elaborate them here:
It is very unlikely that you create the same double value twice. There are roughly 7*1012 different double values (assuming that the random number generator can deliver "most" of them). For the UUIDs, the chance of creating the same value twice is even lower, since there are 2122 different UUIDs. If you created enough elements to have a non-negligible chance for a collision, you'd run out of memory anyhow.
So this approach does not make sense in practice.
However, from a purely theoretical point of view:
Performance
Using a List for this operation is not optimal. The "best case" (and by far the most common case) for you is that the new element is not contained in the list. But for the check whether the element is contained, this is the worst case: You'll have to check each and every element of the list, only to detect that the new element was not yet present. This is said to be linear complexity, or for short, O(n). You could use a different data structure where checking whether an element is contained can be done more quickly, namely in O(1). For example, you could replace the line
private static final List<Double> PREVIOUS = new ArrayList<Double>();
with
private static final Set<Double> PREVIOUS = new HashSet<Double>();
Performance and Correctness
(referring to the recursive approach in general here)
Performance
From a performance point of view, you should not use recursion when it can easily be replaced by an iterative solution. In this case, this would be trivial:
public static double generateUniqueDouble(List<Double> previous) {
double d = RANDOM.nextDouble();
while (previous.contains(d)) {
d = RANDOM.nextDouble();
}
PREVIOUS.add(d);
return d;
}
(it could be written a bit more compact, but that does not matter now).
Correctness
This is more subtle: When there are many recursive calls, then you might end up with a StackOverflowError. So you should never use recursion unless you can prove that the recursion will end (or better: That it will end "after a few steps").
But here's your main problem:
The algorithm is flawed. You cannot prove that it will be able to create a new random number. The chance that even a single new element is already contained in the collection of PREVIOUS elements is ridiculously low for double (or UUID) values. But it is not zero. And there is nothing preventing the random number generator from creating the random number 0.5 indefinitely, trillions of times in a row.
(Again: These are purely theoretical considerations. But not as far away from practice as they might look at the first glance: If you did not create random double values, but random byte values, then, after 256 calls, there would be no "new" values to return - and you would actually receive the StackOverflowError...)
It would be better to use a hash table than a list. Generate your candidate value, check for a collision in the hash table, and accept it if there is no collision. If you use a list, generating a new value is an O(n) operation. If you use a hash table, generating a new value is an O(1) operation .

Finding the union between two array that are part of different class instances

I am having trouble here. The question is:
The union of two collections consists of their contents combined into a new collection. Add a method union to the interface BagInterface for the ADT bag that returns as a new bag the union of the bag receiving the call to the
method and the bag that is the method’s one argument. Include sufficient comments to fully specify the method. Note that the union of two bags might contain duplicate items. For example, if object x occurs five times in one
bag and twice in another, the union of these bags contains x seven times. Specifically, suppose that bag1 and bag2 are Bag objects, where Bag implements BagInterface; bag1 contains the String objects a, b, and c; and bag2 contains
the String objects b, b, d, and e. After the statement BagInterface everything = bag1.union(bag2); executes, the bag everything contains the strings a, b, b, b, c, d, and e. Note that union does not affect the contents
of bag1 and bag2.
So essentially I have a class called ResizableArrayClass that specifies T[] bag in it's data field, and is essentially resizable per other methods within the class. The method header for "union" as defined in my interface is as follow's:
public BagInterface union(BagInterface anotherBag);
Normally, finding the union between two array's would be very simple. But I am trying to find the union between two array's that are part of two separate objects (bag1, bag2 of ResizableArrayClass). My question is, how would I go about finding the union between two array's in this way when using the following statement in a demo program:
BagInterface<String> everything = bag1.union(bag2);
Interface (sorry for comments):
public int getCurrentSize();
/** Sees whether this bag is empty.
#return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
#param newEntry The object to be added as a new entry.
#return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
#return Either the removed entry, if the removal.
was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag.
#param anEntry The entry to be removed.
#return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
#param anEntry The entry to be counted.
#return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
#param anEntry The entry to locate.
#return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
#return A newly allocated array of all the entries in the bag.
Note: If the bag is empty, the returned array is empty. */
public T[] toArray();
//public <T> T[] toArray(); // Alternate
//public Object[] toArray(); // Alternate
/** Creates a new bag that combines the contents of this bag and anotherBag.
#param anotherBag The bag that is to be added.
#return A combined bag. */
public BagInterface union(BagInterface anotherBag);
I think you could use BagInterface's methods only:
public BagInterface<T> union(BagInterface<T> anotherBag) {
BagInterface<T> result = new ResizableArrayClass<T>();
T[] mine = this.toArray();
for (T elem : mine) {
result.add(elem);
}
T[] others = anotherBag.toArray();
for (T elem : others) {
result.add(elem);
}
return result;
}

Does guava have an equivalent to Python's reduce function?

Does guava (or another java library) have something like reduce() function in Python?
I'm looking for something like this http://docs.python.org/library/functions.html#reduce
No. It might eventually, though functional stuff like that isn't a core focus of Guava. See this issue.
I've not (yet) managed to find any Java collections libraries that support map and reduce. (I exclude map/reduce functionality in parallel / distributed processing frameworks ... because you need a "big" problem for these frameworks to be worthwhile.)
Probably, the reason for this "lack" is that map/reduce coding without closures is just too cumbersome. Too much boilerplate code, too much heavy-weight syntax. Since the main point of using map / reduce primitives on simple collections is to make your code simple and elegant ...
#CurtainDog contributed a link to lambdaj. That does the kind of thing that the OP is after (though there's no method specifically called reduce). But it illustrates what I was saying about boilerplate. Notice that many of the higher order operations involve creating classes that extend one or other of the Closure classes.
(FWIW, I think that the Lambda.aggregate(...) methods are the lambdaj analog of reduce.)
Java 8 streams allow you to do this.
mylist.stream().map((x) -> x + 1).reduce((a,b) -> a + b)
For more information: http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
I have recently submitted an issue where I requested / discussed something similar. This is what would be needed in my implementation
/**
* Aggregate the selected values from the supplied {#link Iterable} using
* the provided selector and aggregator functions.
*
* #param <I>
* the element type over which to iterate
* #param <S>
* type of the values to be aggregated
* #param <A>
* type of the aggregated value
* #param data
* elements for aggregation
* #param selectorFunction
* a selector function that extracts the values to be aggregated
* from the elements
* #param aggregatorFunction
* function that performs the aggregation on the selected values
* #return the aggregated value
*/
public static <I, S, A> A aggregate(final Iterable<I> data,
final Function<I, S> selectorFunction,
final Function<Iterable<S>, A> aggregatorFunction){
checkNotNull(aggregatorFunction);
return aggregatorFunction.apply(
Iterables.transform(data, selectorFunction)
);
}
(The selector function can pull the value to aggregate from the object to query, but in many cases it will be Functions.identity(), i.e. the object itself is what's aggregated)
This is not a classic fold, but it requires a Function<Iterable<X>,X> to do the work. But since the actual code is a one-liner, I have instead chosen to request some standard aggregator functions (I'd put them in a class called something like Aggregators, AggregatorFunctions or even Functions.Aggregators):
/** A Function that returns the average length of the Strings in an Iterable. */
public static Function<Iterable<String>,Integer> averageLength()
/** A Function that returns a BigDecimal that corresponds to the average
of all numeric values passed from the iterable. */
public static Function<Iterable<? extends Number>,BigDecimal> averageOfFloats()
/** A Function that returns a BigInteger that corresponds to the average
of all numeric values passed from the iterable. */
public static Function<Iterable<? extends Number>,BigInteger> averageOfIntegers()
/** A Function that returns the length of the longest String in an Iterable. */
public static Function<Iterable<String>,Integer> maxLength()
/** A Function that returns the length of the shortest String in an Iterable. */
public static Function<Iterable<String>,Integer> minLength()
/** A Function that returns a BigDecimal that corresponds to the sum of all
numeric values passed from the iterable. */
public static Function<Iterable<? extends Number>,BigDecimal> sumOfFloats()
/** A Function that returns a BigInteger that corresponds to the integer sum
of all numeric values passed from the iterable. */
public static Function<Iterable<? extends Number>,BigInteger> sumOfIntegers()
(You can see my sample implementations in the issue)
That way, you can do things like this:
int[] numbers = { 1, 5, 6, 9, 11111, 54764576, 425623 };
int sum = Aggregators.sumOfIntegers().apply(Ints.asList(numbers)).intValue();
This is definitely not what you are asking for, but it would make like easier in many cases and would overlap with your request (even if the approach is different).
Jedi has a reduce operation. Jedi also helps reduce the boiler plate by using annotations to generate functors for you. See these examples.
Guava has transform (map). Seems like reduce is missing though?
I have developed a library to do map/filter/reduce with standard J2SE.
Sorry it is in french, but with google translate you can read it :
http://caron-yann.developpez.com/tutoriels/java/fonction-object-design-pattern-attendant-closures-java-8/
You can use if like this :
int sum = dogs.filter(new Predicate<Arguments2<Dog, Integer>>() {
#Override
public Boolean invoke(Arguments2<Dog, Integer> arguments) {
// filter on male
return arguments.getArgument1().getGender() == Dog.Gender.MALE;
}
}).<Integer>map(new Function<Integer, Arguments2<Dog, Integer>>() {
#Override
public Integer invoke(Arguments2<Dog, Integer> arguments) {
// get ages
return arguments.getArgument1().getAge();
}
}).reduce(new Function<Integer, Arguments2<Integer, Integer>>() {
#Override
public Integer invoke(Arguments2<Integer, Integer> arguments) {
// sum âges
return arguments.getArgument1() + arguments.getArgument2();
}
});
System.out.println("Le cumul de l'âge des mâles est de : " + sum + " ans");
Enjoy this help
Use Totally Lazy, it implements all of those things an even more.
It basicly copied the whole funcional approach from Clojure.

Java - sorted stack

I need a sorted stack. I mean, the element removed from the stack must be the one with great priority. Stack dimension varies a lot (becomes bigger very fast).
I need also to search elements in that stack.
Does Java give some good implementation for this? What class or algorithm do you suggest for this?
I'm using a PriorityQueue right now which I consider reasonable except for searching, so I'm wondering if I can use something better.
I also need to remove elements!
In summary: I need to maintain a sorted stack/queue, get the element with greater priority fast and also remove elements as fast as possible
TreeSet is a sorted set. Set means no duplicates though.
add() adds an item, which is inserted in the correct sorted place.
pollLast() removes and returns the last item,
pollFirst() removes and returns the first item.
Java doesn't provide a PriorityStack, but you could easily write one by wrapping the PriorityQueue class and providing the push/pop methods to manage the underlying queue.
import java.util.Stack;
public class Q6_SortStack {
/**
* #param args
* Write a program to sort a stack in ascending order.
* You should not make any assumptions about how the stack is implemented.
* The following are the only functions that should be used to
* write this program: push | pop | peek | isEmpty.
*/
public static void main(String[] args) {
int[] array = {2,5,10,3,11,7,13,8,9,4,1,6};
Stack<Integer> s1 = new Stack<Integer>();
//int[] array = {2,4,1,6};
for(int i=0;i<array.length;i++){
s1.push(array[i]);
}
//displayStack(s1);
displayStack(sortStack(s1));
}
public static Stack<Integer> sortStack(Stack<Integer> s1){
Stack<Integer> s2 = new Stack<Integer>();
while(!s1.isEmpty()){
int temp = s1.pop();
while(!s2.isEmpty() && s2.peek()<temp){
s1.push(s2.pop());
}
s2.push(temp);
}
return s2;
}
public static void displayStack(Stack<Integer> s){
while(!s.isEmpty())
System.out.print(s.pop()+"->");
System.out.println("end");
}
}
You can always use two data structures. A priority queue and a map. The first will let you get the smallest/largest item, and the second will let you search items fast. You just need to wrap them in the logic to keep them in sink (which shouldn't be too hard)
You could modify/overload the method you use to push data into your stack such that it inserts into the correct or "sorted" position. Otherwise, if you're implementing the stack using an array of some primitive datatype, you could use Arrays.sort(*Stack data array goes here*) from the java.util package every time you push data into the stack.

Categories