Skip to content

Instantly share code, notes, and snippets.

@icasdri
Last active September 28, 2016 02:55
Show Gist options
  • Save icasdri/36f18e9db55e643dd1c4fa739e9e9bfc to your computer and use it in GitHub Desktop.
Save icasdri/36f18e9db55e643dd1c4fa739e9e9bfc to your computer and use it in GitHub Desktop.
Java one-liner for taking mean of two ints without overflow
import java.util.Random;
public class GeneralAverage {
public static int mean(int a, int b) {
return ((a<0) ^ (b<0)) ? (a + b) / 2 : (a%2 == 0 || b%2 == 0 ? a/2 + b/2 : a/2 + b/2 + ((a < 0) ? -1 : 1));
}
public static void main(String[] args) {
Random rand = new Random();
int a = Integer.MAX_VALUE;
int b = Integer.MAX_VALUE - 1;
for (int i = 0; i < 10000; i++) {
int mean = mean(a, b);
int actual = (int) (((long) a + (long) b) / 2);
if (mean != actual) {
System.out.println("(" + i + ") " + a + " " + b + " : " + mean + " " + actual);
System.out.println("DOESN'T WORK!");
break;
}
a = rand.nextInt(Integer.MAX_VALUE);
b = rand.nextInt(Integer.MAX_VALUE);
}
a = Integer.MIN_VALUE;
b = Integer.MAX_VALUE - 1;
for (int i = 0; i < 10000; i++) {
int mean = mean(a, b);
int actual = (int) (((long) a + (long) b) / 2);
if (mean != actual) {
System.out.println("(" + i + ") " + a + " " + b + " : " + mean + " " + actual);
System.out.println("DOESN'T WORK!");
break;
}
a = - rand.nextInt(Integer.MAX_VALUE - 1);
b = rand.nextInt(Integer.MAX_VALUE);
}
a = Integer.MIN_VALUE;
b = Integer.MIN_VALUE + 1;
for (int i = 0; i < 10000; i++) {
int mean = mean(a, b);
int actual = (int) (((long) a + (long) b) / 2);
if (mean != actual) {
System.out.println("(" + i + ") " + a + " " + b + " : " + mean + " " + actual);
System.out.println("DOESN'T WORK!");
break;
}
a = - rand.nextInt(Integer.MAX_VALUE - 1);
b = - rand.nextInt(Integer.MAX_VALUE - 1);
}
}
}
import java.util.Random;
/*
* Only works for positive ints.
*/
public class PositiveAverage {
public static int mean(int a, int b) {
return (a % 2 == 0 || b % 2 == 0) ? (a / 2 + b / 2) : (a / 2 + b / 2 + 1);
}
public static void main(String[] args) {
Random rand = new Random();
int a = Integer.MAX_VALUE;
int b = Integer.MAX_VALUE - 1;
for (int i = 0; i < 10000; i++) {
int mean = mean(a, b);
int actual = (int) (((long) a + (long) b) / 2);
if (mean != actual) {
System.out.println("(" + i + ") " + a + " " + b + " : " + mean + " " + actual);
System.out.println("DOESN'T WORK!");
break;
}
a = rand.nextInt(Integer.MAX_VALUE);
b = rand.nextInt(Integer.MAX_VALUE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment