Skip to content

Instantly share code, notes, and snippets.

@leons727
Created October 31, 2011 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leons727/1326736 to your computer and use it in GitHub Desktop.
Save leons727/1326736 to your computer and use it in GitHub Desktop.
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