Solved

extrafront challenge

Posted on 2015-01-15
24
68 Views
Last Modified: 2015-01-27
Hi,

I am trying below challenge
http://codingbat.com/prob/p172063

I wrote as below and passing all tests.

public String extraFront(String str) {
int strLen=str.length();
String strOutput="";
if(strLen>=2){
 strOutput= str.substring(0,2)+str.substring(0,2)+str.substring(0,2);
  return strOutput;
  }
  
  if(strLen<2){
  strOutput= str+str+str;
  return strOutput;
  }
  return strOutput;
}

Open in new window


i would like to know how can i improve my code. thanks in advance
0
Comment
Question by:gudii9
  • 12
  • 7
  • 3
  • +1
24 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 250 total points
Comment Utility
To some extent, "improvement" can be in the eye of the beholder, but what I would probably do would be to first extract the first 2 chars of the original string (or whatever is there If there are fewer than 2 chars)
and then return 3 copies of that.
0
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 125 total points
Comment Utility
I'd suggest learning about the "Math.min" function which takes 2 values and returns the smaller of the two.

So:

int x = Math.min(10,2) ; // Returns 2
int y = Math.min(1,2) ;   // Returns 1

Then you can use that to make it much simpler to say "get the first 2 characters of the string or the length of the string - whichever is smaller".

Like this:

public String extraFront(String str) {
  int len = Math.min(str.length(),2) ;
  String firstTwo = str.substring(0, len) ;
  return firstTwo + firstTwo + firstTwo ;
}

Open in new window

0
 
LVL 31

Assisted Solution

by:awking00
awking00 earned 125 total points
Comment Utility
You could also use the StringUtils repeat method -
public String extraFront(String str) {
  int idx = str.length() == 1 ?  1 : 2;
return StringUtils.repeat(str.substring(0, idx),3);
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
int idx = str.length() == 1 ?  1 : 2;

what is meaning of above line
if
str.length() == 1 is true then idx is 1
if str.length() == 1 is false then idx is 2?
how it is taking care of string with more than 2 length.
please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String extraFront(String str) {
  int idx = str.length() == 1 ?  1 : 2;
return StringUtils.repeat(str.substring(0, idx),3);
}

when i wrote like above

i am getting

Compile problems:


Error:      return StringUtils.repeat(str.substring(0, idx),3);
             ^^^^^^^^^^^
StringUtils cannot be resolved


please advise
0
 
LVL 26

Expert Comment

by:dpearson
Comment Utility
He's using a 3rd party library - you won't want to use StringUtils.

If you're testing this code just use:
 String front = str.substring(0, idx) ;
 return front + front + front ;

Doug
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
int idx = str.length() == 1 ?  1 : 2;


what is meaning of above line
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String extraFront(String str) {
  int idx = str.length() == 1 ?  1 : 2;
String st=str.substring(0, idx);
return str+str+str;
}

Open in new window


when i wrote as above failing test cases as below
Expected	Run		
extraFront("Hello") → "HeHeHe"	"HelloHelloHello"	X	    
extraFront("ab") → "ababab"	"ababab"	OK	    
extraFront("H") → "HHH"	"HHH"	OK	    
extraFront("") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:3)"	X	    
extraFront("Candy") → "CaCaCa"	"CandyCandyCandy"	X	    
extraFront("Code") → "CoCoCo"	"CodeCodeCode"	X	    
other tests
X	    
Your progress graph for this problem

Open in new window


please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
In in http:#a40554355, String st is never used for anything.

Also, the case of str.length()==0 handled improperly.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String extraFront(String str) {
  int idx = str.length() == 1 ?  1 : 2;
String st=str.substring(0, idx);
return st+st+st;
}

Open in new window


i fixed by removing 'r' from str
now i fail one test case. please advise
Expected	Run		
extraFront("Hello") → "HeHeHe"	"HeHeHe"	OK	    
extraFront("ab") → "ababab"	"ababab"	OK	    
extraFront("H") → "HHH"	"HHH"	OK	    
extraFront("") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:3)"	X	    
extraFront("Candy") → "CaCaCa"	"CaCaCa"	OK	    
extraFront("Code") → "CoCoCo"	"CoCoCo"	OK	    
other tests
OK

Open in new window

0
 
LVL 26

Expert Comment

by:dpearson
Comment Utility
The code you posted isn't handling a string of length 0.

This will work:

public String extraFront(String str) {
  int idx = str.length() == 1 ?  1 : 2;
  if (str.length() == 0) idx = 0 ;
  
String st=str.substring(0, idx);
return st+st+st;
}

Open in new window


However as I posted up at the top this is computing the same thing in a clearer and less error-prone way:

public String extraFront(String str) {
  int len = Math.min(str.length(),2) ;
  String firstTwo = str.substring(0, len) ;
  return firstTwo + firstTwo + firstTwo ;
}

Open in new window

0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
I agree that my original submission did not account for a string lengthof 0 and shouldn't be used and dpearson's method of determining the len (i.e. index) to use is best. One modification that could be made is to return the repeated string in one line without the concatenation -

public String extraFront(String str) {
  int len = Math.min(str.length(),2) ;
  return new String(new char[3]).replace("\0",str.substring(0, idx));
}
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 7

Author Comment

by:gudii9
Comment Utility
int idx = str.length() == 1 ?  1 : 2;


what is meaning of above line in plain english.
return new String(new char[3]).replace("\0",str.substring(0, idx));
what is meaning of above line in plain english.
please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String extraFront(String str) {
  int idx = str.length() == 1 ?  1 : 2;
  if (str.length() == 0) idx = 0 ;
  
String st=str.substring(0, idx);
return st+st+st;
}

Open in new window


by the way i passed all tests as above
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
int idx = str.length() == 1 ?  1 : 2;
means
if(  str.length() == 1 ){
  idx = 1;
}else{
 idx = 2;
}

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
By the way, although using str.replace is not the method I'd be primarily inclined to choose for this challenge,
and although this, as well as your other
startMatch challenge
without x challenge
without x2 challenge
deFront challenge
without 2 challenge
questions are all simple enough to be done with basic String manipulation operations of the kind you may be getting used to by now,
so that it could seem overkill to throw the weight of a regular expression replacement mechanism at problems that can be easily solved using the familiar tools you are trying to learn to master,
it may be of interest to note that all of those challenges can be solved with a one line program that looks like
return str.replaceAll(pattern,replacement);
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
so when i see ? kind of regular expression then if and else loop should ring bell in mind. Also

return str.replaceAll(pattern,replacement);
can you please elaborate on this
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
so that it could seem overkill to throw the weight of a regular expression replacement mechanism at problems that can be easily solved using the familiar tools you are trying to learn to master,

i wonder which is the regular expression replacement mechanism.
In other post i got coment like below kind of format is not regular expression but short cut if else condition?


int idx = str.length() == 1 ?  1 : 2;

please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
replaceAll
public String replaceAll(String regex,
                String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Parameters:
regex - the regular expression to which this string is to be matched
replacement - the string to be substituted for each match
Returns:
The resulting String
Throws:
PatternSyntaxException - if the regular expression's syntax is invalid
Since:
1.4
See Also:
Pattern

i was reading aove API. I wonder where we are using  above method/regular expression pattern in this challenge. Please advise
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
We are not using the above regular expression method in this challenge.
The comment was that we could use the above regular expression method in this, as well as several other challenges.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
We are not using the above regular expression method in this challenge.
The comment was that we could use the above regular expression method in this, as well as several other challenges.

can you please advise how to use regular exoression for this and other challenges like
startMatch challenge
without x challenge
without x2 challenge
deFront challenge
without 2 challenge
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
I'd advise that it is more useful to learn to use the basic tools you know than to delve into more unfamiliar specialized tools, but for the sake of closure, one way to do this challenge with replaceAll is
return str.replaceAll("(..?).*","$1$1$1");
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
sure.. i will probably open separate question with regular expresiions later
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

772 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

12 Experts available now in Live!

Get 1:1 Help Now