I keep getting a null pointer exception when adding to this queue, especially with the percolate up. I think something is wrong with my set up but I can't figure it out. When I try to add things I get an error and my IDE says its a null pointer exception and a problem in the compare methods, making me think that the if else statements in the compare method point to a null value. I can't figure out why they would?
public class GenericHeap<E> {
int size;
int capacity = 10;
public E[] heap;
Comparator mycomparator;
public GenericHeap(Comparator c) {
heap = (E[]) new Object[capacity];
mycomparator = c;
}
public void add(E e) {
if (size == 0) {
heap[size++] = e;
} else {
heap[size++] = e;
this.percolateup(this.size);
}
}
private void percolateup(int I) {
E temp;
while (I / 2 > 0) {
if (mycomparator.compare(heap[I / 2], heap[I]) == 1) {
temp = heap[I / 2];
heap[I / 2] = heap[I];
heap[I] = temp;
}
I = I / 2;
}
}
public int compare(String t, String t1) {
if (t.length()>t1.length()){
return 1;}
else if (t.length()<t1.length()){
return -1;}
return t.compareTo(t1);
}}
You're getting your index one step ahead, to where the heap[I] is still null.
Say you are adding your 2nd item.
#entry: size==1
you go down the else path, setting heap[1]=e, THEN incrementing size to 2. You then call percolateup(2). Notice what happens when I==2 here:
if (mycomparator.compare(heap[I / 2], heap[I]) == 1) {
you access heap[2], which of course has not yet been set. NPE !
Above is definitely why you are getting the NPE...now to speculate further. I don't really understand the logic of percolateup(), but I bet the issue is you are advancing the value of size too aggressively. Possibly instead of:
heap[size++] = e;
this.percolateup(this.size);
this might help
heap[size] = e;
this.percolateup(this.size);
size++
Separately, you have a style which lends to this confusion. In add() you reference member variable size directly (size++). Nothing wrong with that; but then you turn around and access this.size. Compiler is happy but this inconsistent style is not helping your comprehension. (I personally prefer to only use "this." when absolutely required, but that's personal taste.)
Related
I am working on a function, countH(), that is supposed to count the amount of times a given number appears in a linked list. For some reason, I cannot get this to work recursively. I have tried a number of different solutions but I guess I can't get something in the correct place. Sorry if I am asking the question poorly, I struggle to understand recursion formatting sometimes.
Here is the function:
public int count(int i) {
return countH(first, i);
}
private int countH(Node front, int i) { // TODO
int cter = 0;
if (front.next==null) {
return 0;
}
if(front.item == i)
cter++;
return countH(front, cter);
}
This is a late version of my code, I'm sure it was a bit better before I messed with it a bunch to try to get it to work
Thanks!
Every recursive implementation consists of two parts:
base case - that represents a simple edge-case for which the outcome is known in advance. For this task, the base case is a situation the given Node is null. Think about it this way: if a head-node is not initialed it will be null and that is the simplest edge-case that your method must be able to handle. And return value for the base case is 0.
recursive case - a part of a solution where recursive calls a made and where the main logic resides. In the recursive case, you need to check the value of a current node. If it matches the target value, then the result returned by the method will be 1 + countH(cur.next, i), otherwise it will be a result of the subsequent recursive call countH(cur.next, i).
Base case is always placed at the beginning of the method, followed by a recursive case.
And when you are writing a recursive part, one of the most important things that you have to keep in mind is which parameters change from one recursive call to another, and which remains the same. In this case, changes only a Node, the target value i remains the same.
public int count(int i) {
return countH(first, i);
}
private int countH(Node cur, int i) { // `front` replaced by `cur`
if (cur == null) { // not cur.next == null (it'll fail with exception if the head-node is null)
return 0;
}
// int cter = 0; // this intermediate variable isn't needed, it could be incremted by 1 at most during the method execution
// if(cur.item == i)
// cter++;
// return countH(cur, cter); // this line contains a mistake - variable `i` has to be passed as a parameter and `cter` must be added to the result returned by a recursive call
return cur.item == i ? 1 + countH(cur.next, i) : countH(cur.next, i);
}
Suggestion
Follow the comments in the code. I've left your original lines in place so that will be easier to compare solutions. Also, always try to come up will reasonable self-explanatory names for variables (as well as methods, classes, etc). For that reason, I renamed the parameter front to cur (short for current), because it's meant to represent any node, not first or any other particular node.
Side note
This statement is called a ternary operator or inline if statement
cur.item == i ? 1 + countH(cur.next, i) : countH(cur.next, i);
And it's just a shorter syntax for the code below:
if (cur.item == i) {
return 1 + countH(cur.next, i);
} else {
return countH(cur.next, i);
}
You could use either of these constructs in your code. The difference is only in syntax, both will get executed in precisely the same way.
In a linked list, you should have one element and from that you get the value and the next element. So your item could look like (I am omitting getters, setters and exception handling):
class Item {
Object value;
Item next;
}
Then your counter for a specific value could look like
int count(Object valueToCount, Item list) {
int result = 0;
if (valueToCount.equals(list.value)) {
result++; // count this value
}
if (value.next != null) {
result += count(valueToCount, value.next) // add the count from remainder of the list
}
return result;
}
public int count(int i) {
return countH(first, i);
}
private int countH(Node front, int i) { // TODO
if(front==null) {
return 0;
}
if (front.item == i) {
return 1 + countH(front.next, i);
} else {
return countH(front.next, i);
}
}
i have implemented logic like if i am giving a index that is not yet there then it will change the index to the reminder (Same like rotated i guess ).
import java.util.LinkedList;
public class MycircularlinkedList extends LinkedList {
private static int count = 0;
public Object get(int i) {
System.out.println("count==" + count);
if (i > count) {
i = i % count;
return super.get(i);
} else {
return super.get(i);
}
}
public boolean add(Object o) {
super.add(o);
count++;
return true;
}
public void add(int i, Object o) {
if (i > count)
i = i % count;
super.add(i, o);
count++;
}
}
A couple of points I can see:
count is static, this means you're only ever going to have one number here. Probably not what you want
count is redundant, use Collection#size()
The great thing about mod (%) is that it works for all numbers, you don't need to have the conditional. 2 % 12 == 14 % 12 == -10 % 12
If you're getting rid of the count property, you can get rid of your overridden #add(Object o) logic and just do return super.add(o);
I find some problem with your code: if count ==0 and if I use the method add(7,obj) ,then 7%0 will throw ArithmeticException.count should be declared to private since you may have two instances of your class.Also,you need to check
whether poll\offerLast method satisfies your needs,since you cant restrict
any client code to avoid using them.Finally,clone\readObject\writeObject
need to be overrried to include the count variable.
You're close.
(1) The term "circular linked list" is well-known to mean a list where the tail links back to the head (and vice versa if it's a doubly-linked list). Yours is more like a "circular buffer" stored in a linked list. We could call it LinkedListCircularBuffer or something.
(2) The class should be parameterized by the element type, thus
public class LinkedListCircularBuffer<E> extends LinkedList<E> {
#Override
public E get(int i) {
return super.get(i % size()); // simpler and faster without an "if"
}
}
(3) You can call size() instead of all the code to maintain another count.
(4) Your add(int i, Object o) method doesn't support the case where i == size(), but you can fix that by not overriding add() at all.
(5) Overridden methods need the #Override annotation.
(6) It's good style to always put braces around each "then" and "else" clause. Code like
if (i > count)
i = i % count;
is fragile, e.g. adding a println() statement into that "then" clause will break it.
Often in java I have to get a value of a property of an object which is deep in this object. For example, if I'm sure that all my sub-objects are not null, I can do that :
public function getDeepValue(A a) {
String value = a.getB().getC().getListeD().get(0).getE().getValue();
return value;
}
But in case of sub objects of the parent can be null, I have to test every object.
To do that, I see 2/3 solutions :
First, step by step :
public function getDeepValue(A a) {
if(a == null){
return null;
}
B b = a.getB();
if(b == null) {
return null;
}
C c = b.getC();
if(c == null){
return null;
}
List<D> ds = c.getListeD();
if(ds == null || ds.size() == 0){
return null;
}
D d = ds.get(0);
if(d == null) {
return null;
}
E e = d.getE()
if(e == null){
return null;
}
return e.getValue();
}
Second, test all in one if block, soooo dirty :
public function getDeepValue(A a) {
if(a != null && a.getB() != null && a.getB().getC() != null && a.getB().getC().getListeD() != null && a.getB().getC().getListeD().size() > 0 && a.getB().getC().getListeD().get(0) != null && a.getB().getC().getListeD().get(0).getE() != null){
return a.getB().getC().getListeD().get(0).getE().getValue();
}
return null;
}
Third solution, using a try catch block :
public function getDeepValue(A a) {
try {
return a.getB().getC().getListeD().get(0).getE().getValue();
} catch(NullPointerException e) {
return null;
} catch(IndexOutOfBoundsException e) {
return null;
}
}
Solution 1 seems not too bad but needs a lot of code. It is generally the solution I use.
Solution 2 is for me really dirty...
In paper, I realy like solution 3, but is it a good solution in term of performances ?
Is there any others acceptables solutions ?
Thanks for help, I hope my english is not too bad..
Regards
Solution #3 looks simple, but it can potentially hide a whole host of problems. It might be an adequate solution if you have full access to all of the classes in the chain and you know what's going on in each method and you can guarantee those methods won't cause problems with your try/catch and you're never going to change them... that's a lot of conditions to make it a worthwhile solution, but I can conceive that it's possibly a useful sufficient one.
Solution #2 looks horrid to me, especially if one or more of the get methods is a bottleneck (such as a slow database query or using a blocking network connection). The earlier in the chain such a potential bottleneck, the worse it would potentially be, as you're calling it over and over again. This of course depends on the implementation of the methods in question (even if one of them is slow, the result could be cached, for example), but you shouldn't need to know that in your client code. Even with efficient or trivial implementations, you've still got the overhead of repeated method calls you oughtn't need.
Solution #1 is the best of the three, but it's likely not the best possible. This solution takes more lines of code than the other two, but it doesn't repeat itself and it isn't going to be tripped up by the implementations of the other methods. (Note: If you do not have access to the classes in the chain for refactoring, I would use this solution.)
A better solution than #1 would be to refactor the classes so that the client code doesn't need to know about this chain at all. Something along these lines:
class Client {
public Mumble getDeepValue(A a) { return a == null ? null : a.getDeepValue(); }
}
class A {
private B b;
public Mumble getDeepValue() { return b == null ? null : b.getDeepValue(); }
}
class B {
private C c;
public Mumble getDeepValue() { return c == null ? null : c.getDeepValue(); }
}
class C {
private List<D> ds;
public Mumble getDeepValue() {
D d = ds == null || ds.size() == 0 ? null : ds.get(0);
return d == null ? null : d.getDeepValue();
}
}
class D {
private E e;
public Mumble getDeepValue() { return e == null ? null : e.getMumble(); }
}
class E {
private Mumble m;
public Mumble getMumble() { return m; }
}
As you can see, the longest chain any of these classes has is to access the public members of an element of a collection that is a private member of the class. (Essentially ds.get(0).getDeepValue()) The client code doesn't know how deep the rabbit hole goes, only that A exposes a method which returns a Mumble. Client doesn't even need to know that the classes B, C, D, E, or List exist anywhere!
Additionally, if I were designing this system from the ground up, I would take a good long look at whether it could be restructured such that the actual Mumble object wasn't so deep. If I could reasonably get away with storing the Mumble within A or B, I'd recommend doing it. Depending on the application, that may not be possible however.
in terms of performance solution 3 is the best one. In addition It is neat and easy to understand , For example looking at a loop example:
int[] b = somevalue;
for(int i=0;i<b.length;i++){
//do something
}
in this case for every iteration we execute the condition. However, there is another approach for it which uses try and catch
int[] b = somevalue;
try{
for(int i=0;;i++){
//do something
}
}catch(IndexOutOfBoundException e){
// do something
}
on the second solution,the loop keeps going until we reach the end of the loop which then it throws IndexOutOfBoundException as soon as we reach the end of the array. meaning we don't check for the condition no more. thus faster.
I have two functions here for size() but they both look like crap. The first one uses an overloaded function and the second, well, see for yourself. What I want to do is create a slick version of the second attempt but I'm low on ideas.
P.S: Telling me to use Java's util is kind of pointless. I want to make it pretty, not hide it.
So my function is called from a BST object and looks like this:
public int size() {
return size(root);
}
private int size(Node x) {
if (x == null) {
return 0;
} else {
return 1 + size(x.left) + size(x.right);
}
}
Now I don't want to overload the function so I rewrote it as such:
public int size() {
Node y = root;
if (y == null) {
return 0;
} else {
root = y.left;
int left = size();
root = y.right;
int right = size();
root = y;
return 1 + left + right;
}
}
All suggestions are welcome!
If it is something that is called regularly, perhaps you would be better caching the size in your Node class, and updating when you insert or delete, then it simply becomes
public int size() {
return root == null ? 0 : root.size();
}
IMHO Your first approach is good enough. Why? Because you have a perfect public interface(public size()) that governs how the size of the BST is calculated(using private size()) hiding the internal implementation. I don't see any harm in overloading as long as it lead to a better design decision.
Edit: This is my understanding of how 1st one is better than the 2nd approach. I welcome any feedbacks. Thanks!!
With Java, I have a class, known as TestClass, which has a member named Name, which is a string. I also have an ArrayList of this type, which is already sorted alphabetically by Name. What I want to do is find the best index in which to put a new instance of TestClass. The best approach I could come up with so far is this:
public static int findBestIndex(char entry, ArrayList<TestClass> list){
int desiredIndex = -1;
int oldPivot = list.size();
int pivot = list.size()/2;
do
{
char test = list.get(pivot).Name.charAt(0);
if (test == entry)
{
desiredIndex = pivot;
}
else if (Math.abs(oldPivot - pivot) <= 1)
{
if (test < entry)
{
desiredIndex = pivot + 1;
}
else
{
desiredIndex = pivot - 1;
}
}
else if (test < entry)
{
int tempPiv = pivot;
pivot = oldPivot - (oldPivot - pivot)/2;
oldPivot = tempPiv;
}
else
{
int tempPiv = pivot;
pivot = pivot - (oldPivot - pivot)/2;
oldPivot = tempPiv;
}
} while (desiredIndex < 0);
return desiredIndex;
}
Essentially, Break the array in half, check to see if your value goes before, after, or at that point. If it's after, check the first half of the array. Other wise, check the second half. Then, repeat. I understand that this method only tests by the first character, but that's easily fixed, and not relevant to my main problem. For some scenarios, this approach works well enough. For most, it works horribly. I assume that it isn't finding the new pivot point properly, and if that's the case, how would I fix it?
Edit: For clarification, I'm using this for an inventory system, so I'm not sure a LinkedList would be appropriate. I'm using an ArrayList because they are more familiar to me, and thus would be easier to translate into another language, if needed (which is likely, at the moment, might be moving over to C#). I'm trying to avoid things like Comparable for that reason, as I'd have to completely re-write if C# lacks it.
Edit part Duex: Figured out what I was doing wrong. Instead of using the previous pivot point, I should have been setting and changing the boundaries of the area I was checking, and creating the new pivot based on that.
It might not be a good idea to use a SortedSet (e.g. a TreeSet) for this, because Set‘s don't allow duplicate elements. If you have duplicate elements (i.e. TestClass instances with the same name), then a List should be used. To insert an element into an already sorted list is as simple as this:
void insert(List<TestClass> list, TestClass element) {
int index = Collections.binarySearch(list, element, Comparator.comparing(TestClass::getName));
if (index < 0) {
index = -index - 1;
}
list.add(index, element);
}
This code requires Java 8 or later, but can be rewritten to work in older Java versions as well.
As already pointed out, there is no reason to implement this by yourself, simple code example:
class FooBar implements Comparable<FooBar> {
String name;
#Override
public int compareTo(FooBar other) {
return name.compareTo(other.name);
}
}
TreeSet<FooBar> foobarSet = new TreeSet<>();
FooBar f1;
foobarSet.add(new FooBar("2"));
foobarSet.add(f1 = new FooBar("1"));
int index = foobarSet.headSet(f1).size();
(Based on How to find the index of an element in a TreeSet?)
I think the problem is in this bit of the code:
else if (test < entry)
{
int tempPiv = pivot;
pivot = oldPivot - (oldPivot - pivot)/2;
oldPivot = tempPiv;
}
else
{
int tempPiv = pivot;
pivot = pivot - (oldPivot - pivot)/2;
oldPivot = tempPiv;
}
You are peforming the same actions wether test < entry or wether test > entry. This will lead to a linear search when the item you are searching for is at the start of the array.
I prefer to use (low and high) like
high = list.size();
low = 0;
do {
pivot = (high + low) / 2;
if (test < entry) {
low = pivot;
} else if (test > entry) {
high = pivot
} else {
....
}
} while ...;
You should use something like a PriorityQueue that already has a sense of order. Inserting into a collection with a sense of order will automatically place the element in the correct place with minimal time(usually log(n) or less).
If you want to do arbitrary inserts without this, then I would suggest using a LinkedList that won't have to be resorted or completely copied over to insert a single item like the ArrayList you currently have. While finding the correct insert location for a LinkedList will take up to O(n) time, in practice it will still be faster than using a log(n) search for the correct location in an ArrayList, but then needing to copy or sort it afterwards.
Also the code for finding the insert location in a linked list is much simpler.
if (next != null && next.compareTo(insertElement) > 0){
// You have the right location
}
There are other data structures used could use instead of list like a tree, priority queue etc.
Make a list implementation of your own, and in your add method have these lines:
wrappedList.add(object);
Collections.sort(wrappedList);