Java, algorithm there is money in a piggy bank

0

given this statement

How could I do it? I do not finish taking it out

I use two Array, one for the value and the other for the amount of that value, I begin to subtract from the highest, to never stay without change.

  • there is Money: You will receive a quantity of money and it will return true if there are enough coins and false otherwise.

  • sacaDinero: you will receive a number corresponding to an amount of money. If the amount requested can be obtained in the coins of the piggy bank, a message will be shown with the amount of coins provided of each type and will be deducted from the piggy bank.

      public static void main(String[] args) {
    int[] valor = {1, 2, 5};
    int[] cantidad = {1, 2, 4};
    int contador = valor.length - 1;
    int total = 24;
    //total es la suma de todo el array
    int dinero = 23;
    boolean hayDinero = false;
    if (total >= dinero) {
        do {
            if (cantidad[contador] != 0 & dinero >= valor[contador]) {
    
                dinero = dinero - valor[contador];
    
                cantidad[contador]--;
            }else{
                contador--; 
            }
    
        } while (dinero >= 0 & contador >= 0);
    }
    if(dinero==0){
        hayDinero=true;
    }
    System.out.println(dinero + " " + total);
    System.out.println(hayDinero);
    

    }

The problem is how I do for the second module, that is, the amount of coins I have to take out if there is money, that I would copy this algorithm to use it with some additions in this module, to know the amount of coins every type I take?

I can not think of another way to not copy this module in the second one with some console output add-ons + what it asks for

    
asked by user7407723 06.03.2018 в 14:00
source

1 answer

1

Simply put it in an array and if it is possible to reach that amount, you will sample this array saying which ones you are taking:

public static void main(String Args[])
{
    int[] valor = {1, 2, 5};
    int[] cantidad = {1, 2, 4};
    int contador = valor.length - 1;
    int total = 24;
    //total es la suma de todo el array
    int dinero = 23;
    boolean hayDinero = false;

    int[] cuales = new int[valor.length];
    if (total >= dinero) {
        do {
            if (cantidad[contador] != 0 & dinero >= valor[contador]) {

                dinero = dinero - valor[contador];

                cuales[contador]++;

                cantidad[contador]--;
            }else{
                contador--; 
            }

        } while (dinero >= 0 & contador >= 0);
    }
    if(dinero==0){
        hayDinero=true;
    }

    System.out.println(dinero + " " + total);
    System.out.println(hayDinero);

    if(hayDinero){
        System.out.println("Cuantas de cada tipo:");
        for(int j = 0; j < cuales.length; j++){
            System.out.println(cuales[j] + " monedas de valor " + valor[j]);
        }
    }
}
    
answered by 06.03.2018 / 15:53
source