Solved

conCat challenge

Posted on 2014-12-11
25
72 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
  • 9
  • 9
  • 6
  • +1
25 Comments
 
LVL 1

Assisted Solution

by:firebeast
firebeast earned 100 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
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 200 total points
Comment Utility
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
Comment Utility
If zzynx means ==0 instead of <0, then case 2) adequately covers case 1)
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
are edge cases different from corner cases. Or both essentially means same?
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility

      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
Comment Utility
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
Comment Utility
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 200 total points
Comment Utility
Much better, though I personally prefer indentation proportional to depth of nesting.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

The purpose of this article is to demonstrate how we can use conditional statements using Python.
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

762 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now