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));
}
}
-
1\$\begingroup\$ Welcome to Code Review! I hope you get some great answers. \$\endgroup\$Phrancis– Phrancis2016年02月26日 20:41:15 +00:00Commented Feb 26, 2016 at 20:41
-
\$\begingroup\$ Related: codereview.stackexchange.com/questions/121041/… \$\endgroup\$h.j.k.– h.j.k.2016年02月27日 02:35:03 +00:00Commented Feb 27, 2016 at 2:35
1 Answer 1
Lack of separation of concerns
You have a single main
function that:
- Reads a
String
and parses it to an internal format - Applies logic to it (finds numbers that sum to the target)
- Pretty prints the result
You should have at least 3 more functions:
public class NumPairs {
// Pseudocode, to return two objects at once read
// http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method
public static (int[], int) parseInput(String input) {
}
public static int[][] sumsTo(int[] list, int result) {
}
public static String prettify(int[][] result) {
}
public static void main(String[] args) {
// Simply use the other functions
}
}
You may still need to subdivide sumsTo
surther.
-
\$\begingroup\$ Surely you mean "prettify" \$\endgroup\$shmosel– shmosel2016年03月01日 22:41:05 +00:00Commented Mar 1, 2016 at 22:41