How to encode integers in BDDs - java

I'm implementing in Java.
At the moment I'm trying to use BDDs (Binary Decision Diagramms) in order to store relations in a datastructure.
E.g. R={(3,2),(2,0)} and the corresponding BDD:
For this reason I was looking for libraries, which have BDD functionalities in order to help me.
I found two possibilities: JavaBDD and JDD.
But in both cases, I do not understand how I can encode a simple integer to a BDD, because how or when do I give the value of my integer? Or what does it mean, if the BDD is represented by an integer?
In both cases, there are methods like:
int variable = createBDD(); //(JBDD)
or
BDD bdd = new BDD(1000,1000);
int v1 = bdd.createVar(); // (JDD)
How can I simply create a BDD like my example?
Thank you very much!!

So I found a solution for this, but it is not very satisfying, as I cannot get the tuple back from the BDD without knowing, how many boolean variables I used for representing the integer in binary. So I have to define in the beginning for example: All my integers are smaller than 64, so they are represented by 6 binary variables. If I want to add a bigger integer than 64 afterwards I have a problem, but I don't want to use the maximum size of integers from the beginning, in order to save time, because I wanted to use BDDs in order to save running time, else there are a lot of easier things than BDDs for just representing tuples.
I use JDD as my BDD library, so in JDD BDDs are represented as integers.
So this is how I will get a BDD out of an integer tuple:
In the beginning you have to create the BDD-variables, the maxVariableCount is the maximum number of binary variables, which represent the integer (explained in the beginning of this answer):
variablesDefinition is just the number of integer variables I want to represent later in the BDD. So in the example of my question variablesDefinition would be 2, because each tuple has two intereger variables.
The array variables is a two dimension array, which has all BDD variables inside. So for example if our tuple has 2 elements, the BDD variables which represent the first integer variable can be found in variables[0].
BDD bddManager = new BDD(1000,100);
private int variablesDefinition;
private int[][] variables;
private void createVariables(int maxVariableCount) {
variables = new int[variablesDefinition][maxVariableCount];
for(int i = 0; i < variables.length; i++) {
for(int j = 0; j < maxVariableCount; j++) {
variables[i][j] = bddManager.createVar();
}
}
}
Then we can create a bdd from a given integer tuple.
private int bddFromTuple(int[] tuple) {
int result;
result = bddManager.ref(intAsBDD(tuple[0],variables[0]));
for(int i = 1; i < tuple.length; i++) {
result = bddManager.ref(bddManager.and(result, intAsBDD(tuple[i], variables[i])));
}
return result;
}
private int intAsBDD(int intToConvert, int[] variables) {
return bddFromBinaryArray(intAsBinary(intToConvert, variables.length), variables);
}
private int[] intAsBinary(int intToConvert, int bitCount) {
String binaryString = Integer.toBinaryString(intToConvert);
int[] returnedArray = new int[bitCount];
for (int i = bitCount - binaryString.length(); i < returnedArray.length; i++) {
returnedArray[i] = binaryString.charAt(i - bitCount + binaryString.length()) - DELTAConvertASCIIToInt;
}
return returnedArray;
}
static int DELTAConvertASCIIToInt = 48;
private int bddFromBinaryArray(int[] intAsBinary, int[] variables) {
int f;
int[] tmp = new int[intAsBinary.length];
for(int i = 0; i < intAsBinary.length; i++) {
if(intAsBinary[i] == 0) {
if (i == 0) {
tmp[i] = bddManager.ref(bddManager.not(variables[i]));
}
else {
tmp[i] = bddManager.ref(bddManager.and(tmp[i-1], bddManager.not(variables[i])));
bddManager.deref(tmp[i - 1]);
}
}
else {
if (i == 0) {
tmp[i] = bddManager.ref(variables[i]);
}
else {
tmp[i] = bddManager.ref(bddManager.and(tmp[i-1], variables[i]));
bddManager.deref(tmp[i - 1]);
}
}
}
f = tmp[tmp.length-1];
return f;
}
My first intention was to add these tuples to the BDD and afterwards being able to execute arithmetic functions in the integers in the BDD, but this is only possible after transforming the BDD back to tuples and executing the function and returning it to the BDD, which destroys all reasons why I wanted to use BDDs.

Simply encode integer tuples using a k-subset encoding algorithm like lex, colex, revdoor, coolex etc.
Lex encodes a k-tuple out of n integers in lexicographic order, e.g. n=4, k=2 yields the (1 based) encoding
tuple rank
(0,1) -> 1
(0,2) -> 2
(0,3) -> 3
(1,2) -> 4
(1,3) -> 5
(2,3) -> 6
You need a rank(tuple) and unrank(rank) routine to transform tuple to rank and back.

Related

Difference between two Sorted Arrays

Im trying to create a method that it´s able to print the difference between two sets of numbers
In this case, I want to make the difference (h1 - h2) or in other words, print all the elements of the array h1 that are not also in h2.
so far this is what i have come up with, and it works only if the numbers of the first set h1 are smaller than the ones of the second set h2, but I want to make it work under any given set.
I would really apreciate any idea that you might have, Thanks ¡
private void metodoDifference(int[] h1, int[] h2, int m, int n) {
int i = 0, j = 0;
ArrayList<Integer> arrayDifference = new ArrayList<>();
while (i < m && j < n) {
if(h1[i] < h2[j]) {
arrayDifference .add(h1[j++]);
i++;}
else if (h2[j] < h1[i]){
arrayDifference .add(h1[j++]);
}
else {
i++;
j++;
}
}
differenceText.setText(arrayDifference .toString());
}
You don't appear to need m or n. I would use ArrayList.removeAll(Collection). Then, assuming you are using Java 8+, you can collect and box your int[](s) in one step. Like,
private void metodoDifference(int[] h1, int[] h2) {
List<Integer> arrayDifference = Arrays.stream(h1).boxed().collect(Collectors.toList());
arrayDifference.removeAll(Arrays.stream(h2).boxed().collect(Collectors.toList()));
differenceText.setText(arrayDifference.toString());
}

Comparing Two Arrays & Get the Percent that Match - Java

Background: Very new at Java, have little understanding. Would prefer a "point in the right direction" with explanation, if possible, than a copy/paste answer without explanation. If I want to stop being a novice, I need to learn! :)
Anyway, my goal is, as simply as possible, to be given 2 arrays numberList and winningNumbers, compare them, and return the percentage that numberList matches winningNumbers. Both array lengths will always be 10.
I have no idea where to start. I have been googling and going at this for 2 hours. My idea is to write a for loop that compares each individually integer in a string to one in the other, but I am not sure how to do that, or if there is a simpler method. I have little knowledge of arrays, and the more I google the more confused I become.
So far the only thing I have is
public double getPercentThatMatch(int[] winningNumbers) {}
numberList is preset.
one way you could approach it is to:
1) convert both lists to sets.
2) subtract one from the other. ie if 4 are the same, the resulting set will have the 6 values not the same
3) 10 - (size of resulting set) * 100 = %
Here's a runnable example of how you would compare the two arrays of ints to get a percent match.
public class LotteryTicket {
int[] numberList;
LotteryTicket(int... numbers) {
numberList = numbers;
}
public int getPercentThatMatch(int[] winningNumbers) {
Arrays.sort(numberList);
Arrays.sort(winningNumbers);
int i = 0, n = 0, match = 0;
while (i < numberList.length && n < winningNumbers.length) {
if (numberList[i] < winningNumbers[n]) {
i++;
} else if (numberList[i] > winningNumbers[n]) {
n++;
} else {
match++;
i++;
n++;
}
}
return match * 100 / winningNumbers.length;
}
public static void main(String[] args)
{
int[] winningNumbers = { 12, 10, 4, 3, 2, 5, 6, 7, 9, 1 };
LotteryTicket ticket = new LotteryTicket(5, 2, 6, 7, 8, 4, 3, 1, 9, 0);
int percentMatching = ticket.getPercentThatMatch(winningNumbers);
System.out.println(percentMatching + "%");
}
}
Output:
80%
Since you wanted to be pointed in the right direction, rather than havving proper code, and assuming you want to use arrays to solve the problem, try to put something like this in your method:
(loop through arrayA){
(loop through arrayB){
if (current arrayA number is equal to current arrayB number){
then increase match counter by one, since this exists.
also break out of current arrayB loop. (Check next arrayA now.)
}
}
}
When done: return 100*matchCount/totalCount, as a double
So for every index in one array, you check against every other index of the other array. Increase a counter each time there's a match, and you'll be able to get a ratio of matches. If you use an integer as a counter, remember that division with integers acts funky, so you'd need to throw to a double:
double aDoubleNumber = (double) intNumber / anotherIntNumber
The problem would be easier if we consider them set. Let you have two set -
Set<Integer> s1 = //a HashSet of Integer;
Set<Integer> s2 = //a HashSet of Integer;
Now make a copy of s1 for example s11 and do the following thing -
s1.retainAll(s2);
Now s1 contains only element of both sets - that is the intersection.
After that you can easily calculate the percentage
Edit: You can convert the array to a set easily by using the following code snippet (I am assuming you have array of int) -
Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(somePrimiteiveIntArray));
I think this trick will works for other primitive type also.
Hope this will help.
Thanks a lot.
I am going to attempt to beat a dead horse and explain the easiest (conceptual) way to approach this problem I will include some code but leave a lot up to interpretation.
You have two arrays so I would change the overall method to something like this:
public double getPercentage(int[] arrayA, int[] arrayB) {
double percentage=0;
for(/*go through the first array*/) {
for(/*go through second array*/) {
if(arrayA[i]==arrayB[j]) { /*note the different indices*/
percentage++; /*count how many times you have matching values*/
/* NOTE: This only works if you don't have repeating values in arrayA*/
}
}
}
return (percentage/arrayA.length)*100; /*return the amount of times over the length times 100*/
}
You are going to move through the first array with the first loop and the second array with the second loop. So you go through every value in arrayB for each value in arrayA to check.
In my approach I tried storing the winning numbers in a Hashset (one pass iteration, O(n) )
And when iterating on the numberList, I would check for presence of number in Hashset and if so, I will increment the counter. (one pass iteration, so O(n) )
The percentage is thus calculated by dividing the counter with size of array.
See if the sample code makes sense:
import java.util.HashSet;
public class Arraycomparison {
public static void main(String ... args){
int[] arr0 = {1,4,2,7,6,3,5,0,3,9,3,5,7};
int[] arr1 = {5,2,4,1,3,7,8,3,2,6,4,4,1};
HashSet set = new HashSet();
for(int j = 0; j < arr1.length; j++){
set.add(arr1[j]);
}
double counter = 0;
for(int i = 0; i < arr0.length; i++){
if(set.contains(arr0[i])){
counter++;
}
}
System.out.println("Match percentage between arrays : " + counter/arr0.length*100);
}
}
You should use List over array, because that's a convenient way, but with array:
public class Winner {
public static void main(String... args) {
double result = getPercentThatMatch(new int[]{1,2,3,4,5}, new int[]{2,3,4,5,6});
System.out.println("Result="+result+"%");
}
public static double getPercentThatMatch(int[] winningNumbers,
int[] numberList) { // it is confusing to call an array as List
int match = 0;
for (int win : winningNumbers) {
for (int my : numberList ){
if (win == my){
System.out.println(win + " == " + my);
match++;
}
}
}
int max = winningNumbers.length; // assume that same length
System.out.println("max:"+max);
System.out.println("match:"+match);
double devide = match / max; // it won't be good, because the result will be intm so Java will trunc it!
System.out.println("int value:"+devide);
devide = (double) match / max; // you need to cast to float or double
System.out.println("float value:"+devide);
double percent = devide * 100;
return percent;
}
}
Hope this helps. ;)
//For unique elements
getpercentage(arr1, arr2){
res = arr1.filter(element=>arr2.includes(element))
return res.lenght/arr2.lenght * 100;
}
//For duplicate elements
getpercentage(arr1, arr2){
const setA = Set(arr1);
const setB = Set(arr2);
Let res = [ ];
for(let i of setB){
if(setA.has(i)){
res.push(i);
}
}
return res.lenght/setA.size* 100;

Convert matlab to java

i am new in java programming.I need to convert my matlab code to basic java codes not complex like just using loops and array, i tried several times but i failed.Thanks for helping.Here is my code.
x = [1,2,3,4,5,6,7];
x = perms(x);
i = 0;
c=1;
for m=1:1:5040;
for n=1:1:6;
if(x(c,n) == (x(c,(n+1))-1))
i = i+1;
break
end
end
c=c+1;
end
Answer : 2119
Let us go through the Matlab code and translate each row into Java. We will be going to need some abstractions, which we will introduce on the go.
First line:
x = [1,2,3,4,5,6,7];
A vector is assigned to a variable x. We could simply say that a vector is an array of integers, but maybe we need some better abstractions later. Let us define a new class Vector. Do not confuse it with java.util.Vector: There may be multiple classes of the same unqualified name.
class Vector {
private int[] value;
Vector(int... value) {
this.value = value;
}
int apply(int i) {
return value[i - 1];
}
int length() {
return value.length;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (int entry : value) {
result.append(prefix).append(entry);
prefix = " ";
}
return result.toString();
}
}
We are using an array of integers for the internal representation of our Vector. Note that you can swap out the internal representation any time as long as it does not leak out into the classe's interface. Hence, we restrict the access of our value-member to private, meaning only objects of type Vector are allowed to access it.
New Vector objects are instantiated by calling the constructor Vector(int... value), which takes a vararg integer argument. Internally in Java, varargs are the same as arrays, but they give us syntactic sugar, to instantiate our x in the following way:
Vector x = new Vector(1, 2, 3, 4, 5, 6, 7);
which looks very similar to your Matlab code.
An other thing is that, in Java, arrays are zero-indexed, while Matlab starts indexing at 1. Our Vector class defines an apply-method, which is supposed to access the i-th index. Hence, it returns value[i-1].
Now we want to compute
x = perms(x);
perms returns a matrix, containing all permutations of vector x. So we need an other abstraction: Matrix.
class Matrix {
private Vector[] rows;
Matrix(Vector... value) {
this.rows = value;
}
int apply(int x, int y) {
return rows[x - 1].apply(y);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (Vector row : rows) {
result.append(prefix).append(row.toString());
prefix = System.lineSeparator();
}
return result.toString();
}
}
Matrix is defined very similar to Vector, but its internal representation is an array of Vector, the rows of the matrix. Again, we define a method apply to retrieve an element: this time, it takes two parameters, the row index and the column index.
Side note: It is always good to override the method toString which is defined in the top element of Java's type hierarchy: Object. You can try to instantiate a Vector or a Matrix and pass it as argument to System.out.println to see how the string representation looks like.
Now we still need to implement perms in Java. The method perms takes a Vector and returns a Matrix. I have a very hacked and ugly implementation which I am a bit reluctant to show, but for the sake of a complete answer, here it is:
static Matrix perms(Vector vector) {
int[] indices = new int[vector.length()];
for (int i = 0; i < vector.length(); i++)
indices[i] = i;
List<int[]> allPermuationIndices = new ArrayList<int[]>();
permutation(new int[0], indices, allPermuationIndices);
Vector[] perms = new Vector[allPermuationIndices.size()];
for (int i = 0; i < perms.length; i++) {
int[] permutationIndices = allPermuationIndices.get(i);
int[] vectorValue = new int[permutationIndices.length];
for (int j = 0; j < permutationIndices.length; j++)
vectorValue[j] = vector.apply(permutationIndices[j] + 1);
perms[i] = new Vector(vectorValue);
}
return new Matrix(perms);
}
private static void permutation(int[] prefix, int[] remaining, List<int[]> returnValue) {
if (remaining.length == 0)
returnValue.add(prefix);
else {
for (int i = 0; i < remaining.length; i++) {
int elem = remaining[i];
int[] newPrefix = Arrays.copyOf(prefix, prefix.length + 1);
newPrefix[prefix.length] = elem;
int[] newRemaining = new int[remaining.length - 1];
System.arraycopy(remaining, 0, newRemaining, 0, i);
System.arraycopy(remaining, i + 1, newRemaining, i + 1 - 1, remaining.length - (i + 1));
permutation(newPrefix, newRemaining, returnValue);
}
}
}
Don't bother to understand what it is doing. Try writing a clean implementation on your own (or google for a solution).
Now, if we want to reassign our x, we run into trouble: The type does not match: We declared x to be of type Vector, but perm is returning a Matrix. There are multiple ways to solve this:
We could declare Vector to be a Matrix, i.e., change the signature to Vector extends Matrix. This solution may make sense, but be careful not to break behavioral subtyping: If a class B is a class A, then B must have the same behavior as A and can define additional behavior. Look up the Liskov Substitution Principle on the same note.
We could declare x to be of a supertype of both, Vector and Matrix. Currently, this is Object, but we could also define a new common supertype. This solution may however lose our static type safety. For example, if we want to use x as argument to perm, we need to dynamically cast it to a Vector
We could define a second variable x2 of type Matrix which holds the result. I suggest this solution in this case.
Next, we assign i = 0; and c=1;, which in Java translates to
int i = 0;
int c = 1;
Now, the for-loops:
for m = 1:1:5040
...
end
translates to
for (int m = 1; m <= 5040; i++) {
...
}
The only thing remaining, besides putting it all together, is the if-statement:
if(x2(c,n) == (x2(c,(n+1))-1))
...
end
translates to
if (x2.apply(c, n) == (x2.apply(c, n+1) - 1)) {
...
}
where apply is the method we defined on Matrix. Note that in Java, == will give you strange results if applied to non-primitive types, i.e., everything besides int, byte, char, double, boolean, and float. Generally, you test equivalence using the method equals which is defined on Object.

Complex Java Permutation Generation Problem

I am trying to work out the best way to generate all possible permutations for a sequence which is a fixed number of digits and each digit has a different alphabet.
I have a number of integer arrays and each one can have different length and when generating the permutations only the values of the array can occupy the position in the final results.
A specific example is an int array called conditions with the following data:
conditions1 = {1,2,3,4}
conditions2 = {1,2,3}
conditions3 = {1,2,3}
conditions4 = {1,2}
conditions5 = {1,2}
and I want to create a 5 column table of all the possible permutations - this case 144 (4x3x3x2x2). Column 1 can only use the values from conditions1 and column 2 from conditions2, etc.
output would be :
1,1,1,1,1
1,1,1,1,2
1,1,1,2,1
1,1,1,2,2
1,1,2,1,1
.
.
through to
4,3,3,2,2
It's been too long since since I've done any of this stuff and most of the information I've found relates to permutations with the same alphabet for all fields. I can use that then run a test after removing all the permutations that have columns with invalid values but sounds inefficient.
I'd appreciate any help here.
Z.
Look ma, no recursion needed.
Iterator<int[]> permutations(final int[]... conditions) {
int productLengths = 1;
for (int[] arr : conditions) { productLengths *= arr.length; }
final int nPermutations = productLengths;
return new Iterator<int[]>() {
int index = 0;
public boolean hasNext() { return index < nPermutations; }
public int[] next() {
if (index == nPermutations) { throw new NoSuchElementException(); }
int[] out = new int[conditions.length];
for (int i = out.length, x = index; --i >= 0;) {
int[] arr = conditions[i];
out[i] = arr[x % arr.length];
x /= arr.length;
}
++index;
return out;
}
public void remove() { throw new UnsupportedOperationException(); }
};
}
Wrapping it in an Iterable<int[]> will make it easier to use with a for (... : ...) loop. You can get rid of the array allocation by doing away with the iterator interface and just taking in as argument an array to fill.

Finding closest number in an array

In an array first we have to find whether a desired number exists in that or not?
If not then how will I find nearer number to the given desired number in Java?
An idea:
int nearest = -1;
int bestDistanceFoundYet = Integer.MAX_INTEGER;
// We iterate on the array...
for (int i = 0; i < array.length; i++) {
// if we found the desired number, we return it.
if (array[i] == desiredNumber) {
return array[i];
} else {
// else, we consider the difference between the desired number and the current number in the array.
int d = Math.abs(desiredNumber - array[i]);
if (d < bestDistanceFoundYet) {
// For the moment, this value is the nearest to the desired number...
bestDistanceFoundYet = d; // Assign new best distance...
nearest = array[i];
}
}
}
return nearest;
Another common definition of "closer" is based on the square of the difference. The outline is similar to that provided by romaintaz, except that you'd compute
long d = ((long)desiredNumber - array[i]);
and then compare (d * d) to the nearest distance.
Note that I've typed d as long rather than int to avoid overflow, which can happen even with the absolute-value-based calculation. (For example, think about what happens when desiredValue is at least half of the maximum 32-bit signed value, and the array contains a value with corresponding magnitude but negative sign.)
Finally, I'd write the method to return the index of the value located, rather than the value itself. In either of these two cases:
when the array has a length of zero, and
if you add a "tolerance" parameter that bounds the maximum difference you will consider as a match,
you can use -1 as an out-of-band value similar to the spec on indexOf.
//This will work
public int nearest(int of, List<Integer> in)
{
int min = Integer.MAX_VALUE;
int closest = of;
for (int v : in)
{
final int diff = Math.abs(v - of);
if (diff < min)
{
min = diff;
closest = v;
}
}
return closest;
}
If the array is sorted, then do a modified binary search. Basically if you do not find the number, then at the end of search return the lower bound.
Pseudocode to return list of closest integers.
myList = new ArrayList();
if(array.length==0) return myList;
myList.add(array[0]);
int closestDifference = abs(array[0]-numberToFind);
for (int i = 1; i < array.length; i++) {
int currentDifference= abs(array[i]-numberToFind);
if (currentDifference < closestDifference) {
myList.clear();
myList.add(array[i]);
closestDifference = currentDifference;
} else {
if(currentDifference==closestDifference) {
if( myList.get(0) !=array[i]) && (myList.size() < 2) {
myList.add(array[i]);
}
}
}
}
return myList;
Array.indexOf() to find out wheter element exists or not. If it does not, iterate over an array and maintain a variable which holds absolute value of difference between the desired and i-th element. Return element with least absolute difference.
Overall complexity is O(2n), which can be further reduced to a single iteration over an array (that'd be O(n)). Won't make much difference though.
Only thing missing is the semantics of closer.
What do you do if you're looking for six and your array has both four and eight?
Which one is closest?
int d = Math.abs(desiredNumber - array[i]);
if (d < bestDistanceFoundYet) {
// For the moment, this value is the nearest to the desired number...
nearest = array[i];
}
In this way you find the last number closer to desired number because bestDistanceFoundYet is constant and d memorize the last value passign the if (d<...).
If you want found the closer number WITH ANY DISTANCE by the desired number (d is'nt matter), you can memorize the last possibile value.
At the if you can test
if(d<last_d_memorized){ //the actual distance is shorter than the previous
// For the moment, this value is the nearest to the desired number...
nearest = array[i];
d_last_memorized=d;//is the actual shortest found delta
}
A few things to point out:
1 - You can convert the array to a list using
Arrays.asList(yourIntegerArray);
2 - Using a list, you can just use indexOf().
3 - Consider a scenario where you have a list of some length, you want the number closest to 3, you've already found that 2 is in the array, and you know that 3 is not. Without checking the other numbers, you can safely conclude that 2 is the best, because it's impossible to be closer. I'm not sure how indexOf() works, however, so this may not actually speed you up.
4 - Expanding on 3, let's say that indexOf() takes no more time than getting the value at an index. Then if you want the number closest to 3 in an array and you already have found 1, and have many more numbers to check, then it'll be faster to just check whether 2 or 4 is in the array.
5 - Expanding on 3 and 4, I think it might be possible to apply this to floats and doubles, although it would require that you use a step size smaller than 1... calculating how small seems beyond the scope of the question, though.
// paulmurray's answer to your question is really the best :
// The least square solution is way more elegant,
// here is a test code where numbertoLookFor
// is zero, if you want to try ...
import java.util.* ;
public class main {
public static void main(String[] args)
{
int[] somenumbers = {-2,3,6,1,5,5,-1} ;
ArrayList<Integer> l = new ArrayList<Integer>(10) ;
for(int i=0 ; i<somenumbers.length ; i++)
{
l.add(somenumbers[i]) ;
}
Collections.sort(l,
new java.util.Comparator<Integer>()
{
public int compare(Integer n1, Integer n2)
{
return n1*n1 - n2*n2 ;
}
}
) ;
Integer first = l.get(0) ;
System.out.println("nearest number is " + first) ;
}
}
int[] somenumbers = getAnArrayOfSomenumbers();
int numbertoLookFor = getTheNumberToLookFor();
boolean arrayContainsNumber =
new HashSet(Arrays.asList(somenumbers))
.contains(numbertoLookfor);
It's fast, too.
Oh - you wanted to find the nearest number? In that case:
int[] somenumbers = getAnArrayOfSomenumbers();
int numbertoLookFor = getTheNumberToLookFor();
ArrayList<Integer> l = new ArrayList<Integer>(
Arrays.asList(somenumbers)
);
Collections.sort(l);
while(l.size()>1) {
if(numbertoolookfor <= l.get((l.size()/2)-1)) {
l = l.subList(0, l.size()/2);
}
else {
l = l.subList(l.size()/2, l.size);
}
}
System.out.println("nearest number is" + l.get(0));
Oh - hang on: you were after a least squares solution?
Collections.sort(l, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
return (o1-numbertoLookFor)*(o1-numbertoLookFor) -
(o2-numbertoLookFor)*(o2-numbertoLookFor);
}});
System.out.println("nearest number is" + l.get(0));

Categories