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()...)

asked Jul 9, 2016 at 3:49
6
  • 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. Commented Jul 9, 2016 at 6:09
  • if you have better than above post that code as an answer. Commented Jul 10, 2016 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! Commented Jul 10, 2016 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. Commented Jul 16, 2016 at 5: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. Commented Jul 16, 2016 at 5:59

3 Answers 3

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

answered Jul 9, 2016 at 4:00

3 Comments

nice answer short and sweet !! @Elliot
really useful, but what if Collections use is not allowed in the code
@piyushsingh Then you should have mentioned that restriction in your question.
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.

answered Jul 9, 2016 at 4:00

1 Comment

@piyushsingh go through Elliot's answer it will be fastest way
0

Looks like an exercise, so not giving actual code.

Use String.split and Arrays.sort

answered Jul 9, 2016 at 3:55

1 Comment

it's not an exercise, i have already working code posted above.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.