Product A costs $10 , B costs $3 and C costs $0.50. A person bought 100 items for $100. How many of each item did the person buy.
I found the answer as-
94 * 0.5 = 47
1 * 3 = 3
5 * 10 = 50
But I am not able to implement it in java as the solution I got the result from Hit and Trial. What will be the algorithm for solving this problem
Plain brute-force:
for (int i1 = 0; i1 <= 10; i1++) {
for (int i2 = 0; i2 < 34; i2++) {
int i3 = 100 - i2 - i1;
int total = i1 * 10 + i2 * 3 + i3 / 2;
if (total == 100 && i3 % 2 == 0)
System.out.println(i1 + " * 10 + " + i2
+ " * 3 + " + i3 + " * 0.5 = 100");
}
}
Gives two answers:
P.S. of course, it's not the optimal solution, but for just three items and 100 total amount - it's fine (and optimal from the point of time required to code it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With