Print all possible combinations of coins per change amount

原创转载请注明出处:http://agilestyle.iteye.com/blog/2361927

 

Question:

Given a change amount, print all possible combinations using different sets of coins

 

Solution:

核心思想:递归

1. Sort coins from large to small based on amount

2. Determine how many large coins used

3. Calculate how much the amount left using a given number of large coins

4. Recursion to the deducted value using sub-set of the coins

5. Print out of the remaining amount dividable by the smallest coin amount

 

package org.fool.java.test;

public class PrintAllCoinChangeCombinationTest {
    public static void main(String[] args) {
        int[] coins = {25, 10, 5, 1};
        int[] counts = new int[coins.length];
        System.out.println("All possible coin combinations of 10 cents are: ");
        printCombination(coins, counts, 0, 10);

        System.out.println("All possible coin combinations of 25 cents are: ");
        printCombination(coins, counts, 0, 25);
    }

    // coins are the sorted coins in descending order, larger positioned more front
    // counts record the number of coins at certain location
    // start index is keep cracking of from which coin we start processing after choosing one larger coin amount
    // total amount keep track of remaining amount left processing
    private static void printCombination(int[] coins, int[] counts, int startIndex, int totalAmount) {
        if (startIndex >= coins.length) {
            // format the print out as "amount=?*25 + ?*10 + ..."
            for (int i = 0; i < coins.length; i++) {
                System.out.print("" + counts[i] + " * " + coins[i] + " + ");
            }

            System.out.println();

            return;
        }
        // notice if startIndex is the last one, we need check if it can be dividable by the smallest coin
        // if so, this is a good combination, otherwise, this is not possible combination thus discarded
        if (startIndex == coins.length - 1) {
            if (totalAmount % coins[startIndex] == 0) { // good combination
                // set the counts of coins at start index
                counts[startIndex] = totalAmount / coins[startIndex];
                // proceed to recursive call
                printCombination(coins, counts, startIndex + 1, 0); // notice startIndex + 1 and remaining amount = 0
            }
        } else {    // we still have option to choose 0-N larger coins
            for (int i = 0; i <= totalAmount / coins[startIndex]; i++) {
                // for every cycle in a loop, we choose an arbitrary number of larger coins and proceed next
                counts[startIndex] = i;
                // notice we need to update the remaining amount
                printCombination(coins, counts, startIndex + 1, totalAmount - coins[startIndex] * i);
            }
        }
    }
}

Console Output


 

Reference

https://www.youtube.com/watch?v=3VBjhiKUtmE&list=PLlhDxqlV_-vkak9feCSrnjlrnzzzcopSG&index=38

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以给你一个Python脚本,用来生成真值表并输出3个布尔变量的所有可能的组合以及所有逻辑门。# 参考代码 def truth_table_generator(a, b, c): # Create a list of binary values for each variable a_list = [False, True] b_list = [False, True] c_list = [False, True] # Generate all possible combinations of variables all_combinations = [(a_val, b_val, c_val) for a_val in a_list for b_val in b_list for c_val in c_list] # Print the truth table print("A\tB\tC\tAND\tOR\tXOR") for a_val, b_val, c_val in all_combinations: print(a_val, "\t", b_val, "\t", c_val, "\t", a_val and b_val and c_val, "\t", a_val or b_val or c_ ### 回答2: 以下是一个Python脚本,用于生成真值表,并输出包括所有逻辑门的可能组合: ```python # 定义逻辑门的函数 def AND_gate(a, b, c): return a and b and c def OR_gate(a, b, c): return a or b or c def NOT_gate(a): return not a def XOR_gate(a, b, c): return (a and not b and not c) or (not a and b and not c) or (not a and not b and c) # 定义输入变量 input_a = [False, True] input_b = [False, True] input_c = [False, True] # 遍历所有可能的组合,打印真值表 print("A\tB\tC\tAND\tOR\tNOT\tXOR") for a in input_a: for b in input_b: for c in input_c: # 计算逻辑门的输出 AND_output = int(AND_gate(a, b, c)) OR_output = int(OR_gate(a, b, c)) NOT_output = int(NOT_gate(a)) XOR_output = int(XOR_gate(a, b, c)) # 打印当前组合的结果 print(f"{a}\t{b}\t{c}\t{AND_output}\t{OR_output}\t{NOT_output}\t{XOR_output}") ``` 这个脚本中定义了4个逻辑门函数:AND_gate(与门),OR_gate(或门),NOT_gate(非门)和XOR_gate(异或门)。然后通过遍历3个输入变量的所有可能组合,分别计算逻辑门的输出,并将结果打印成真值表的形式。每一行表示一个组合,包括输入变量的值和逻辑门的输出结果。输出结果为0代表False,1代表True。 ### 回答3: 这是一个生成真值表的Python脚本,它将输入3个布尔变量,并输出所有逻辑门的可能组合。 ```python def generate_truth_table(): variables = [False, True] # 可能的布尔变量值 for var1 in variables: for var2 in variables: for var3 in variables: # AND门 result_and = var1 and var2 and var3 # OR门 result_or = var1 or var2 or var3 # NOT门 result_not1 = not var1 result_not2 = not var2 result_not3 = not var3 # XOR门 result_xor = var1 ^ var2 ^ var3 # 打印结果 print(f"Input: {var1}, {var2}, {var3}") print("AND:", result_and) print("OR:", result_or) print("NOT1:", result_not1) print("NOT2:", result_not2) print("NOT3:", result_not3) print("XOR:", result_xor) print() # 调用函数生成真值表 generate_truth_table() ``` 这个脚本使用3个循环来遍历所有可能的布尔变量值组合。然后,根据这些变量值计算并打印出与门、或门、非门和异或门的结果。每个组合和其结果将以易读的方式打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值