Skip to content

Instantly share code, notes, and snippets.

@kylelong
Created November 3, 2018 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelong/572f29e7bdbb4168eabe692952161b5f to your computer and use it in GitHub Desktop.
Save kylelong/572f29e7bdbb4168eabe692952161b5f to your computer and use it in GitHub Desktop.
Given a set of numbers -50 to 50, find all pairs that add up to a given sum. Week of 10/28/2018 cassido newsletter interview problem
/**
Given a set of numbers -50 to 50, find all pairs that add up to a given sum.
* Created by kylel95 on 11/3/18.
*/
import java.util.*;
public class fiftysum {
public static void main(String [] args){
int [] arr = new int[101];
int index = 0;
for(int i = -50; i <= 50; i++){
arr[index] = i;
index++;
}
int n = 10;
List<String> list = allPairs(n, arr);
if(list.size() == 0){
System.out.println("No pairs were found.");
}
else {
for (String s : list) {
System.out.println(s);
}
}
}
public static List<String> allPairs(int n, int [] arr){
List<String> list = new ArrayList<>();
for(int i : arr){
for(int j: arr){
if(i + j == n){
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(i);
sb.append(",");
sb.append(j);
sb.append(")");
list.add(sb.toString());
}
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment