I am trying to override comparable thusly:
public int compareTo(Object other) {
if(other.getlength() > this.getlength()){
return 1;
} else if (other.getlength() < this.getlength()){
return -1;
} else {
if (other.getVal() > this.getVal()){
return 1;
} else {
return -1;
}
}
}
What I want to happen, is for the list to be sorted on the length first, then if the length is the same, I want the those same lengthed items to be sorted (in place) on their values. But my implementation is not working correctly. Can anyone see what I am doing wrong?
My results are:
a b = 3
a b c = 1
a b c = 1
a b = 2
a b = 1
The results I want are:
a b c = 1
a b c = 1
a b = 3
a b = 2
a b = 1
Avoid logic where possible. Seriously - where feasible, use arithmetic to avoid if/else's. It tends to be more reliable. In this case:
public int compareTo(Object o) {
int ret = other.getlength() - this.getlength();
if ( ret == 0 ) {
ret = other.getVal() - this.getVal();
}
return ret;
}
it is not clear from your remarks that list would be already sorted or not. But you can handle that by sorting the list after comparing there lengths. But on thing which you are obviously doing wrong is object.getValue()...this doesnt makes sense you have to iterate through both lists and compare values to conclude if they are equal.
It wasnt obvious without the example sorry for above comments, It is not possible to have this result with your comparator. Your logic looks correct to me. But it would be good idea to incorporate w00t's comments also otherwise you will have a<'b as well as a>b and could cause a runtime error. Please check if the comparator is applied properly to you sorting function ( objects ).
Related
How can I create a method that would check whether or not a linked list contains any number larger than a parameter?
Let's say we have the linked list
[ 8 7 1 3 ]. This would return true and
[ 10 12 3 2] would return false.
Would this work?
public boolean f(int k) {
for (int=0; int<linkedList.size(); i++) {
if (linkedList.get(i)>k)
return false;
}
else
return true;
}
Also, I need to mention, this method would not change the list in any way and it should still work if the list contains null elements.
Thanks!
With Java 8
public boolean f(int k) {
return !linkedList.stream().anyMatch(i-> i> k );
}
clarification: I assume that you want to return false from the method in the case that even a single element is higher then the given k. Hence I use anyMatch since we only need to look for one element that is higher. There is no need to loop over the whole list.
No this will not work how you have it currently. You need to loop through the whole list before returning. The only time you should return prematurely is if you find a reason to return false in this context. So move your return true outside of your loop and then you'd be fine.
Also, try to give meaning to your method and class definitions. Saying obj.f(12) doesn't really say much, whereas obj.noElementGreaterThan(12) says a lot more.
for example:
public boolean noElementGreaterThan( int k ) {
for( int i = 0; i < linkedList.size(); i++ )
{
if( linkedList.get(i) > k )
return false;
}
return true;
}
The reason this works is because it will loop through the entire list of objects, comparing each to the value passed in (k). If the value is greater than k, then it will return false, meaning in this case that it does have an element greater than k.
using streams you could do like this:
public boolean f(int k) {
List<Integer> filtered = linkedList.stream().filter(i -> i > k).collect(Collectors.toList());
return !filtered.isEmpty();
}
I'm new to Java and still trying to wrap my head around recursion.The function below returns true at the very first intersection between the two sorted lists list x and list y.
public static boolean checkIntersection(List<Integer> x, List<Integer> y) {
int i = 0;
int j = 0;
while (i < x.size() && j < y.size()) {
if (x.get(i).equals(y.get(j))) {
return true;
} else if (x.get(i) < y.get(j)) {
i++;
} else {
j++;
}
}
return false;
}
Now I've been trying to implement it using recursion instead, and I know that there should be a base case which is an empty list in this case and then try to reduce the list by excluding one element at a time and feed it back to the same recursive function, but I can't work out how to check for intersection as I pass the rest of the list over and over.
public static boolean recursiveChecking(List<Integer> x,List<Integer> y) {
if(x.size() == 0){
return false;
}
else {
return recursiveChecking(x.subList(1, x.size()-1), y);
}
}
Any help would be highly appreciated. Thank you.
General approach to making something recursive is to think of two things:
When can I produce an answer trivially? - An answer to this question lets you code the base case. In your situation, you can produce the answer trivially when at least one of two lists is empty (the result would be false) or the initial elements of both non-empty lists are the same (the result would be true)
How do I reduce the problem when the answer is non-trivial? - An answer to this question lets you decide how to make your recursive call. In your case you could, for example, remove the initial element of one of the lists before making the recursive call*, or pass ListIterator<Integer> in place of List<Integer> for a non-destructive solution.
*Of course in this case you need to take care of either adding your numbers back after the call, or make a copy of two lists before starting the recursive chain.
As the lists are ordered, your recursion should remove the first element of the list with the smaller first value. Then you have to return true, if both lists start with the same number and false if any of the lists is empty. Otherwise you keep removing elements. This would look something like this (This code is untested):
public static boolean recursiveChecking(List<Integer> x,List<Integer> y) {
if(x.size() == 0 || y.size() == 0){
return false;
} else if (x.get(0).equals(y.get(0))) {
return true;
} else {
if (x.get(0) < y.get(0)) {
return recursiveChecking(x.subList(1, x.size()-1), y);
} else {
return recursiveChecking(x, y.subList(1, y.size()-1));
}
}
}
This question already has answers here:
Best way to format multiple 'or' conditions in an if statement
(8 answers)
Closed 1 year ago.
Basically, what I want to do is check two integers against a given value, therefore, classically what you would do is something like this:
//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);
//the actual thing in question
if(a == 0 || b == 0)
{
//Then do something
}
But is there a more concise format to do this? Possibly similar to this (which returns a bad operand type):
//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);
//the actual thing in question
if((a||b) == 0)
{
//Then do something
}
You can do the following in plain java
Arrays.asList(a, b, c, d).contains(x);
Unfortunately there is no such construct in Java.
It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:
public boolean oneOfEquals(int a, int b, int expected) {
return (a == expected) || (b == expected);
}
Then you could use it like this:
if(oneOfEquals(a, b, 0)) {
// ...
}
If you don't want to restrict yourselft to integers, you can make the above function generic:
public <T> boolean oneOfEquals(T a, T b, T expected) {
return a.equals(expected) || b.equals(expected);
}
Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.
As referenced from this answer:
In Java 8+, you might use a Stream and anyMatch. Something like
if (Stream.of(b, c, d).anyMatch(x -> x.equals(a))) {
// ... do something ...
}
Note that this has the chance of running slower than the other if checks, due to the overhead of wrapping these elements into a stream to begin with.
I think that a bit-wise OR:
if ((a | b) == 0) . . .
would work if you want to check specifically for 0. I'm not sure if this saves any execution time. More to the point, it makes for cryptic code, which will make the future maintainer of this code curse you (even if its yourself). I recommend sticking with the more-typing option.
Bah. I misread OP's original logic.
Another go...
If you want to test whether any one of many variables is equal to an expected value, a generic function might work:
public <T> boolean exists(T target, T... values) {
for (T value : values) {
if (target == null) {
if (value == null) {
return true;
}
} else if (target.equals(value)) {
return true;
}
}
return false;
}
This will work for any number of objects of one type. Primitives will be autoboxed so it will work with them as well. Your original code will be something like:
if (test(0, a, b)) {
// do something
}
(A better method name would be desperately needed to even consider whether this an improvement over what you have now. Even if the test expands to 3 or 4 variables, I question the need for this kind of thing.) Note that this also works with arrays:
int[] values = { . . . };
if (test(0, values)) { . . .
and it can be used to test whether an array (or any of a collection of variables) is null.
if(a == 0 || b == 0)
{
//Then do something
}
Why not keep it readable? What is not concise about this? On the other hand,
a = (int)(Math.random()*5);
involves an unnecessary cast. Why not just use Random and invoke nextInt()?
For this example, you can do
if (a * b == 0)
or for more variables
if (a * b * c * d == 0)
while more concise it may not be as clear. For larger values, you need to cast to a long to avoid an overflow.
You could put the integers in a set and see if it contains the given value. Using Guava:
if(newHashSet(a, b).contains(0)){
// do something
}
But two simple int comparisons are probably easier to understand in this case.
Here's a modification of #buc's answer that can take any number of any arguments:
public <T> boolean oneOfEquals(T expected, T... os) {
for (T o : os) {
if (expected.equals(o)) return true;
}
return false;
}
Even if you have used the bit-wise operation as Ted suggested, the expressions are not equal, since one requires at least one of the variables to be zero and the second requires both of them to be zero.
Regarding your question, there is no such shortcut in Java.
You can try this code:
public static boolean match (Object ref, Object... objects)
{
if (ref == null)
return false;
//
for (Object obj : objects)
if (obj.equals (ref))
return true;
//
return false;
} // match
So if you can check this way:
if (match (reference, "123", "124", "125"))
; // do something
In Java 8 we can achieve the same by using the below method:
private boolean methodName(int variant,int... args){
if(args.length > 0){ return Arrays.stream(args).anyMatch( x -> x == variant); }
return false;
}
The given method will return true if the variant will match any possible input(s). This is used for or condition.
In the same way, if you want to do &&(and) condition then you just need to used other Java 8 methods:
Note: These methods take Predicate as an argument.
anyMatch: return true the moment the first predicate returns true otherwise false.
allMatch: return true if all the predicates return true otherwise false.
noneMatch: return true if none of the predicates return true otherwise false.
Performance Note: This is good when you have enough amount of data to
check as it has some overhead but it works really well when you use
this for enough amount of data. normal way is good for just two
conditions.
There is no special syntax for that. You could make a function for that. Assuming at least Java 1.5:
public <T> boolean eitherOneEquals(T o1, T o2, T expectedValue) {
return o1.equals(expectedValue) || o2.equals(expectedValue);
}
if(eitherOneEquals(o1, o2, expectedValue)) {
// do something...
}
I get this error:
Exception in thread "Thread-3" java.lang.IllegalArgumentException: Comparison method violates its general contract!
When I try to run this comparator for my entity system in Java:
private Comparator<Entity> spriteSorter = new Comparator<Entity>() {
public int compare(Entity e0, Entity e1) {
if (e1.position.getX() <= e0.position.getX())
return +1;
if (e1.position.getY() >= e0.position.getY())
return -1;
return 0;
}
};
Here is the implementation:
private void sortAndRender(Bitmap b, Vec2 offset, ArrayList<Entity> l) {
Collections.sort(l, spriteSorter);
for (int i = 0; i < l.size(); i++) {
l.get(i).render(b, offset);
}
}
This issue only really began occurring when I was displaying large amounts of entities on the screen. What is going on here?
Your comparator is just plain wrong. Better would be something like
if (e1.position.getX() != e0.position.getX())
return Integer.compare(e1.position.getX(), e0.position.getX());
if (e1.position.getY() != e0.position.getY())
return Integer.compare(e1.position.getY(), e0.position.getY());
return 0;
While #Louis beat me to it for the most part, to elaborate and possibly clarify...
Your Compare method must be fairly "stable" and complete. Yours will return 0, "equals" for a lot of cases where the X and Y are different.
I'd rewrite it as
int result = Integer.compare(e1.position.getX(), e0.position.getX());
if (result == 0)
result = Integer.compare(e1.position.getY(), e0.position.getY());
... if you have more to compare, add more if (result == 0) blah blah here...
return result;
As for "stable", let's say you have two points, a = 4,2 and b = 2,4
When you compare a to b, you get 0
But when you compare b to a, you get 1.
This is "illegal" in a comparator. a.compareTo(b) should equal -b.compareTo(a)
Haha, issue was i was for some reason moving them up on the list based on x position, and down the list based on y position??!?!? This was a really silly mistake from me
I will explain the title better for starters. My problem is very similar to the common: find all permutations of an integer array problem.
I am trying to find, given a list of integers and a target number, if it is possible to select any combination of the numbers from the list, so that their sum matches the target.
It must be done using functional programming practices, so that means all loops and mutations are out, clever recursion only. Full disclosure: this is a homework assignment, and the method header is set as is by the professor. This is what I've got:
public static Integer sum(final List<Integer> values) {
if(values.isEmpty() || values == null) {
return 0;
}
else {
return values.get(0) + sum(values.subList(1, values.size()));
}
}
public static boolean groupExists(final List<Integer> numbers, final int target) {
if(numbers == null || numbers.isEmpty()) {
return false;
}
if(numbers.contains(target)) {
return true;
}
if(sum(numbers) == target) {
return true;
}
else {
groupExists(numbers.subList(1, numbers.size()), target);
return false;
}
}
The sum method is tested and working, the groupExists method is the one I'm working on. I think it's pretty close, if given a list[1,2,3,4], it will return true for targets such as 3 and 10, but false for 6, which confuses me because 1,2,3 are right in order and add to 6. Clearly something is missing. Also, The main problem I am looking at is that it is not testing all possible combinations, for example, the first and last numbers are not being added together as a possibility.
UPDATE:
After working for a bit based on Simon's answer, this is what I'm looking at:
public static boolean groupExists(final List<Integer> numbers, final int target) {
if(numbers == null || numbers.isEmpty()) {
return false;
}
if(numbers.isEmpty()) {
return false;
}
if(numbers.contains(target)) {
return true;
}
if(sum(numbers.subList(1, numbers.size())) == (target - numbers.get(0))) {
return true; }
else {
return groupExists(numbers.subList(1, numbers.size()), target);
}
}
For convenience, declare
static Integer head(final List<Integer> is) {
return is == null || is.isEmpty()? null : is.get(0);
}
static List<Integer> tail(final List<Integer> is) {
return is.size() < 2? null : is.subList(1, is.size());
}
Then your function is this:
static boolean groupExists(final List<Integer> is, final int target) {
return target == 0 || target > 0 && head(is) != null &&
(groupExists(tail(is), target) || groupExists(tail(is), target-head(is)));
}
There are no surprises, really, regular checking of base cases plus the final line, where the left and right operands search for a "group" that does or does not, respectively, include the head.
The way I have written it makes it obvious at first sight that these are all pure functions, but, since this is Java and not an FP language, this way of writing it is quite suboptimal. It would be better to cache any function calls that occur more than once into final local vars. That would still be by the book, of course.
Suppose you have n numbers a[0], a[1], ..., a[n-1], and you want to find out if some subset sums to N.
Suppose you have such a subset. Now, either a[0] is included, or it isn't. If it's included, then there must exist a subset of a[1], ..., a[n] which sums to N - a[0]. If it isn't, then there exists a subset of a[1], ..., a[n] which sums to N.
This leads you to a recursive solution.
Checking all combinations is factorial (there's a bit missing on your implementation).
Why not try a different (dynamic) approach: see the Hitchhikers Guide to Programming Contests, page 1 (Subset Sum).
Your main method will be something like:
boolean canSum(numbers, target) {
return computeVector(numbers)[target]
}
computeVector return the vector with all numbers that can be summed with the set of numbers.
The method computeVector is a bit trickier to do recursively, but you can do something like:
boolean[] computeVector(numbers, vector) {
if numbers is empty:
return vector
addNumber(numbers[0], vector)
return computeVector(tail(numbers), vector);
}
addNumber will take vector and 'fill it' with the new 'doable' numbers (see hitchhikers for an explanation). addNumber can also be a bit tricky, and I'll leave it for you. Basically you need to write the following loop in recrusive way:
for(j=M; j>=a[i]; j--)
m[j] |= m[j-a[i]];
The lists of all possible combinations can be reached by asking a very simple decision at each recursion. Does this combination contain the head of my list? Either it does or it doesn't, so there are 2 paths at each stage. If either path leads to a solution then we want to return true.
boolean combination(targetList, sourceList, target)
{
if ( sourceList.isEmpty() ) {
return sum(targetList) == target;
} else {
head = sourceList.pop();
without = combination(targetList, sourceList, target); // without head
targetList.push(head);
with = combination(targetList, sourceList, target); // with head
return with || without;
}
}