Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

extrafront challenge

Posted on 2015-01-15
24
Medium Priority
?
102 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 85

Accepted Solution

by:
ozo earned 1000 total points
ID: 40552585
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 28

Assisted Solution

by:dpearson
dpearson earned 500 total points
ID: 40552674
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 32

Assisted Solution

by:awking00
awking00 earned 500 total points
ID: 40553542
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
Technology Partners: 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 7

Author Comment

by:gudii9
ID: 40554184
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
ID: 40554192
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 28

Expert Comment

by:dpearson
ID: 40554227
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
ID: 40554340
int idx = str.length() == 1 ?  1 : 2;


what is meaning of above line
0
 
LVL 7

Author Comment

by:gudii9
ID: 40554355
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 85

Expert Comment

by:ozo
ID: 40554409
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
ID: 40554414
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 28

Expert Comment

by:dpearson
ID: 40554436
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 32

Expert Comment

by:awking00
ID: 40555209
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
 
LVL 7

Author Comment

by:gudii9
ID: 40558618
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
ID: 40558623
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 85

Expert Comment

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

Open in new window

0
 
LVL 85

Expert Comment

by:ozo
ID: 40558760
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
ID: 40559839
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
ID: 40567111
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 85

Expert Comment

by:ozo
ID: 40567124
0
 
LVL 7

Author Comment

by:gudii9
ID: 40567252
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 85

Expert Comment

by:ozo
ID: 40568002
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
ID: 40570638
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 85

Expert Comment

by:ozo
ID: 40571752
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
ID: 40573806
sure.. i will probably open separate question with regular expresiions later
0

Featured Post

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!

Question has a verified solution.

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

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
This video teaches viewers about errors in exception handling.
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 …
Suggested Courses

927 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