Skip to content

Instantly share code, notes, and snippets.

@14104chk
Last active November 16, 2022 05:39
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 14104chk/08670a70a04dbd1b4b15747e9ed4f9d5 to your computer and use it in GitHub Desktop.
Save 14104chk/08670a70a04dbd1b4b15747e9ed4f9d5 to your computer and use it in GitHub Desktop.
private int[] a;
private int[] b;
/**
* @see <a href="https://v2ex.com/t/895464?p=2">see</a>
*/
public void calc(String[] input1, String[] input2) {
a = Stream.of(input1).mapToInt(e -> new BigDecimal(e).multiply(BigDecimal.valueOf(100)).intValue()).sorted().toArray();
b = Stream.of(input2).mapToInt(e -> new BigDecimal(e).multiply(BigDecimal.valueOf(100)).intValue()).sorted().toArray();
if (IntStream.of(a).sum() != IntStream.of(b).sum()) {
throw new IllegalArgumentException();
}
//多线程
int n = Runtime.getRuntime().availableProcessors();
for (int i = 0; i < n; i++) {
int begin = i;
new Thread(() -> {
calc(new int[b.length], a[1], 1, begin, n);
}, begin + ":" + n).start();
}
//单线程
// calc(new int[b.length], a[1], 1, 0, 1);
}
private void calc(int[] bused, int s, int index, int begin, int step) {
for (int i = begin; i < b.length; i += step) {
if (bused[i] > 0) {
continue;
}
if (i > 0 && b[i - 1] == b[i] && bused[i - 1] == 0) {
continue;
}
if (b[i] > s) {
break;
} else {
bused[i] = index;
if (b[i] < s) {
calc(bused, s - b[i], index, i + 1, 1);
} else if (index + 1 < a.length) {
calc(bused, a[index + 1], index + 1, 0, 1);
} else {
print(bused);
}
bused[i] = 0;
}
}
}
private synchronized void print(int[] bused) {
System.out.println("result:");
for (int j = 0; j < a.length; j++) {
System.out.print(BigDecimal.valueOf(a[j]).divide(BigDecimal.valueOf(100)) + " = ");
for (int k = 0; k < b.length; k++) {
if (bused[k] == j) {
System.out.print(BigDecimal.valueOf(b[k]).divide(BigDecimal.valueOf(100)) + " + ");
}
}
System.out.println("\b\b\b");
}
System.exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment