Using a stack as a Queue in Java - java

I need to process a tree in different orders, let's say BFS and DFS. Both is easy by using a queue or a stack, however, I'm missing a proper interface in Java allowing to do something like
QueueOrStack<N> pending = ...
while (!pending.isEmpty()) {
N node = pending.poll(); // <----- this is the problem
pending.addAll(node.children());
process(node);
}
There's no real problem, I can encapsulate an ArrayList into something implementing Queue1, however I'd bet I'm overlooking something in the Java Collection Framework. Or is it really missing?
__
1 or use a newest-first comparator with a PriorityQueue, which is probably a dumb idea

There is such a structure.
It is called ArrayDeque -> http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html

Related

Why is there an algorithm to find loops in linked lists, when the implementation should prevent them? [duplicate]

I see many Q/A on how to detect a loop in linked list, but I want to understand is why we want to do that, in other words what are the practical use cases of detecting a loop in a linked list
In real life, you'll probably never need to detect a loop in a linked list, BUT the algorithms for doing that are important and I have used them in real life many times.
Pretty often, for example, I will process a linked data structure recursively when it's supposed to be tree-shaped. If it isn't tree-shaped and has a cycle, however, that would cause infinite recursion and a stack overflow, so I like to catch that before it explodes. I usually use Brent's cycle-finding algorithm for that, because it's easy to fit into my recursive processing and has extremely low overhead.
Cycle finding algorithms are also useful in Pollard's "rho" factorization algorithm (https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm)
The ideas you learn when learning about these algorithms will also be useful when learning other more complex things later on.
ETA:
I should add that common situations that produce cycles by mistake are those in which users specifically create the links. For example in Java a class can have a superclass, and the programmer writes class C extends A {}, for example. The extends keyword creates a link between classes. If he also writes class A extends C, then he has created a cycle and the compiler has to detect that condition.
linked list with loop has no end , linked list contains two links to some node
Iterating through the linked list will yield all nodes in the loop multiple times A malformed (with unknown loop) linked list with a loop causes iteration over the list to fail because the iteration will never reach the end of the list. Therefore, it is desirable to be able to detect that a linked list is have loop before trying an iteration
you can find answer here
https://blog.ostermiller.org/find-loop-singly-linked-list
Because, if you have a list like this (for example):
head -> A -> B -> C -+
^ |
+-------+
and the code to traverse it as follows:
node = head
while node <> null:
processNode(node)
node = node.next
then you will never complete the loop. It will happily process A, B, C, B, C, B, C,... for eternity (or until the heat death of the universe, whichever comes first).
A normal linked list will never have a cycle in it. In order to detect such a degenerate list, you can look at this answer.
Note that some cyclic linked lists are indeed valid. One example I've seen was a process list used for scheduling where the head and tail are irrelevant (since the thing that processes them wanted to loop over them forever). Hence the scheduler would be something like:
curr = somePointInList()
while true:
runForABit(curr)
curr = curr.next

Is there a capacity-restricted queue object in Java that is accessible from both ends?

I was thinking something the likes of java.util.ArrayBlockingQueue, which enables you to create size-limited queues. But that would have methods to retrieve and and add elements from both sides (head or tail).
Kind of like Perl arrays which have push/pop and shift/unshift methods.
I can probably roll my own but if something already exists out there I'd like to know.
There certainly is, the LinkedBlockingDeque.

Produce a Stream from a Stream and an element, Java 8

I'm working on getting my head around some of the Java 8 Stream features. I'm tolerably familiar with FP, having written some Lisp thirty years ago, and I think I might be trying to do something this new facility isn't really targeted at. Anyway, if the question is stupid, I'm happy to learn the error of my ways.
I'll give a specific problem, though it's really a general concept I'm trying to resolve.
Suppose I want to get a Stream from every third element of a Stream. In regular FP I would (approximately) create a recursive function that operates by concatenating the first element of the list with the (call-thyself) of the remainder of the list after dropping two elements. Easy enough. But to do this in a stream, I feel like I want one of two tools:
1) a means of having an operation extract multiple items from the stream for processing (then I'd just grab three, use the first, and dump the rest)
2) a means of making a Supplier that takes an item and a Stream and creates a Stream. Then it feels like I could create a downstream stream out of the first item and the shortened stream, though it's still unclear to me if this would do the necessary recursive magic to actually work.
BEGIN EDIT
So, there's some interesting and useful feedback; thanks everyone. In particular, the comments have helped me clarify what my head is trying to get around a bit better.
First, one can--conceptually, at least--having / needing knowledge of order in a sequence should not prevent one from permitting fully parallelizable operations. An example sprang to mind, and that's the convolution operations that graphics folks are inclined to do. Imagine blurring an image. Each pixel is modified by virtue of pixels near to it, but those pixels are only read, not modified, in themselves.
It's my understanding (very shaky at this stage, for sure!) that the streams mechanism is the primary entry point to the wonderful world of VM managed parallelism, and that iterators are still what they always were (yes? no?) If that's correct, then using the iterator to solve the problem domain that I'm waffling around doesn't seem great.
So, at this point, at least, the suggestion to create a chunking spliterator seems the most promising, but boy, does the code that supports that example seem like hard work! I think I'd rather do it with a ForkJoin mechanism, despite it being "old hat" now :)
Anyway, still interested in any more insights folks wish to offer.
END EDIT
Any thoughts? Am I trying to use these Streams to do something they're not intended for, or am I missing something obvious?
Cheers,
Toby.
One of the things to keep in mind is that Stream was primarily designed to be a way of taking advantage of parallel processing. An implication of this is that they have a number of conditions associated with them that are aimed at giving the VM a lot of freedom to process the elements in any convenient order. An example of this is insisting that reduction functions are associative. Another is that local variables manipulated are final. These types of conditions mean the stream items can be evaluated and collected in any order.
A natural consequence of this is that the best use cases for Stream involve no dependencies between the values of the stream. Things such as mapping a stream of integers to their cumulative values are trivial in languages like LISP but a pretty unnatural fit for Java streams (see this question).
There are clever ways of getting around some of these restrictions by using sequential to force the Stream to not be parallel but my experience has been that these are more trouble than they are worth. If your problem involves an essentially sequential series of items in which state is required to process the values then I recommend using traditional collections and iteration. The code will end up being clearer and will perform no worse given the stream cannot be parallelised anyway.
Having said all that, if you really want to do this then the most straightforward way is to have a collector that stores every third item then sends them out as a stream again:
class EveryThird {
private final List<Integer> list = new ArrayList<>();
private int count = 0;
public void accept(Integer i) {
if (count++ % 3 == 0)
list.add(i);
}
public EveryThird combine(EveryThird other) {
list.addAll(other.list);
count += other.count;
return this;
}
public Stream<Integer> stream() {
return list.stream();
}
}
This can then be used like:
IntStream.range(0, 10000)
.collect(EveryThird::new, EveryThird::accept, EveryThird::combine)
.stream()
But that's not really what collectors are designed for and this is pretty inefficient as it's unnecessarily collecting the stream. As stated above my recommendation is to use traditional iteration for this sort of situation.
My StreamEx library enhances standard Stream API. In particular it adds the headTail method which allows recursive definition of custom operations. It takes a function which receives stream head (first element) and tail (stream of the rest elements) and should return the resulting stream which will be used instead of the original one. For example, you can define every3 operation as follows:
public static <T> StreamEx<T> every3(StreamEx<T> input) {
return input.headTail(
(first, tail1) -> tail1.<T>headTail(
(second, tail2) -> tail2.headTail(
(third, tail3) -> every3(tail3))).prepend(first));
}
Here prepend is also used which just prepends the given element to the stream (this operation is just a best friend of headTail.
In general using headTail you can define almost any intermediate operation you want, including existing ones and new ones. You may find some samples here.
Note that I implemented some mechanism which optimizes tails in such recursive operation definition, so properly defined operation will not eat the whole stack when processing the long stream.
Java's streams are nothing like FP's (lazy) sequences. If you are familiar with Clojure, the difference is exactly like the difference between lazy seq and reducer. Whereas the lazy seq packages all processing with each element individually, and thus allows getting individually processed elements, a reducer collapses the complete sequence in a single atomic operation.
Specifically for the example you have described, consider relying on a stream partitioning transformation, as described in detail here. You would then easily do
partition(originalStream, 3).map(xs -> xs.get(0));
resulting in a stream having every third element of the original.
This would maintain efficiency, laziness, and parallelizability.
You can use (or peek at the source) of BatchingSpliterator
Then given aStream you can create a stream that consists of lists with size=3 (except maybe for the last one) and use the first element of that list
Stream<T> aStream = ...;
Stream<List<T>> batchedStream =
new BatchingSpliterator.Builder().wrap(aStream).batchSize(3).stream();
batchedStream.map(l -> l.get(0) ). ...
You can also "go parallel":
batchedStream.parallel().map(l -> l.get(0) ). ....

How do we usually process sequences in Java?

In C++, iterators in STL is very useful. I can write container independent code to process sequences.
However, I found Iterator and ListIterator are very poor in Java. They even don't support clone(). I think it's impossible to process sequences with them.
The only way to do this seems to be using arrays forever, but how can I reuse my code when I change arrays to Lists ?
Processing sequences is to do some algorithms on a sequences of Objects. For example, sorting them , finding the maximun, remove duplicated items.
List<Type> list = new List<Type>
//add the elements...
for(Type t : list)
//do you stuff with t
Normally you will not need to use the iterators explicitly in Java. Also, be careful with .clone() as it is rarely the most appropriate solution.
List itself is a interface that is implemented by different containers.
I would use List<Type>, and avoid clone() as it doesn't always do what you think. i.e. it can be shallow or deep depending on the implementation.
List is a basic class. Perhaps if you give an example of what you are having trouble with it we can help you with that.

Printing out items in any Collection in reverse order?

I have the following problem in my Data Structures and Problem Solving using Java book:
Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.
First, I believe it is asking you to write a method. Like:
void printReverseList(Collection col) {}
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).
That could technically count as 1 routine (all have the same name).
I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.
You might want to read this.
Isn't there a base Collection class?
Probably worth looking here as a starting point: Collections.

Categories