0

In below code string is passed in a method with numbers separated by space, now we need to provide sum of smallest two numbers in the string.

public class SumNearZero {
public static int SumNearZero(String s) {
String temp=s;
int t1=0;
for (int i = 0; i <s.length(); i++) {

    if(temp.contains(" "))
    {
        t1++;
        temp=temp.substring(temp.indexOf(" ")+1);
    }
}
int a[]=new int[++t1];
int index=0;
for(int i=0; i<s.length(); i++)
{
if(s.contains(" "))
{
    a[index]=Integer.parseInt(s.substring(0,s.indexOf(" ")));
    s=s.substring(s.indexOf(" ")+1);
    index++;
}

}
a[index]=Integer.parseInt(s);

for (int i = 0; i < a.length; i++) {

for(int j=0; j<a.length-1; j++)
{
    int c=a[j],n=a[j+1];
    if(c>n)
    {
        int t=c;
        a[j]=n;
        a[j+1]=t;

    }   }   }
int result=a.length>1 ? a[0]+a[1]:a[0];
return result;
  }
public static void main(String[] args) {
System.out.println(SumNearZero("35 96 10 20 5"));
       }
         }

Above code is working fine but i want to reduce the code. if you provide some suggestion regarding this, I'll be happy to learn from you.

Restrictions : use of Collections, predefined methods e.g(String.split(),Arrays.sort()...)

piyush singh
  • 395
  • 8
  • 24
  • The code might be working, but the style is atrocious. 1) Indentation is awful. 2) Violations of identifier capitalization rules. 3) Meaningless variable names. 4) No javadocs. IMO, you should fix those things before you spend time trying to simplify / optimize the code. Why? Because you are asking other people to read your code ... now. – Stephen C Jul 09 '16 at 06:09
  • if you have better than above post that code as an answer. – piyush singh Jul 10 '16 at 10:45
  • I'll do better than than that. Compare your code style with Elliott Frisch's code. See how he indents his code? See how he uses correct identifier style and how consistent whitespace, consistent line breaks, etcetera? Copy Elliott's code style! – Stephen C Jul 10 '16 at 12:18
  • it's so easy with collections to implement the above code , i have asked without using Collections , please look at restrictions in the question. – piyush singh Jul 16 '16 at 05:23
  • piyushisingh - You are missing the point. Please read my comments again. I said your code style is bad. You said how do I improve my code style. I said read Elliot Frisch's code for an example of good style. The fact that Elliot's code does not satisfy your other requirements is irrelevant. It >does< provide an examplar of better style ... for you to learn from. – Stephen C Jul 16 '16 at 05:59
  • StephenC -Thank you – piyush singh Jul 16 '16 at 07:06

3 Answers3

2

I would suggest you not perform your calculation and display in a constructor, create a static method and invoke it. Next, in that method, create a List of Integer by iterating the substrings generated by splitting your input on one (or more) white space characters. Then, sort the List. Finally, return the sum of the first two elements1. It's also a good to do some error checking for one number (or no numbers). That might look something like

public static int sumNearZero(String s) {
    List<Integer> al = new ArrayList<>();
    for (String str : s.split("\\s+")) {
        al.add(Integer.parseInt(str));
    }
    if (al.isEmpty()) {
        return 0;
    }
    Collections.sort(al);
    if (al.size() == 1) {
        return al.get(0);
    }
    return (al.get(0) + al.get(1));
}

Then invoke it like

public static void main(String[] args) {
    System.out.println(sumNearZero("35 96 10 20 5"));
}

I get (as I expected)

15

1once sorted the first two are the minimum, and the last two are the maximum

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You can make it faster by using for each loop instead of for loop every time, it is more recommended and faster approach whenever loop is increasing for array, lists etc.

Plus more you can get all numbers in string by using split function which retrives you array of those numbers.and then you can put your logic for getting small numbers.this will reduce counting and increase speed highly in general if you want to learn about optimization then this is definitive guide i suggest you to go through it. and see this answer.

Community
  • 1
  • 1
TapanHP
  • 5,969
  • 6
  • 37
  • 66
0

Looks like an exercise, so not giving actual code.

Use String.split and Arrays.sort

saugata
  • 2,823
  • 1
  • 27
  • 39