Java Algorithm to solve vendor machine 'change giving' problem

前端 未结 6 798
太阳男子
太阳男子 2021-01-16 22:10

As a graduate I went for an interview for a java development role and was doing pretty well in the technical examinations until i came up against this question.

If i

6条回答
  •  一生所求
    2021-01-16 22:20

    To answer your second question:

    Try with only {20,10} you will see that your program is really not right .

    You tried to transform my recurence into a loop, and I guess it's the best solution. But it's very difficult to do that in one loop (you're missing a lot of possibilities).

    You can try to reinialise the while loop with different constraint at each step for example adding a new while loop around your loop like this one

    while (i

    but it's still not enough ... so you will need to add some loop again until you treat all the cases.

    I don't think your approach with a while loop is the good one here.

    The easiest way would be to use for loop like this to treat all the possible solutions (from the similar question to your question):

     int total = 200;
    
                   System.out. printf("quarter\tdime\tnickle\tpenny\tto make %d\n", total);
    
                    int combos = 0;
    
                    for (int q = 0; q <= total / 25; q++)
                    {
                        int total_less_q = total - q * 25;
                        for (int d = 0; d <= total_less_q / 10; d++)
                        {
                            int total_less_q_d = total_less_q - d * 10;
                            for (int n = 0; n <= total_less_q_d / 5; n++)
                            {
                                int p = total_less_q_d - n * 5;
                                System.out.printf("%d\t%d\t%d\t%d\n", q, d, n, p);
                                combos++;
                            }
                        }
                    }
    
                    System.out.printf("%d combinations\n", combos);
    

    Hope it helps

提交回复
热议问题