Suppose I have a list(0,1,2,3,4,5,6)
I already have my queueclass.
I want the result as 1,3,5,0,2,4,6 (the item at nth position is attached to the end of the original queue.
Here is what I have so far:
Queue a=new Queue();
for(int i=0;i<7;i++){
a.enter(i);
}
Queue temp=new Queue();`
while(!a.isEmpty()){
temp.enter(a.leave());//put the first element in temp
System.out.print(a.leave()+" ");//print out the second one
a.enter(temp.leave());//put the first element at the end of original queue
}
So My idea is to store the item that leave in temp then enter back.
No matter how I try this, it cannot give me the correct result. And its a infinite loop.
leave() remove the first item and return it.
enter() put the element at the end of queue
OK I've solved the problem.
I should do like:
while(!a.isEmpty()){
a.enter(a.leave());
System.out.print(a.leave()+" ");
}
Then it will give me the correct result.
Thanks guys for the effort, and sorry if anything in this problem is unclear. I'm still new to this :)
I will start by warning you that this is a lousy answer that does not actually solve your problem, because I can't figure out what your goal is. It does, however, explain the infinite loop you've encountered.
The infinite loop is the while, which waits for Queue a to be empty, which will never happen (unless a was already empty when the while loop started).
Each iteration through your while loop de-queues two items from a, and then en-queues the first item. Even if this is what you intended for most of the iterations (I honestly can't tell), it fails for what should have been the last one.
When a is down to just one element, your while loop starts repeating this useless behavior forever:
Remove the one and only element from Queue a.
Remove another element from the now-empty a... somehow.
Print God-knows-what, followed by a space.
Put that "one and only" element (the one that actually existed) right back onto a.
Test if a is empty, which --- surprise --- it is not.
Go to 1.
Heat-Death of the Universe.
Once Queue a gets caught in this trap, it will "always" contain that last element. The brief moments during which it is empty will occur only in the middle of the while block, and never during the iteration test at the top of that same block.
Other Weirdness
I came up with these questions while typing this answer. They are questions you should ask yourself:
What is the goal of your program? (This will be required for almost any Stack Overflow questions you ask in the future. Its near-absence from this question is why you've received such an incomplete answer.)
What happens when you call leave on an empty Queue? (Your while loop does this forever.) Why is that the obviously correct thing to do? What are the alternatives, and why are they obviously incorrect?
What is Queue temp for? It never has more than one item in it, so why can't it be replaced with a local variable?
Why do you print the items you throw away? Alternatively: Why do you throw away the items you print? Is printing them to the console something you wanted to do at all?
What does any of this have to do with the "Nth position" in your title?
For future questions, I suggest you review the Help Center's "How do I ask a good question?" and the links at the bottom of that article, especially Eric Lippert's "How To Debug Small Programs". I suspect your code could benefit a lot from the latter's "Rubber Duck Debugging":
Explain to the duck using simple words why each line of each method in your program is obviously correct. At some point you will be unable to do so, either because you don't understand the method you wrote, or because it's wrong, or both. Concentrate your efforts on that method; that's probably where the bug is.
The duck would have caught many of these, I think.
the methods used in the program doesn't exist i believe i.e .leave()
but to get the element from any position using queues then you can use this
here n is the required position-1
for example if you need to print out element which is at position 5
n = 5-1, i.e 4
cause it follows indexing.
for(int i = 0; i<n; i++) {
queue.remove();
}
System.out.print(queue.peek());
Related
When solving the Chinese postman problem (route inspection problem), how can we find the pairings (between odd vertices) such that the sum of the weights is minimized?
This is the most crucial step in the algorithm that successfully solves the Chinese Postman Problem for a non-Eulerian Graph. Though it is easy to implement on paper, but I am facing difficulty in implementing in Java.
I was thinking about ways to find all possible pairs but if one runs the first loop over all the odd vertices and the next loop for all the other possible pairs. This will only give one pair, to find all other pairs you would need another two loops and so on. This is rather strange as one will be 'looping over loops' in a crude sense. Is there a better way to resolve this problem.
I have read about the Edmonds-Jonhson algorithm, but I don't understand the motivation behind constructing a bipartite graph. And I have also read Chinese Postman Problem: finding best connections between odd-degree nodes, but the author does not explain how to implement a brute-force algorithm.
Also the following question: How should I generate the partitions / pairs for the Chinese Postman problem? has been asked previously by a user of Stack overflow., but a reply to the post gives a python implementation of the code. I am not familiar with python and I would request any community member to rewrite the code in Java or if possible explain the algorithm.
Thank You.
Economical recursion
These tuples normally are called edges, aren't they?
You need a recursion.
0. Create main stack of edge lists.
1. take all edges into a current edge list. Null the found edge stack.
2. take a next current edge for the current edge list and add it in the found edge stack.
3. Create the next edge list from the current edge list. push the current edge list into the main stack. Make next edge list current.
4. Clean current edge list from all adjacent to current edge and from current edge.
5. If the current edge list is not empty, loop to 2.
6. Remember the current state of found edge stack - it is the next result set of edges that you need.
7. Pop the the found edge stack into current edge. Pop the main stack into current edge list. If stacks are empty, return. Repeat until current edge has a next edge after it.
8. loop to 2.
As a result, you have all possible sets of edges and you never need to check "if I had seen the same set in the different order?"
It's actually fairly simple when you wrap your head around it. I'm just sharing some code here in the hope it will help the next person!
The function below returns all the valid odd vertex combinations that one then needs to check for the shortest one.
private static ObjectArrayList<ObjectArrayList<IntArrayList>> getOddVertexCombinations(IntArrayList oddVertices,
ObjectArrayList<IntArrayList> buffer){
ObjectArrayList<ObjectArrayList<IntArrayList>> toReturn = new ObjectArrayList<>();
if (oddVertices.isEmpty()) {
toReturn.add(buffer.clone());
} else {
int first = oddVertices.removeInt(0);
for (int c = 0; c < oddVertices.size(); c++) {
int second = oddVertices.removeInt(c);
buffer.add(new IntArrayList(new int[]{first, second}));
toReturn.addAll(getOddVertexCombinations(oddVertices, buffer));
buffer.pop();
oddVertices.add(c, second);
}
oddVertices.add(0, first);
}
return toReturn;
}
I want to use an empty stack S to check whether a Queue Q contaitns element x, thus my solution was to copy elements of Q into S and check if contain x, but I'm also asked to return S elements into Q again as it was originaly, this must be done using only a Q and S without any other arrays of SL, so I have written this algorithm:
Boolean found ← false
int element ← 0
While(Q is not empty)
element ← Q.dequeue()
if(element equal x)
found ← true
S.push(element)
While(S is not empty)
( elements back to Q) ?
stuck in last step, if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed
Correct, the order will be reversed.
This means that if you repeat the algorithm yet again (all to S and back to Q) you will reverse it yet again, meaning you will get back to the original order of elements, which is what you want.
if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed
That's right, it will be reversed. You can use it to your advantage by observing that once you run the same loop again, you would get the original order back.
You can avoid writing the same loop twice if you make a method that does the search, and leaves the queue in reversed state. You can call your search method twice, and ignore the second return value.
This feels like a HW question so I won't solve it for you, but I will give you a hint - what happens when you dequeue a queue into a stack and then dequeue the stack back to the queue?
How can you use that phenomena to restore the original queue?
I am not sure how java default Queue work.
Remove element from the end of the queue.
Check if that element is x, if so return true.
Else, push it into the stack
Repeat until you find x or all the Queue is empty.
When you are done, pop elements one by one from the stack and add them at the beginning of the queue everytime, the last element in the stack would become the first element in the queue. Thus you maintain the order.
I have been looking at the current problem on Coding Bat:
"We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows."
I understand what the problem is asking for, and I understand how recursion works. For example, if I am given a recursion function I can work it out by hand and show what the output will be.
The problem is actually creating the recursion function from a given problem, such as this one. I'm not sure how to actually set this up and do it recursively. Are there some sort of rules to follow when actually setting up a recursion problem? I can only find examples that show you how recursion works, not showing you how to actually solve a recursion problem. Any help understanding how to get ready to write the actually recursion algorithm would be appreciated.
Roughly:
Always look at the problem and try to find out if it can be divided
into subproblems of the same type. That's a first hint that you can
possibly use a recursion. Essentially you are looking for a smaller
instances/versions of an actual problem.
Recursion takes therefore a top down approach(from the more complex to simpler problem cases).
When you can find such cases then you should find out what is the
relation between the "bigger" case and the "smaller" case and you
have your recursion step.
The final thing is to find out the terminating condition or what
is the smallest or last case where you want to stop.
You probably know about this but if not it might help you.
For a recursion algorithm,
first design the base case, for which the function should start the unwinding of the stack or to return the base value.
Then design the algorithm to be actually done, for each of the non-base cases
if(rows == 1) return 1; is useless here.
For the recursion global issue, you must disassemble your problem and find:
An exit rule (can be an initial value like in your example, or some exit condition on one of the inputs)
A stepping process (what do you have to do with the previous input to get the next one)
And assemble them in a function that calls itself.
Try this code:
#include <iostream>
using namespace std;
int sumf(int row,int sum){
if(row==0) //basecase which ends the recursion.
return sum;
else
{sum=row+sum;
return sumf(--row,sum); // repeating the process.
}}
int main() {
cout<<"sum is: "<<sumf(5,0)<<endl;
system("pause");
return 0;
}
This is the video which make you understand about recursion.(forget about language just focus on concept.)
http://www.youtube.com/watch?v=sNJQrtGD1Nc
It must be really basic but I need help. For example, you store monster information in an array, and do for~loop to make each monster attacks/moves in their turn like this
for( i <- 0 to monsters.length-1) monsters(i).act
Then some monsters die during the loop and you have to delete some elements in the array while the loop is still on going. Then the next item in the array could be not really the the next one you want to process.
is there any fast/smart way to make sure each item in an array will be proceed once and only once within the loop, even if you really had to make change to the array during loop?
Scala's collections generally don't assume that you'll be manipulating them while they're using a method like foreach (or executing a for loop). If you want to do things that way, the easiest class to use is Java's java.util.concurrent.ConcurrentSkipListMap.
// This helps you use Java collections like Scala ones
import collection.JavaConversions._
case class Monster(name: String, hp: Int) {}
val horde = new java.util.concurrent.ConcurrentSkipListMap[Int,Monster]
horde put (0, Monster("wolf",7))
horde put (1, Monster("orc",3))
for (h <- horde) println(h) // Prints out both
Iterator.iterate(Option(horde.firstEntry)) {
case None => None
case Some(e) =>
val m = e.getValue
if (m.name=="wolf") horde.remove(1) // Kill the orc
else if (m.name=="orc") horde.remove(0) // Kill the wolf
Option(horde.higherEntry(e.getKey))
}.takeWhile(_.isDefined).foreach(_=>())
for (h <- horde) println(h) // Prints out just the wolf
Now, granted, this is rather a mess, but it does work, and it gives nice random access to your monsters. You have to maintain the keys in a sensible order, but that's not too hard.
Alternatively, as others have indicated, you could add an isAlive or isDead method, and only act on monsters that are alive. Then, after you've passed through the list once, you .filter(_.isAlive) to throw away all the dead monsters (or .filter(! _.isDead)), and run it again.
I would either use a conditional statement to check the monster's isAlive property in the loop before I called act, or do that check inside the act method itself.
I imagine that your monster[i] is not going to die on his turn, but rather off some other hapless monster?
If you're hooked on arrays, or don't mind the processing time (and for what you're doing, i reckon you don't care), just keep a boolean on each monster of isDead.
If a monster dies due to some ... i dunno, reason, just mark the "isDead" as true.
Then, in your monster "act" method, just check if the monster "isDead" or not.
After each loop, you can just prune the list to keep the alive monsters (move all the ones that are alive to a new list and begin again, prune the list in place, whatever is easier for you).
EDIT: This first graph misinterperets your question. However, my solution should still work for you.
What you're asking for is a thread-safe array - one that can be accessed by multiple "threads" of execution at a time. Seeing as you're new to Java, my guess is that your game is not going to be multithreaded, and so if you delete an item in an array, that's going to happen for sure before your next loop runs.
That said, if you really want to, you can add a "monster.dead" boolean function to your array, and set that to true whenever a monster dies. In your loop, then, you'd say:
for( i <- 0 to monsters.length-1)
if (monsters[i].dead == false)
monsters(i).act
Most likely, though, you won't run into this issue.
Edit: just reread your post, and realized that you'll be deleting monsters as your array is running. Remember that each line you execute happens sequentially, so when you remove monsters[i], it will be gone the next time the for loop is evaluated. If you have an array of monsters with 5 monsters in it and you delete the second one, when the loop executes again,
monsters.length - 1
is going to evaluate to 3 now. You'll never run into a moment where you hit a deleted array element.
If you delete an entry in an array, this element would be null.
Therefore you should check every element of your array, e.g.:
for(int i = 0; i <= array.lenght - 1; i++) {
// check null
if(array[i] != null) {
// do stuff
}
}
Hope this helped, have Fun!
make a copy of the original array, and traverse the copy.
if a monster would remove a monster, it would be removed only from the original
Deleting elements from an array while looping over it is generally a horrible idea. What if you delete an element before you reach it in the loop? Should you not actually delete it until the end of the loop, or should you skip over it?
I recommend something more like this:
var monsters = ... initial list of monsters ...
monsters = for (m <- monsters; if m.alive) yield { m.act; m }
Take advantage of yield and if in conjunction with the for loop, which allows you to build a new list.
I keep getting random java.lang.IndexOutOfBoundsException errors on my program.
What am i doing wrong?
The program runs fine, its a really long for loop, but for some elements i seem to be getting that error and then it continues on to the next element and it works fine.
for (int i = 0; i < response.getSegments().getSegmentInfo().size()-1; i++) {
reservedSeats = response.getSegments().getSegmentInfo().get(i).getCabinSummary().getCabinClass().get(i).getAmountOfResSeat();
usedSeats = response.getSegments().getSegmentInfo().get(i).getCabinSummary().getCabinClass().get(i).getAmountOfUsedSeat();
System.out.println("Reserved Seats: " + reservedSeats);
System.out.println("Used Seats : " + usedSeats);
}
How can i prevent this errors?
For those thinking this is an array, it is more likely a list.
Let me guess, you used to be getting ConcurrentModificationExceptions, so you rewrote the loop to use indexed lookup of elements (avoiding the iterator). Congratulations, you fixed the exception, but not the issue.
You are changing your List while this loop is running. Every now and then, you remove an element. Every now and then you look at the last element size()-1. When the order of operations looks like:
(some thread)
remove an element from response.getSegments().getSegmentInfo()
(some possibly other thread)
lookup up the size()-1 element of the above
You access an element that no longer exists, and will raise an IndexOutOfBoundsException.
You need to fix the logic around this List by controlling access to it such that if you need to check all elements, you don't assume the list will be the same as it crosses all elements, or (the much better solution) freeze the list for the loop.
A simple way of doing the latter is to do a copy of the List (but not the list's elements) and iterate over the copy.
--- Edited as the problem dramatically changed in an edit after the above was written ---
You added a lot of extra code, including a few extra list lookups. You are using the same index for all the list lookups, but there is nothing to indicate that all of the lists are the same size.
Also, you probably don't want to skip across elements, odds are you really want to access all of the cabin classes in a segmentInfo, not just the 3rd cabinClass in the 3rd segmentInfo, etc.
You seem to be using i to index into two entirely separate List objects:
response.getSegments().getSegmentInfo().get(i) // indexing into response.getSegments().getSegmentInfo()
.getCabinSummary().getCabinClass().get(i) // indexing into getCabinSummary().getCabinClass()
.getAmountOfResSeat();
This looks wrong to me. Is this supposed to happen this way? And is the list returned by getCabinClass() guaranteed to be at least as long as the one returned by getSegmentInfo()?
You're using i both as an index for the list of segment infos and for the list of cabin classes. This smells like the source of your problem.
I don't know your domain model but I'd expect that we need two different counters here.
Refactored code to show problem (guessed the types, replace with correct class names)
List<SegmentInfo> segmentInfos = response.getSegments().getSegmentInfo();
for (int i = 0; i < segmentInfos.size()-1; i++) {
// use i to get actual segmentInfo
SegmentInfo segmentInfo = segmentInfos.get(i);
List<CabinClass> cabinClasses = segmentInfo.getCabinSummary.getCabinClass();
// use i again to get actual cabin class ???
CabinClass cabinClass = cabinClasses.get(i);
reservedSeats = cabinClass.getAmountOfResSeat();
usedSeats = cabinClass.getAmountOfUsedSeat();
System.out.println("Reserved Seats: " + reservedSeats);
System.out.println("Used Seats : " + usedSeats);
}
Assuming that response.getSegments().getSegmentInfo() always returns an array of the same size, calling .get(i) on it should be safe, given the loop header (but are you aware that you are skipping the last element?) However, are you sure that .getCabinSummary() will return an array that is as large as the getSegmentInfo() array? It looks suspicious that you are using i to perform lookups in two different arrays.
You could split the first line in the loop body into two separate lines (I'm only guessing the type names here):
List<SegmentInfo> segmentInfo = response.getSegments().getSegmentInfo().get(i);
reservedSeats = segmentInfo.getCabinSummary().get(i).getAmountOfResSeat();
Then you'll see which lookup causes the crash.