Solved

frontAgain challenge

Posted on 2014-12-15
27
126 Views
Last Modified: 2015-01-08
Hi,

I am working on below challenge
http://codingbat.com/prob/p196652

I wrote my code as below
public boolean frontAgain(String str) {
int len=str.length();
if(str.substring(0,1)==str.substring(len-1) &&str.substring(1,2)==str.substring(len-2,len-1))
{
return true;
}
  else
  {
  return false;
  }
}

I am failing with below message
Expected      Run            
frontAgain("edited") → true      false      X         
frontAgain("edit") → false      false      OK         
frontAgain("ed") → true      false      X         
frontAgain("jj") → true      false      X         
frontAgain("jjj") → true      false      X         
frontAgain("jjjj") → true      false      X         
frontAgain("jjjk") → false      false      OK         
frontAgain("x") → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:3)      X         
frontAgain("") → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:3)      X         
frontAgain("java") → false      false      OK         
frontAgain("javaja") → true      false      X         
other tests
X         
Your progress graph for this problem

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
  • 13
  • 10
  • 3
  • +1
27 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 40501526
Your code attempts to access non-existent parts of strings of length 0 or 1
Your code attempts to compare strings with ==
0
 
LVL 20

Assisted Solution

by:Sathish David Kumar N
Sathish David  Kumar N earned 50 total points
ID: 40502264
why are checking char ? directly check like string

str.substring(0,2).equals(str.substring(len-2,len))

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40502643
public boolean frontAgain(String str) {
int len=str.length();

if(len>=4){
if(str.substring(0,1).equals(str.substring(len-1)) &&str.substring(1,2).equals(str.substring(len-2,len-1)))
{
return true;
}
  else
  {
  return false;
  }
  }
  return false;
}

i fixed == part. still failing some test cases. please advise
0
Independent Software Vendors: 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!

 
LVL 84

Expert Comment

by:ozo
ID: 40502867
Your code would return true for "deited" not "edited"
Your code returns false for any string shorter than length 4
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503125
i wonder what i should do with 2 character strings.


Given a string, return true if the first 2 chars in the string also appear at the end of the string, such as with "edited".

frontAgain("edited") → true
frontAgain("edit") → false
frontAgain("ed") → true

frontAgain("ed") → true
I wonder how above statement should yield to true based on the challenge description. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503133
public boolean frontAgain(String str) {
int len=str.length();

if(len>=4){
if(str.substring(0,1).equals(str.substring(len-1)) &&str.substring(1,2).equals(str.substring(len-2,len-1)))
{
return true;
}
  else(len<2)
  {
  return false;
  }
  }
  return false;
}

Open in new window


I wonder why i cannot give len<2 condition inside the else block. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503137
public boolean frontAgain(String str) {
int len=str.length();

if(len>=4){
if(str.substring(0,1).equals(str.substring(len-1)) &&str.substring(1,2).equals(str.substring(len-2,len-1)))
{
return true;
}
}

if(len<=2)
  {
  return true;
  }
  
  
  return false;
}

Open in new window


i passed few other tests still failing some. please advise.
challenge did not mention about str being "" or single character.
please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40503340
frontAgain("ed") → true
What are the first two characters of "ed"?
What are the last two character of "ed"?
Are they the same?
0
 
LVL 84

Expert Comment

by:ozo
ID: 40503344
This is how if-then-else statements are constructed http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503370
else do not take condition where as if and else if takes.

 if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503399
frontAgain("ed") → true
What are the first two characters of "ed"?
What are the last two character of "ed"?
Are they the same?

oh i see from both sides ed so both same.

what happens if only one character is there
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503413
Your code would return true for "deited" not "edited"

if(str.substring(0,1).equals(str.substring(len-1)) &&str.substring(1,2).equals(str.substring(len-2,len-1))

i am comparing first with last character and second with last but one character.  I  wonder what i s the mistake i am doing to make java think as deited
please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40503414
Can a string with one character satisfy "the first 2 chars in the string also appear at the end of the string"?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503417
public boolean frontAgain(String str) {
int len=str.length();

if(len>=4){
if(str.substring(0,1).equals(str.substring(len-2,len-1)) &&str.substring(1,2).equals(str.substring(len-1)))
{
return true;
}
}

if(len<=2)
  {
  return true;
  }
  
  
  return false;
}

Open in new window


i modified as above still failing 3 test cases as below
Expected	Run		
frontAgain("edited") → true	true	OK	    
frontAgain("edit") → false	false	OK	    
frontAgain("ed") → true	true	OK	    
frontAgain("jj") → true	true	OK	    
frontAgain("jjj") → true	false	X	    
frontAgain("jjjj") → true	true	OK	    
frontAgain("jjjk") → false	false	OK	    
frontAgain("x") → false	true	X	    
frontAgain("") → false	true	X	    
frontAgain("java") → false	false	OK	    
frontAgain("javaja") → true	true	OK	    
other tests
OK	    

Open in new window

please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503422
Can a string with one character satisfy "the first 2 chars in the string also appear at the end of the string"?
i vote more for No since one character string do not have two characters in it
0
 
LVL 84

Expert Comment

by:ozo
ID: 40503429
Granted there is some room for doubt, but the examples
frontAgain("x") → false
frontAgain("") → false

seem to clarify it.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40503431
public boolean frontAgain(String str) {
int len=str.length();

if(len>2){
if(str.substring(0,1).equals(str.substring(len-2,len-1)) &&str.substring(1,2).equals(str.substring(len-1)))
{
return true;
}
}

if(len==2)
  {
  return true;
  }
  
  
  return false;
}

Open in new window


i think i got what you mentioned.
I passed all tests.
How can i improve my code. please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40503438
You're doing pretty good now, but there is a simpler way to do the test with one .equals instead of two

You might also combine some other things
0
 
LVL 32

Expert Comment

by:awking00
ID: 40507197
Why compare first character with next to last and second character with last? Just compare the two-character substrings -
public boolean frontAgain(String str) {
  int len = str.length();
  if (len > 1) {
    return str.substring(0,2).equals(str.substring(len - 2));
  }
  return false;
}
0
 
LVL 32

Expert Comment

by:awking00
ID: 40507207
As ozo suggests, the above code could be combined to make it shorter -
public boolean frontAgain(String str) {
  if (str.length() > 1) {
    return str.substring(0,2).equals(str.substring(str.length() - 2));
  }
  return false;
}
0
 
LVL 84

Expert Comment

by:ozo
ID: 40507612
Two .substring operations instead of four is an improvement, but you can also reduce it to one:
   return str.length()>=2 && str.endsWith(str.substring(0,2));

If you expect length==2 to be common, it may improve efficiency to add
str.length()==2 ||
0
 
LVL 7

Author Comment

by:gudii9
ID: 40517116
Two .substring operations instead of four is an improvement, but you can also reduce it to one:
   return str.length()>=2 && str.endsWith(str.substring(0,2));

If you expect length==2 to be common, it may improve efficiency to add
str.length()==2 ||

Open in new window


I wonder how to do this
0
 
LVL 84

Expert Comment

by:ozo
ID: 40517247
If you have no reason to expect any particular kind of input to be more common than any other kind of input then it makes little difference.
But if you expect your function to be called more often with one kind of input more often than it is called with other kinds of input, and you have a choice of which kinds of input would flow through the more efficient execution path, then you'd probably prefer to give priority to the kinds of input you expect to see most often.

Here there is no reason for expectation, but there is a choice.

I make the observation that in the case of strings of length 2, you know that str.endsWith(str.substring(0,2)) will automatically be true.
In one sense, it can me more efficient to let the special case be handled as just another instance of the general case,
which may reduce complicated proliferations of branching decisions.
But in another sense, testing the length of a string is a simpler operation than creating a new substring and then checking whether it matches the start of a string.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40533768
I make the observation that in the case of strings of length 2, you know that str.endsWith(str.substring(0,2)) will automatically be true.
In one sense, it can me more efficient to let the special case be handled as just another instance of the general case,
which may reduce complicated proliferations of branching decisions.
But in another sense, testing the length of a string is a simpler operation than creating a new substring and then checking whether it matches the start of a string.

both options seems logicaly valid not sure which one to prefer?
please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40536600
public boolean frontAgain(String str) {
    return str.length()>=2 && str.endsWith(str.substring(0,2));
}

Open in new window


i think i did not understood above code. I see all test passed.


what is meaning of below code.

return str.length()>=2 && str.endsWith(str.substring(0,2));

please advise
0
 
LVL 84

Accepted Solution

by:
ozo earned 225 total points
ID: 40536609
what is meaning of below code.

return str.length()>=2 && str.endsWith(str.substring(0,2));
if( ! (str.length()>=2) ){
   return false;
}else{
   return str.endsWith(str.substring(0,2));
}
0
 
LVL 32

Assisted Solution

by:awking00
awking00 earned 225 total points
ID: 40537745
>>what is meaning of below code.
return str.length()>=2 && str.endsWith(str.substring(0,2));<<
The statement tests two conditions for true or false. The first conditon is str.length() >= 2, if the length of the string is greater than or equal to 2, then the first condition evaluates to true, otherwise the first condition evaluates to false. The second condition is str.endsWith(str.substring(0,2), if the string ends with first two-character substring of the string, then the second condition is true, otherwise the second condition is false. Both condition one and ("&&") condition two must be met in order to return true, otherwise false will be returned.
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

This is about my first experience with programming Arduino.
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

734 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