Java - List<Object> -> Get Maximum of one int field where second int field is less than 1000

Shelo :

The title didn't make sense I know. Here's more detailed version :

Lets say I have :

public class Numbers{
   double x;
   int y;
}

and I have List<Numbers>. Now I need to get the best version of instances of this object and print this versions to console where sum of x is the biggest and sum of y is less than 1000.

I know that x can't be bigger than 1 and less than 0.5

my bet is to sort y values and then try to get the possible solution from filtering y , but I can't figure it out , any help is appreciated.

so lets take this example :

Numbers instances :
x = 0.7 ; 0.65 ; 0.5 ; 0.9 ; 0.55 ; 0.5
y = 250 ; 350 ;  450 ; 550 ; 750 ;  950

the best solution here is -> where numbers.get(0) (x = 0.7 and y = 250) and number.get(3) (x = 0.9 and y = 550) . sum of x is 1.55 and sum of y is less than 1000; Any other solution in this example either x is less than 1.55 or y is greater than 1000

You can sum as many numbers as you want. Of Course I can just make nested for loops and get the answer like that but the whole point is to use as less loop as possible. So basically, get the best solution

Looks like this is the Knapsack Problem. Answer was provided by @Andrew McGuinness

Andrew McGuinness :

It sounds like you're looking at some kind of "knapsack problem" -- you want to find a set of instances bounded by a limit.

This is a hard problem to solve from scratch, but there is a lot of research on it and some libraries you could use. It comes under the general field of "Dynamic Programming"

edit: GLPK is a library I have used for this, but not from Java

(Oh, and you need x to be a float or double, not an int)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25233&siteId=1