01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
// Exercise 1.4.14 (Solution published at http://algs4.cs.princeton.edu/)
package algs14;
import stdlib.*;
/* ***********************************************************************
* Compilation: javac FourSum.java
* Execution: java FourSum < input.txt
*
* A program with N^4 running time. Read in N int integers
* and counts the number of 4-tuples that sum to exactly 0.
*
* Limitations
* -----------
* - we ignore integer overflow
*
*************************************************************************/
public class XFourSum {
// print distinct 4-tuples (i, j, k, l) such that a[i] + a[j] + a[k] + a[l] = 0
public static int printAll(int[] a) {
int N = a.length;
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
for (int k = j+1; k < N; k++) {
for (int l = k+1; l < N; l++) {
if (a[i] + a[j] + a[k] + a[l] == 0) {
StdOut.println(a[i] + " " + a[j] + " " + a[k] + " " + a[l]);
cnt ++;
}
}
}
}
}
return cnt;
}
// return number of distinct 4-tuples (i, j, k, l) such that a[i] + a[j] + a[k] + a[l] = 0
public static int count(int[] a) {
int N = a.length;
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
for (int k = j+1; k < N; k++) {
for (int l = k+1; l < N; l++) {
if (a[i] + a[j] + a[k] + a[l] == 0) {
cnt++;
}
}
}
}
}
return cnt;
}
public static void main(String[] args) {
StdIn.fromFile ("data/100ints.txt");
int[] a = StdIn.readAllInts();
int cnt = count(a);
StdOut.println(cnt);
if (cnt < 10) {
printAll(a);
}
}
}
|