Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Vector;
- import java.util.Arrays;
- import java.io.File;
- class TripleSum{
- public static boolean tripleSum(int[] A){
- return findTriple(A,225);
- }
- public static boolean findTriple(int[] A, int sum){
- int n = A.length;
- boolean[] refTable = new boolean[sum+1];
- //Count all instaces of 0 <= x <= 225
- for(int i = 0; i < n; i++){
- if( (A[i] <= sum) && !refTable[A[i]]){
- refTable[A[i]] = true;
- }
- }
- //Try and find a pair of numbers that add to sum
- for(int i = 0; i <= sum/2; i++){
- if(refTable[i] && refTable[sum-i]){
- //If so, try and break at least one of those numbers into another pair
- for(int j = 0; j <= (sum-i)/2; j++){
- if((i-j) > 0){
- if(refTable[j] && refTable[i-j]){
- return true;
- }
- }
- else{
- if(refTable[j] && refTable[sum-i-j]){
- return true;
- }
- }
- }
- }
- }
- return false;
- }
- public static void main(String[] args){
- Scanner s;
- if (args.length > 0){
- try{
- s = new Scanner(new File(args[0]));
- } catch(java.io.FileNotFoundException e){
- System.out.printf("Unable to open %s\n",args[0]);
- return;
- }
- System.out.printf("Reading input values from %s.\n",args[0]);
- }else{
- s = new Scanner(System.in);
- System.out.printf("Enter a list of non-negative integers. Enter a negative value to end the list.\n");
- }
- Vector<Integer> inputVector = new Vector<Integer>();
- int v;
- while(s.hasNextInt() && (v = s.nextInt()) >= 0)
- inputVector.add(v);
- int[] array = new int[inputVector.size()];
- for (int i = 0; i < array.length; i++)
- array[i] = inputVector.get(i);
- System.out.printf("Read %d values.\n",array.length);
- long startTime = System.currentTimeMillis();
- boolean tripleExists = tripleSum(array);
- long endTime = System.currentTimeMillis();
- double totalTimeSeconds = (endTime-startTime)/1000.0;
- System.out.printf("Array %s a triple of values which add to 225.\n",tripleExists? "contains":"does not contain");
- System.out.printf("Total Time (seconds): %.4f\n",totalTimeSeconds);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement