Created
May 12, 2015 23:50
-
-
Save svpino/d13221dbed231c36c9e5 to your computer and use it in GitHub Desktop.
Problem 5 in "Five programming problems every Software Engineer should be able to solve in less than 1 hour"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
// Solution to Problem 5 in "Five programming problems every Software Engineer should be able to solve in less than 1 hour" | |
// Original post: https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour | |
public class Main { | |
private static int TARGET_SUM = 100; | |
private static int[] VALUES = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; | |
static ArrayList add(int digit, String sign, ArrayList branches) { | |
for (int i = 0; i < branches.size(); i++) { | |
branches.set(i, digit + sign + branches.get(i)); | |
} | |
return branches; | |
} | |
static ArrayList f(int sum, int number, int index) { | |
int digit = Math.abs(number % 10); | |
if (index >= VALUES.length) { | |
if (sum == number) { | |
ArrayList result = new ArrayList(); | |
result.add(Integer.toString(digit)); | |
return result; | |
} | |
else { | |
return new ArrayList(); | |
} | |
} | |
ArrayList branch1 = f(sum - number, VALUES[index], index + 1); | |
ArrayList branch2 = f(sum - number, -VALUES[index], index + 1); | |
int concatenatedNumber = number >= 0 | |
? 10 * number + VALUES[index] | |
: 10 * number - VALUES[index]; | |
ArrayList branch3 = f(sum, concatenatedNumber, index + 1); | |
ArrayList results = new ArrayList(); | |
results.addAll(add(digit, "+", branch1)); | |
results.addAll(add(digit, "-", branch2)); | |
results.addAll(add(digit, "", branch3)); | |
return results; | |
} | |
public static void main(String[] args) { | |
for (String string : f(TARGET_SUM, VALUES[0], 1)) { | |
System.out.println(string); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment