Solved

conCat challenge

Posted on 2014-12-11
25
77 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 100 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Certificat to iSeries KeyStore 1 31
Visual Studio hangs on running project 6 85
junit example issue 2 59
Website checklist for browser compatibility? 2 57
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

752 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