Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

conCat challenge

Posted on 2014-12-11
25
Medium Priority
?
84 Views
Last Modified: 2014-12-24
Hi,

I am working on below challenge
http://codingbat.com/prob/p132118
I wrote my code as below
public String conCat(String a, String b) {
String str="";
int aLength=a.length()-1;
int bLength=b.length()-1;

if(a.substring(aLength)==(b.substring(0,1)))
{
  str=(a.substring(0,aLength-3))+(b.substring(0));
  }
  else
  {
  str=a+b;
  }
  return str;
}

Open in new window

I am failing below tests.


Expected	Run		
conCat("abc", "cat") → "abcat"	"abccat"	X	    
conCat("dog", "cat") → "dogcat"	"dogcat"	OK	    
conCat("abc", "") → "abc"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:6)"	X	    
conCat("", "cat") → "cat"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"	X	    
conCat("pig", "g") → "pig"	"pigg"	X	    
conCat("pig", "doggy") → "pigdoggy"	"pigdoggy"	OK	    
other tests

Open in new window

How to fix and improve my code. Thanks in advance
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 9
  • 6
  • +1
25 Comments
 
LVL 1

Assisted Solution

by:firebeast
firebeast earned 400 total points
ID: 40494974
Can you think of a way to compare the 2 middle characters, and remove one if they are the same?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40494993
public class Test38 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strFinal=conCat("abc","cef");
		System.out.println("string is -->"+strFinal);
	}

	public static String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();
System.out.println("last of a is--"+a.substring(a.length()-1));
System.out.println("first of b is--"+b.substring(0,1));
System.out.println("firstttt of a is--"+a.substring(0));
System.out.println("firsttttt of b is--"+b.substring(1,bLength-1));
		if(a.substring(a.length()-1)==(b.substring(0,1)))
		{
			System.out.println("in if loop");
		  str=(a.substring(0)+(b.substring(1,bLength-1)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			  System.out.println("in else loop");
		  str=a+b;
		  }
		  return str;
		}
}

Open in new window


i tried as above. some how going in else loop not in if loop.

please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40495007
public class Test38 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strFinal=conCat("abc","cef");
		System.out.println("string is -->"+strFinal);
	}

	public static String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();
System.out.println("last of a is--"+a.substring(a.length()-1));
System.out.println("first of b is--"+b.substring(0,1));
System.out.println("firstttt of a is--"+a.substring(0));
System.out.println("firsttttt of b is--"+b.substring(1,bLength-1));
		if(a.substring(a.length()-1).equals((b.substring(0,1))))
		{
			System.out.println("in if loop");
		  str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			  System.out.println("in else loop");
		  str=a+b;
		  }
		  return str;
		}
}

Open in new window


when i write with .equals went inside if loop (not when i used ==. i wonder why)

also
b.substring(1,bLength) givining desired result(i thought b.substring(1,bLength-1 should give desired result)
please advise
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 84

Expert Comment

by:ozo
ID: 40495119
When aLength==0, a.substring(a.length()-1) is an invalid operation
When bLength==0, b.substring(0,1) is an invalid operation
0
 
LVL 84

Expert Comment

by:ozo
ID: 40495135
When used on String objects, == is true when two references are to the same object
equals is true when the values contained in the two objects are identical.
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 800 total points
ID: 40495853
First, you have to check for these corner cases.
1) both strings being empty [ if (aLength<0 && bLength<0) ] => return an empty string
2) the first string being empty [ else if (aLength<0) ]=> return the second string
3) the second string being empty [ else if (bLength<0) ]=> return the first string

Then do the normal processing:
4) the last character of the first string is the same as the first character as the second string
[ if (a.substring(aLength).equals(b.substring(0,1))) ]
=> return the first string + all characters of the  second string except the first character
5) if not all of the above cases [ else ]: return first string + second string

If you program the above flow, all test cases become green.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40495876
If zzynx means ==0 instead of <0, then case 2) adequately covers case 1)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 40495893
Since the author already has defined
int aLength=a.length()-1;
int bLength=b.length()-1;

Open in new window

I really mean <0

PS.
This is in fact a good example of bad variable names ;-)
I would rather call 'em 'aIndex' and 'bIndex'
0
 
LVL 84

Expert Comment

by:ozo
ID: 40495952
I guess it depends on which of  the authors code samples you take the definitions from.
I agree with the point about unclear variable names.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40496176
corner cases before normal processing is good approach which i am missing. Let me re read few times to get it
0
 
LVL 7

Author Comment

by:gudii9
ID: 40496197
1) both strings being empty [ if (aLength<0 && bLength<0)

if (aLength<0 && bLength<0)---> if(true&&true) comes right since if(0<0&&0<0)

0 cannot be less than 0 right (it can only be equal)
Please advise
0
 
LVL 37

Expert Comment

by:zzynx
ID: 40496228
If your first string is "".
aLength defined as a.length()-1 will be -1.
So,
if (aLength<0 && bLength<0) means: first ànd second string are BOTH empty

PS.
>> ...comes right since if(0<0&&0<0)
Wrong!
(0<0) is always false
(0<=0) is always true
(0>=0) is always true
(0>0) is always false
(-1<0) is always true
0
 
LVL 84

Expert Comment

by:ozo
ID: 40496327
corner cases before normal processing
Often, (though perhaps less so for this challenge than some others) one can transform the corner cases in such a way that they will be correctly handled by normal processing.
Alternatively, one might bypass the normal processing after dealing with a corner case.
But even without explicit corner cases, it can be helpful to check that your processing is properly handling its edge cases.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40496338
are edge cases different from corner cases. Or both essentially means same?
0
 
LVL 84

Expert Comment

by:ozo
ID: 40496352
In informal speech, they might be used interchangeably.
In some contexts, one may want to distinguish a corner as a place where two edges meet.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 40496356
>> Often, one can transform the corner cases in such a way that they will be correctly handled by normal processing.
No doubt that is (always) possible.
But in my opinion, in a lot of cases it is much better for the readability and hence the maintainability of the code to process them separately. The normal processing becomes easier and you clearly see that the special corner cases are taken care of. If you process all cases in one process block, you have to take a deeper/closer look to check that the corner cases are dealt with.
That's the eternal trade off between dense code versus readable code. I prefer the last one for sure.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40496380
take a deeper/closer look to check that the corner cases are dealt with
A good precaution even when corner cases are not explicitly presented.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40496385
any good articles links books on these topics. I was not very familiar on these edge, corner, normal etc cases.

Please advise
0
 
LVL 37

Expert Comment

by:zzynx
ID: 40496393
Checking that the corner cases are dealt with is indeed a good thing to do, if not a must.
My point is that checking that, is much easier when those corner cases are processed in separate blocks.
Especially in code that someone else wrote. Which is the case (daily) when you work in a software team.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 40496412
I don't know articles about corner/normal cases.

But the goal of processing them separately is:
of which I quote:
Optimise for the reader of the code, not the writer. Code is read more than it's written. If you optimise for the writer, you'll save a few key presses, but the cost to the reader is confusion, frustration, and subtle (and not-so-subtle) bugs.


0
 
LVL 7

Author Comment

by:gudii9
ID: 40516941
public class Test38 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strFinal=conCat("abc","cef");
		//System.out.println("string is -->"+strFinal);
	}

	public static String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();
//System.out.println("last of a is--"+a.substring(a.length()-1));
//System.out.println("first of b is--"+b.substring(0,1));
//System.out.println("firstttt of a is--"+a.substring(0));
//System.out.println("firsttttt of b is--"+b.substring(1,bLength-1));
		if(a.substring(a.length()-1).equals((b.substring(0,1))))
		{
			//System.out.println("in if loop");
		  str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			 // System.out.println("in else loop");
		  str=a+b;
		  }
		  return str;
		}
}

Open in new window


i tried as above still not passing all. Let me remove system outs and try in coding bat site.please advise on how to fix
0
 
LVL 7

Author Comment

by:gudii9
ID: 40516945

      public String conCat(String a, String b) {
            String str="";
            int aLength=a.length();
            int bLength=b.length();

            if(a.substring(a.length()-1).equals((b.substring(0,1))))
            {
                  
              str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
              }
              else
              {
                  
              str=a+b;
              }
              return str;
            }

i am failing in two test cases.

xpected	Run		
conCat("abc", "cat") → "abcat"	"abcat"	OK	    
conCat("dog", "cat") → "dogcat"	"dogcat"	OK	    
conCat("abc", "") → "abc"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:7)"	X	    
conCat("", "cat") → "cat"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)"	X	    
conCat("pig", "g") → "pig"	"pig"	OK	    
conCat("pig", "doggy") → "pigdoggy"	"pigdoggy"	OK	    
other tests
OK	  

Open in new window


please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40516948
The tests that are not passing are the case when aLength == 0 and  the case when bLength == 0
Some of the operations you are performing are invalid in such cases.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40516967
I see i forgot the edge cases
	public String conCat(String a, String b) {
		String str="";
		int aLength=a.length();
		int bLength=b.length();

		if(aLength>0&& bLength>0&& a.substring(a.length()-1).equals((b.substring(0,1))))
		{
			
		  str=(a.substring(0)+(b.substring(1,bLength)));//complete 1st then 2nd from index 1 to last
		  }
		  else
		  {
			
		  str=a+b;
		  }
		  return str;
		}

Open in new window


above passed all test cases. All looks fine right? please advise
0
 
LVL 84

Accepted Solution

by:
ozo earned 800 total points
ID: 40516979
Much better, though I personally prefer indentation proportional to depth of nesting.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
What do responsible coders do? They don't take detrimental shortcuts. They do take reasonable security precautions, create important automation, implement sufficient logging, fix things they break, and care about users.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Progress

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question