Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for the each item

Tags:

java

algorithm

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

like image 359
Abhishek Choudhary Avatar asked Aug 20 '26 13:08

Abhishek Choudhary


1 Answers

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:

  • 0 * 10 + 20 * 3 + 80 * 0.5 = 100
  • 5 * 10 + 1 * 3 + 94 * 0.5 = 100

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).

like image 164
Eugene Retunsky Avatar answered Aug 23 '26 02:08

Eugene Retunsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!