Input
The input for this problem is a String of sorted numbers and a special number. The syntax of the input would be
1,2,3,4;5
Output
The program will output all of the possible sums that equate to the special number. The output for the example would be
1,4;2,3
I solved the problem by using some simple subtraction. The program will begin at the greatest value and work its way to the lowest value. For each value the program will subtract it from the pre-set value and search the array for that value. I want to know what I could do better for this.
import java.util.*;
public class NumPairs {
static String line = "1,2,3,4;5";
public static void main(String[] args) {
String fina = "";
if(!line.equals("")){
String a = line.substring(line.indexOf(";")+1,line.length());
String[] valu = line.substring(0,line.indexOf(";")).split(",");
for(int h = valu.length-1; h >0; h--){
int need = Integer.parseInt(a) - Integer.parseInt(valu[h]);;
if(Arrays.asList(valu).indexOf(need + "") != -1 && fina.indexOf(need +"") == -1 && need != Integer.parseInt(valu[h])){
if(need > Integer.parseInt(valu[h]))
fina += valu[h] +","+need +";";
else
fina += need +","+ valu[h] + ";";
}
}
}
if(fina.equals(""))
System.out.println("NULL");
else
System.out.println(fina.substring(0,fina.length()-1));
}
}