Solved

extrafront challenge

Posted on 2015-01-15
24
85 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
[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
  • 12
  • 7
  • 3
  • +1
24 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 250 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 125 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 125 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
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 84

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 84

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 84

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 84

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 84

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 84

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article will show, step by step, how to integrate R code into a R Sweave document
A solution for Fortify Path Manipulation.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

627 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