Created
August 14, 2012 17:51
-
-
Save imduffy15/3351225 to your computer and use it in GitHub Desktop.
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
/** | |
* Read in N integers and counts the number of triples | |
* that sum to exactly 0 | |
* | |
* @author Ian Duffy | |
* @version 0.0.1 | |
* | |
*/ | |
import java.util.*; | |
import java.io.*; | |
class Threesum { | |
public static int count(int[] a) { | |
int cnt=0; | |
for(int i=0;i<a.length;i++) { | |
for(int j=i+1;j<a.length;j++) { | |
for(int k=j+1;k<a.length;k++) { | |
if(a[i] + a[j] + a[k] == 0) { | |
cnt++; | |
} | |
} | |
} | |
} | |
return cnt; | |
} | |
public static void main(String[] args) { | |
try { | |
Scanner f = new Scanner(new File(args[0])); | |
if(f.hasNextLine()) { | |
String[] fields = f.useDelimiter("\\A").next().trim().split("\\s+"); | |
int[] vals = new int[fields.length]; | |
for(int i=0;i<fields.length;i++) { | |
vals[i] = Integer.parseInt(fields[i]); | |
} | |
System.out.println(count(vals)); | |
} | |
} catch(IOException e) { | |
System.out.println(e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment