Possible Ways to reach a Sum

165 Views Asked by At

Imagine that I have a N long set of numbers. I would like to know the possible ways that I could reach a specific sum using only the numbers in my set. As an example:

sum to be reached is 60
set of numbers contains:
     10,18,7

output: case 1 : 10 (6 times)
        case 2 : 10 (2 times), 7 (2 times), 18 (2 times)
        etc...

Is there an algorithm/concept I could use for this? Thank you.

1

There are 1 best solutions below

0
On

Ok, as nobody answered this question I will provide what I came up with using help from the comments in my initial question. The solution utilizes recursion and is programmed in java. It may not be the most efficient method but it works.

import java.util.*;

public class Calc {
  private static double[] denom;  
  private static double amount;
  private static HashSet<List<Double>> possible;
  Scanner keyboard;

  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Please enter your total sum.");
    amount = keyboard.nextDouble();

    System.out.println("Please enter your denominators, seperated by commas.");
    String[] denominators = keyboard.next().split(",");
    denom = new double[denominators.length];

    for (int i=0; i<denominators.length; i++) denom[i] = Double.parseDouble(denominators[i]);

    changer(amount, new ArrayList<Double>(), 0);
  }

  private static void changer(double remaining, List<Double> coins, int pos) {
      possible = new HashSet<List<Double>>();
      change(remaining,coins,pos);
      System.out.println(possible);
  } 

  private static void change(double remaining, List<Double> coins, int pos) {
    if (remaining == 0) {
      //S
      possible.add(coins);
      System.out.println(coins);
      System.out.println(coins);
    } 
    else {
      if (remaining >= denom[pos]) {
        coins.add(denom[pos]);
        change(remaining - denom[pos], coins, pos);
        coins.remove(coins.size() - 1);
      }
      if (pos + 1 < denom.length) {
        change(remaining, coins, pos + 1);
      }
    }
  }
}