I am in need of some help trying to compare 2 arraylist and then sorting; If I am even on the right track. So here is my problem..
Say arraylist 1 contains the objects in which 3 integers adds up to 4 and each integer has to be at least greater or greater/equal to the next number.
So for example, arraylist 1 contains {(2,1,1), (2,2,0), (3,1,0), (4,0,0)}.
Also each object integers are sorted from greatest to least.
Now I have a take the (2,1,1) and send it to a method to perform an algorithm on it. for each integer place, i need to add 2 to that integer place, and subtract 1 from the rest. We can call these A event, B event, or C Event.
for example, (2,1,1) which these events would be
A Event: (4,0,0)
B Event: (3,1,0)
C Event: (3,1,0)
Now, my question is because A event produced (4,0,0) how would I sort the first arraylist to have that number come next and then have (3,1,0) but without (3,1,0) duplicating. So after sorting the array, it should be
(2,1,1) ( 4,0,0) (3,1,0) (2,2,0)
At present your question is not clear to me, but I think I can help point you in the right direction.
Since you said:
without (3,1,0) duplicating
I'd suggest that to ensure uniqueness of objects in a Collection you should consider using a class that implements the Set interface (see Javadoc for Set for details).
Assuming you are not writing the sorting algorithm yourself you could use a SortedSet and then implement the necessary functionality (Comparable interface or Comparator) so that your objects are sorted in the way you want (the earlier link provides links that describe how to do this).
Hope this helps, and if you could try to make the question more clear I'd be happy to offer some additional pointers.
Here are some of the confusing parts that you could work on:
each integer has to be at least greater or greater/equal to the next number.
This is confusing because you're giving two conflicting requirements. Is each number strictly greater than the next or is it greater than or equal to the next?
Also each object integers are sorted from greatest to least.
I'm not sure what you mean by this because you already said that the integers contained in the objects were in a specific order.
because A event produced (4,0,0) how would I sort the first arraylist to have that number come next
You're not really telling us how the sorting should work. Can you describe the algorithm more - how does it decide the order of the items, how should one item be compared with another?
Related
I have the following homework question:
Suppose you are given two sequences S1 and S2 of n elements, possibly containing duplicates, on which a total order relation is defined. Describe an efficient algorithm for determining if S1 and S2 contain the same set of elements. Analyze the running time of this method
To solve this question I have compared elemements of the two arrays using retainAll and a HashSet.
Set1.retainAll(new HashSet<Integer>(Set2));
This would solve the problem in constant time.
Do I need to sort the two arrays before the retainAll step to increase efficiency?
I suspect from the code you've posted that you are missing the point of the assignment. The idea is not to use a Java library to check if two collections are equal (for that you could use collection1.equals(collections2). Rather the point is to come up with an algorithm for comparing the collections. The Java API does not specify an algorithm: it's hidden away in the implementation.
Without providing an answer, let me give you an example of an algorithm that would work, but is not necessarily efficient:
for each element in coll1
if element not in coll2
return false
remove element from coll2
return coll2 is empty
The problem specifies that the sequences are ordered (i.e. total order relation is defined) which means you can do much better than the algorithm above.
In general if you are asked to demonstrate an algorithm it's best to stick with native data types and arrays - otherwise the implementation of a library class can significantly impact efficiency and hide the data you want to collect on the algorithm itself.
I have been trying to figure out a question on a recent assignment for a few days now, and I can't seem to wrap my head around it. The question reads as follows:
Create a PriorityQueue class that contains two fields noOfPriorities
and a LinkedList… It should have one constructor that takes in an int
value assign that value to the noOfPriorities… at the same time add as
many LinkedLists as numberOfPriorities.. Enqueue method that takes in
a priority and an object.. Dequeue method that returns the next
priority element… and remove it from the list…
A large part of my problem is that I can't determine exactly what the professor is looking for because the wording seems a bit weird to me... simply asking about it yielded no help either.
Just to clarify, I'm not looking for anyone to give me the answer. I'm simply looking for a push in the right direction. If anyone could help It would be greatly appreciated.
Cheers on being honest about this being homework.
I think you can understand the problem better if you read up on what a priority queue is.
Let's take a small example. You have a few tasks to do, and each task has a priority.
Pri 1 - breathe, eat, sleep
Pri 2 - study, play
Pri 3 - watch a movie
All the above information can be handled by your PriorityQueue. You have 3 kinds of priorities, so you have 3 lists. Each list is to maintain tasks with the same priority.
Once you construct the empty PriorityQueue by calling PriorityQueue(3), you can add tasks to it.
Let's say you want to add the task "study" that has priority 2.
You can say, priorityQueue.enqueue(2, "study"). You would then go to the list that maintains priority 2 items, and add the task "study" to that list.
Similarly, when you want to find out what the next priority 3 item is, you can say, priorityQueue.dequeue(3). You would then find the list that handles priority 3 items, and remove the last element from that list.
This should give you a good understanding to start working. :)
Agreed, the assignment's badly worded.
at the same time add as many LinkedLists as numberOfPriorities..
This should probably be "at the same time add as many nodes to the LinkedList as numberOfPriorities.."
The next question to ask yourself is, just what type of thing should I store in all these linked nodes...?
I think you'd need an array of linked lists instead of just one. The problem description is contradictory, saying that you need both a class that has one linked list, and to create a number of them when you construct an object.
Here's a constructor for your class:
MyPriorityQueue(int npriorities)
{
noOfPriorities = npriorities;
queueArray = new ArrayList<List<T>>();
for (int i = 0; i < npriorities; ++i) queueArray.add(new LinkedList<T>());
}
You'd then have a mapping of priorities to queues. Your enqueue method would take an object and a priority (an int representing a priority) and would add the object to the queue specified by the priority. Your dequeue method would simply return the end of the highest priority queue with an element in it.
Make any sense?
Edit: I should have probably mentioned that I am extremely new to Java programming. I just started with the language about two weeks ago.
I have tried looking for an answer to this questions, but so far I haven't found one so that is why I am asking it here.
I writing java code for an Dungeons and Dragons Initiative Tracker and I am using a TreeMap for its ability to sort on entry. I am still very new to java, so I don't know everything that is out there.
My problem is that when I have two of the same keys, the tree merges the values such that one of the values no longer exists. I understand this can be desirable behavior but in my case I cannot have that happen. I was hoping there would be an elegant solution to fix this behavior. So far what I have is this:
TreeMap<Integer,Character> initiativeList = new TreeMap<Integer,Character>(Collections.reverseOrder());
Character [] cHolder = new Character[3];
out.println("Thank you for using the Initiative Tracker Project.");
cHolder[0] = new Character("Fred",2);
cHolder[1] = new Character("Sam",3,23);
cHolder[2] = new Character("John",2,23);
for(int i = 0; i < cHolder.length; ++i)
{
initiativeList.put(cHolder[i].getInitValue(), cHolder[i]);
}
out.println("Initiative List: " + initiativeList);
Character is a class that I have defined that keeps track of a player's character name and initiative values.
Currently the output is this:
Initiative List: {23=John, 3=Fred}
I considered using a TreeMap with some sort of subCollection but I would also run into a similar problem. What I really need to do is just find a way to disable the merge. Thank you guys for any help you can give me.
EDIT: In Dungeons and Dragons, a character rolls a 20 sided dice and then added their initiative mod to the result to get their total initiative. Sometimes two players can get the same values. I've thought about having the key formatted like this:
Key = InitiativeValue.InitiativeMod
So for Sam his key would be 23.3 and John's would be 23.2. I understand that I would need to change the key type to float instead of int.
However, even with that two players could have the same Initiative Mod and roll the same Initiative Value. In reality this happens more than you might think. So for example,
Say both Peter and Scott join the game. They both have an initiative modifier of 2, and they both roll a 10 on the 20 sided dice. That would make both of their Initiative values 12.
When I put them into the existing map, they both need to show up even though they have the same value.
Initiative List: {23=John, 12=Peter, 12=Scott, 3=Fred}
I hope that helps to clarify what I am needing.
If I understand you correctly, you have a bunch of characters and their initiatives, and want to "invert" this structure to key by initiative ID, with the value being all characters that have that initiative. This is perfectly captured by a MultiMap data structure, of which one implementation is the Guava TreeMultimap.
There's nothing magical about this. You could achieve something similar with a
TreeMap<Initiative,List<Character>>
This is not exactly how a Guava multimap is implemented, but it's the simplest data structure that could support what you need.
If I were doing this I would write my own class that wrapped the above TreeMap and provided an add(K key, V value) method that handled the duplicate detection and list management according to your specific requirements.
You say you are "...a TreeMap for its ability to sort on entry..." - but maybe you could just use a TreeSet instead. You'll need to implement a suitable compareTo method on your Character class, that performs the comparison that you want; and I strongly recommend that you implement hashCode and equals too.
Then, when you iterate through the TreeSet, you'll get the Character objects in the appropriate order. Note that Map classes are intended for lookup purposes, not for ordering.
Say I have an arrayList of strings like [a, b, c, d, ....]. Can anybody help me with a sample code that how can I come out with a result that contains all possible power subsets form this list which are including a particular string from that list(except the single and empty subset)?
For example: if I like to get all the power subsets including a from the example list then the output will be:
[a,b], [a,c], [a,d], [a,b,c], [a,b,d], [a,c,d] without the empty and single subset([a])
Similarly if I want for b then the output will be:
[b,a], [b,c], [b,d], [b,a,c], [b,a,d], [b,c,d] without the empty and single subset([b])
As all of the items in the example list are string then their might be a memory problem when the subsets will be too rich. Because I need to keep this subsets in memory for a single string at a time. So I also need help about what would be the optimized solution for this scenario?
I need the help in Java. As I am not that much good at Java please pardon me if I made any mistake!
Thanks!
If your initial arraylist of strings has 30 or fewer items, you can use the set method powerSet (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#powerSet%28java.util.Set%29 - Thanks, Jochen). The documentation claims the memory usage is only O(n) for the set-of-sets returned by that method. You can then iterate over that, with an if condition to only consider sets which contain "A" and are of size 2 or greater.
I recommend you try the above or a similar simple solution first and see if you run into memory problems.
If you do run into memory issues, you can try to optimize by minimizing the number of copies of the strings you hold in memory. For example, you can use lists of bytes, shorts, or ints (depending on how long your arraylist is) where each is an index into your arraylist of strings.
The ultimate way to reduce memory usage, however, would be to only hold one subset in memory at a time (if possible). I.e. generate (A, B), process it, discard it, then generate (A, C), process it, discard it, etc.
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.