Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solution: http://beust.com/weblog/2011/10/30/a-new-coding-challenge (updated using some ideas from other comments)
public class FortyPounds {
static final int[] s = {-1, 0, 1};
public static void main(String[] args) {
for (int w1 = 1; w1 <= 37; w1++)
for (int w2 = 1; w2 <= 38 - w1; w2++)
W3: for (int w3 = 1; w3 <= 39 - w1 - w2; w3++) {
int w4 = 40 - w1 - w2 - w3;
W: for (int w = 1; w <= 40; w++) {
for (int s1 : s) for (int s2 : s) for (int s3 : s) for (int s4 : s)
if (w == w1 * s1 + w2 * s2 + w3 * s3 + s4 * w4)
continue W;
continue W3;
}
System.out.println(String.format("%s %s %s %s", w1, w2, w3, w4));
}
}
}
/* Output:
1, 3, 9, 27
1, 3, 27, 9
1, 9, 3, 27
1, 9, 27, 3
1, 27, 3, 9
1, 27, 9, 3
3, 1, 9, 27
3, 1, 27, 9
3, 9, 1, 27
3, 9, 27, 1
3, 27, 1, 9
3, 27, 9, 1
9, 1, 3, 27
9, 1, 27, 3
9, 3, 1, 27
9, 3, 27, 1
9, 27, 1, 3
9, 27, 3, 1
27, 1, 3, 9
27, 1, 9, 3
27, 3, 1, 9
27, 3, 9, 1
27, 9, 1, 3
27, 9, 3, 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment