Fastest way to sort 3 values in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have to put 3 values in correct order and print them out to the console.
A solution is to put them into an array and then sort them, but I remember (from school times) that there was faster to compare and order them, however I can't find the correct comparison order.
Could you please show me how to compare 3 values with the minimum number of if statements?

bubble sort would have only 3 compare ops, and 6 assignments at worst case (it will be very similar if not identical to the behavior of insertion sort in this case):
if (a > b)
swap(a,b)
if (b > c)
swap(b,c)
if (a > b)
swap(a,b)
print a,b,c
It cannot be done in less then 3 compares because there are n!=6 possible permutations for the array, and ceil(log_2(n!)) = 3

There is no point in optimizing this. It will not gain any speed. O(n!) for 3 is still only 3*2 = 6 operations. Even O(2^n) is going to be 8. You could really do whatever it takes to sort these 3 values and not see a difference in performance.
edit
int a, b, c, min, max, med;//assume values are there for a b c
if( a > b ){
if( a > c ){
max = a;
if( b > c ){
med = b;
min = c;
}else{
med = c;
min = b;
}
}else{
med = a;
max = c;
min = b;
}
}else{
if( b > c ){
max = b;
if( a > c ){
med = a;
min = c;
}else{
med = c;
min = a;
}
}else{
med = b;
max = c;
min = a;
}
}

As far as i know, Java uses the Quicksort algorithm for sorting - an already optimized approach. No speed to harvest here!

Related

I can't truncate a number to be compared [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need to compare numbers of decimal type, where the comparison will be made up to decimal number three but with the code that I have it cannot do it.
I have tried round as well but it is not achieved either
The code is the following:
the number compare=
-3.1756 ; -3.175 this is true
3.174 ; 3.175 this is false
public static boolean areEqualByThreeDecimalPlaces(double one, double two)
int a = (int) Math.floor(one*1000);
int b = (int) Math.floor((two*1000));
if(a == b){
System.out.println(true);
System.out.println(a + "---" + b);
return true;
}
else
System.out.println(false);
System.out.println(a + "---" + b);
return false;
Since you are using floor(), you are not just truncating after the decimal point. You are moving to the next smaller integer. Since you are dealing with negative numbers here, floor(-3.1756) unexpectedly becomes -3176 (not -3175!). Thus the two numbers do not compare equal.
So to do truncation you have to use ceil() for negative numbers:
int a = (int) (one < 0 ? Math.ceil(one * 1000) : Math.floor(one*1000));
int b = (int) (two < 0 ? Math.ceil(two * 1000) : Math.floor(two*1000));
Another option might be to use rounding with a function that respects RoundingMode.DOWN.

Assign a value to Integer between two constant values? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Lets say I have 3 Integers:
int a, b, c;
b = 25;
c = 10;
Now I want a to be either 25 or 10 but by random not something like:
a = b;
I want something like in if statement:
a = b || c;
How can I achieve it?
if(Math.random() < 0.5)
a = 25;
else
a = 10;
Math.random() returns a random number from 0 to 1, so if you want a 50% chance of something being true, just check if it's less than (or greater than) 0.5.
one way is to do by taking the millis of time like:
if(System.currentTimeMillis() % 2 == 0){
a=b;
} else{
a=c;
}
#immibis' answer is the simplest way to achieve this.
For testability, I would strongly advise that you use an explicit Random instance, rather than using Math.random():
static int pickRandomValue(Random r, int b, int c) {
return r.nextInt(2) == 1 ? b : c;
}
This allows you to inject a mock Random instance, allowing you to fix the behaviour when you need to test specific behaviour. Non-deterministic tests are a pain, and should be avoided.
Try the below code:
Random rand = new Random();
int myRandom = rand.nextInt(2); // will be 0 or 1
if (myRandom == 0) {
a=b;
} else {
a=c;
}

Program is supposed to determine if the input number is prime or not [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
//I am supposed to do it with loops and decision statements, but it's not working. Help!
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
//Declare variables
Scanner abc;
abc = new Scanner (System.in);
int input;
int divide = 2;
int count=0;
//Ask for input
System.out.println("Please enter an integer to determine if it is prime");
input = abc.nextInt();
//Do math
for (int x=1; x < input; x++) {
if ((input%divide) == 0)
count += 1;
divide = divide + 1;
}
if (count == 0)
System.out.println("It is a prime number");
else
System.out.println("It is not a prime number");
}
}
In your for loop, for the last iteration, x = input - 1, but that means divide = input (since divide was one greater in the beginning, and you increment both once per iteration of the loop), so count will actually be equal to 1 if the number is prime, not 0.
You're counting the number of divisors; all you need to do is determine if there is at least one divisor. Here's a better algorithm:
function isPrime(n)
if n is even
return n == 2
d := 3
while d * d <= n
if n % d == 0
return False
d := d + 2
return True
I discuss this algorithm, among others in the essay Programming with Prime Numbers at my blog, which includes implementations in Java.
It looks like count is supposed to count the number of factors of input not counting 1 and input. For readability, I'd recommend using a name like numOfFactors instead of count.
Given that, now look at your loop and answer these questions. I'm not going to give you the answer. (Yes, you can get the answer by looking at others' comments, but I think you will learn more by answering these questions anyway.)
(1) What are x and divide the first time you go through the loop, at the beginning of the loop?
(2) If you look at what happens to x and divide, there's a simple relationship between x and divide at the beginning of each time through the loop. What is it?
(3) What is x the last time you go through the loop?
(4) Based on the answers to #2 and #3, what is divide at the beginning of the last time through the loop? What will input%divide be equal to?
That's why it isn't working. Figure that out first. Then we can talk about how to can make it work more efficiently.
MORE: OK, I'll say one more thing. If all you care about is whether count is zero or not, you can quit your loop as soon as you find a factor. Like this:
if ((input%divide) == 0)
{
count += 1;
break;
}
(And if you do it that way, then instead of count you should use a boolean foundAFactor because all it says is whether you found a factor, not how many there are.)
But if you really want to know the exact number of factors, don't do that.
Hello do it like this:
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("is a prime");
else
System.out.println("is not a prime");
break;
}
}
for (int x=2; x < input; x++) (change x=1 to x=2)
otherwise you end up trying to divide 5 by 5 to test if 5 is prime

Recursive definition solution

im studying for my final exam from the text book. I need an answer for this question since i couldn't solve it.
1)Write a recursive definition of the function multiply(int a, int b) that takes two integers and return the result of their multiplication.
I answered:
Multiply(a, b) :
0 - if a or b is equal to zero. (I got -1 here. Reason written: only 1)
a * b - (I didn't know what to write here)
2)
Write a recursive method that takes a linked list of integers and returns the sum of it's elements.
My solution was:
int sumList(Node<Integer> list) {
int temp = list.getInfo();
if(temp == null) {
return 0;
} else {
return temp + sumList(temp.getNext);
}
}
I fixed it, i think:
public int sumList(Node<Integer> list) {
Node<Integer> temp = list;
if(temp == null) {
return 0;
} else {
return temp.getInfo() + sumList(temp.getNext());
}
}
Is the solution for question 2 right?
Since this is for exam preparation, I don't want to give you the code for doing this. Instead I will give you some ideas.
For the question no 1. Since multiplication is repeated summation, you can use that as the base for recursion here.
If you want to find 3 * 4, use recursion to calculate and return 4 + 4 + 4.
In other words, you can see a pattern emerge below.
4 * 3 = 4 + (4 * 2)
4 * 3 = 4 + 4 + (4 * 1)
To get a working recursive solution you need a base case, for example a == 0, and then work yourself down towards the base case by recursively calling yourself.
The solution for question 1 could be something along the lines of this, that decreases the a argument until it reaches 0:
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return b + multiply(a - 1, b);
}
For example, multiply(2, 5) would become 5 + multiply(1, 5) -> 5 + 5 + multiply(0, 5) -> 5 + 5 + 0.
Note that this particular solution doesn't work for negative numbers, but you get the idea. You should be able to easily add support for that yourself.
A) well, you really need to reread that chapter on recursion.
The mathematical principle is this:
http://en.wikipedia.org/wiki/Mathematical_induction
and the Wikipedia article will step you through a much more complicated task.
B) No, it won't compile at all. There are multiple syntax errors.
Try using a Java compiler for excersising your programming skills.

compareTo with primitives -> Integer / int

Is it better to write
int primitive1 = 3, primitive2 = 4;
Integer a = new Integer(primitive1);
Integer b = new Integer(primitive2);
int compare = a.compareTo(b);
or
int primitive1 = 3, primitive2 = 4;
int compare = (primitive1 > primitive2) ? 1 : 0;
if(compare == 0){
compare = (primitive1 == primitive2) ? 0 : -1;
}
I think the second one is better, should be faster and more memory optimized. But aren't they equal?
For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.
I would do either
int cmp = a > b ? +1 : a < b ? -1 : 0;
or a longer version
int cmp;
if (a > b)
cmp = +1;
else if (a < b)
cmp = -1;
else
cmp = 0;
or
int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7
It's best not to create an object if you don't need to.
Performance wise, the first is best.
If you know for sure that you won't get an overflow you can use
int cmp = a - b; // if you know there wont be an overflow.
you won't get faster than this.
Use Integer.compare(int, int). And don'try to micro-optimize your code unless you can prove that you have a performance issue.
May I propose a third
((Integer) a).compareTo(b)
Wrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :
Integer a = 3;
About comparision there is Math.signum(double d).
compare= (int) Math.signum(a-b);
They're already ints. Why not just use subtraction?
compare = a - b;
Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.
For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:
Integer.valueOf(x).compareTo(y);
If you are using java 8, you can create Comparator by this method:
Comparator.comparingInt(i -> i);
if you would like to compare with reversed order:
Comparator.comparingInt(i -> -i);
If you need just logical value (as it almost always is), the following one-liner will help you:
boolean ifIntsEqual = !((Math.max(a,b) - Math.min(a, b)) > 0);
And it works even in Java 1.5+, maybe even in 1.1 (i don't have one). Please tell us, if you can test it in 1.5-.
This one will do too:
boolean ifIntsEqual = !((Math.abs(a-b)) > 0);

Categories