[Algorithms] – The sum of pairs

Problem :

Given a set of numbers, you need check if has two numbers in this set that the sum is igual an integer number.

If there is you should return 1, otherwise 0.

Inputs :

– N integer corresponding to the sum;
– N integer corresponding to the number of array elements;
– 0..n – set elements;

My solution :

private static final Integer FOUND = 1;
private static final Integer NOT_FOUND = 0;

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<Integer> array = new ArrayList<>();
    Integer number = scan.nextInt();
    Integer counter = scan.nextInt();
    int i = 0;
    while( i < counter ) {
        array.add(scan.nextInt());
        i++;
    }
    Integer output1 = hasParNumberEqualsSun(number, array);
    System.out.println(output1);
}

private static int hasParNumberEqualsSun(Integer number, List<Integer> inputArray) {
    Integer result = NOT_FOUND;
    for (int i=0; i < inputArray.size(); i++){
        for (int x=1; x < inputArray.size(); x++){
            if (isSunEqualsN(number, inputArray.get(i), inputArray.get(x))) {
                result = FOUND;
                break;
            }
        }
        if ( result == FOUND) break;
    }
    return result;
}

private static boolean isSunEqualsN(Integer number, Integer firstNumber, Integer secondNumber) {
    if ( number.equals(firstNumber+secondNumber) ){
        return true;
    }
    return false;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s