Return to Snippet

Revision: 66503
at May 16, 2014 15:00 by rikesh_kisnah


Initial Code
import java.io.*;
import java.util.*;

public class FindPair 
{
    public static Vector<MyPair> v = new Vector<MyPair> ();
	public static void main (String args[]) 
	{
//		System.out.println ("Hello world");
	 
        int target = -1; 
	    if (args.length != 0)
		{
			target = Integer.parseInt(args[0]);
		}
		else
		{
		    target = 5;
		}
		Iterator it = v.iterator(); 
		        
	
		//int []array = {0,1,2,3,4,5};
		int []array = new int[100];
		int size = PopulateArrayFromFile(array);
		PopulateArrayFromFile(array);
 //       for(int x=0; x < size; x++)
//		{
			//System.out.print (array[x]+ "... ");
//		}
		
		FindPairs(array,size, target);

        // System.out.println ("Size: "  + v.size());

        Enumeration e = v.elements();
		System.out.print("Array elements:");

		for(int n=0; n < size;n++ )
		{
			System.out.print (array[n]+ " ");
		}
		System.out.println();

        System.out.println ("target: " + target);
		
		while (e.hasMoreElements())
		{
			MyPair p = (MyPair)e.nextElement(); 
			System.out.println ("x: " + p.x + " y: " + p.y);
		}
		
	}
	
    public static int PopulateArrayFromFile (int []arr)
	{
	    int size = -1;
		try 
		{
			BufferedReader br = new BufferedReader (new FileReader ("data.txt"));
			String l;
			Vector <String> vFileContents = new Vector<String>();
			while ((l = br.readLine())!= null)
			{
			//	System.out.println ("l: " + l);
				vFileContents.add(l);
			}

			size = vFileContents.size(); 

			int count = 0;
			for (String x:vFileContents)
			{
			 //   System.out.println ("x: " + x);
				arr[count] = Integer.parseInt (x);
			 //   System.out.println ("arr: " + arr[count]);	
				count++;
			}
			//System.out.println ("here size: " + arr.length);

//			for (int n=0; n < size; n++)
//			{
			//	System.out.println ("here2: " + arr[n]);
//			}
		}catch (IOException io)
		{
			io.printStackTrace ();
		}
		return size;
	}

	public static void FindPairs(int []array, int size, int target)
	{
		for (int i =0; i <  size; i++)
		{
			for (int j = 1; j < size; j++)
			{
				int sum = array[i] + array[j]; 

				if (sum == target)
				{
					//System.out.println ("Adding elem: " + array[i] + " " + array[j]);
					v.addElement(new MyPair(array[i],array[j])); 
				}
			}
		}
	}

}


class MyPair 
{
    int x = 0;
	int y = 0;
	public MyPair (int x, int y) 
	{
		this.x = x;
		this.y = y; 
	} 
}

Initial URL


Initial Description
Write a code that will find the sum of any pairs of numbers

Initial Title
Find Pairs of Numbers

Initial Tags
number

Initial Language
Java