extrafront challenge

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
LVL 7
gudii9Asked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
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
 
dpearsonConnect With a Mentor Commented:
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
 
awking00Connect With a Mentor Commented:
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
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
dpearsonCommented:
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
 
gudii9Author Commented:
int idx = str.length() == 1 ?  1 : 2;


what is meaning of above line
0
 
gudii9Author Commented:
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
 
ozoCommented:
In in http:#a40554355, String st is never used for anything.

Also, the case of str.length()==0 handled improperly.
0
 
gudii9Author Commented:
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
 
dpearsonCommented:
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
 
awking00Commented:
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
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
ozoCommented:
int idx = str.length() == 1 ?  1 : 2;
means
if(  str.length() == 1 ){
  idx = 1;
}else{
 idx = 2;
}

Open in new window

0
 
ozoCommented:
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
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
ozoCommented:
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
 
gudii9Author Commented:
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
 
ozoCommented:
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
 
gudii9Author Commented:
sure.. i will probably open separate question with regular expresiions later
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.