Solved

string front three times

Posted on 2014-10-13
25
206 Views
Last Modified: 2014-10-15
Hi,

I am working on below challenge


http://codingbat.com/prob/p101475

I wrote as below and passed all test cases



Show output only (no red/green)
prev  |  next  |  chance   |  CodingBat  >  Warmup-2      
Expected      Run            
stringTimes("Hi", 2) → "HiHi"      "HiHi"      OK         
stringTimes("Hi", 3) → "HiHiHi"      "HiHiHi"      OK         
stringTimes("Hi", 1) → "Hi"      "Hi"      OK         
stringTimes("Hi", 0) → ""      ""      OK         
stringTimes("Hi", 5) → "HiHiHiHiHi"      "HiHiHiHiHi"      OK         
stringTimes("Oh Boy!", 2) → "Oh Boy!Oh Boy!"      "Oh Boy!Oh Boy!"      OK         
stringTimes("x", 4) → "xxxx"      "xxxx"      OK         
stringTimes("", 4) → ""      ""      OK         
stringTimes("code", 2) → "codecode"      "codecode"      OK         
stringTimes("code", 3) → "codecodecode"      "codecodecode"      OK         
public String frontTimes(String str, int n) {
  if(str.length()<3){
   String results = "" ;
   for(int i = 0;i<n;i++) {
       results += str ;
   }
   return results;
  }
   String result = "" ;
   for(int i = 0;i<n;i++) {
       result += str.substring(0,3) ;
   }
   return result ;
}

Open in new window


Does my code looks ok. Do i need to make some improvement or fix some issues. Please advise
0
Comment
Question by:gudii9
  • 8
  • 6
  • 5
  • +2
25 Comments
 
LVL 16

Assisted Solution

by:krakatoa
krakatoa earned 125 total points
ID: 40377399
That's ok.

I would prefer myself an if-else structure however, such as -

public String frontTimes(String str, int n) {
String result = "" ;
 if(str.length()<3){
   
   for(int i = 0;i<n;i++) {
       result += str ;
   }
     }
  else{
      for(int i = 0;i<n;i++) {
       result += str.substring(0,3) ;
   }
   }
       return result ;
  }

Open in new window


and then only declare the one String to use to return results.

It could also be considered an improvement if you were to declare a final int such as :  
final int FRONT = 3;

Open in new window


and to then use that FRONT in place of the two 3s. This makes bugs in longer passages less likely, which will be more important when your code gets longer.

(Also, strictly speaking, you would make everything as watertight as possible by putting the entire routine in a try{} catch(){} finally{} construction, returning the 'result' from within that finally clause).
0
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 125 total points
ID: 40377535
Your solution is certainly fine.

I think it could be further improved like this which makes 2 changes.

1st - find the front of the string using the "Math.min()" method to decide how many characters you need.

2nd - use StringBuilder instead of a simple String when building up the result.

public String frontTimes(String str, int n) {
   int len = Math.min(3, str.length()) ;
   String front = str.substring(0,len) ;

   StringBuilder result = new StringBuilder() ;
   for(int i = 0;i<n;i++) {
       result.append(front);
   }
   return result.toString() ;
}

Open in new window

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40377575
>>Math.min()<<

'luckily' Math is a default lang import - otherwise you'd be stuffed - if you didn't import verbatim. ;)
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40377898
You can cut things down further with recursion :

public String frontTimes(String st, int n) {
          String rS="";
        
	if (n >0){
		st=st.substring(0,Math.min(3,st.length()))+frontTimes(st,n-1);
	        rS = st;
	}
	return rS;	  
    }

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40378167
final int FRONT = 3;

I have to give static also  as below to make code to compile

public class Test14 {

	/**
	 * @param args
	 */
	final static int FRONT = 3;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		frontTimes("hello",2);
	}
	
	public static String frontTimes(String str, int n) {
		  if(str.length()<FRONT){
		   String results = "" ;
		   for(int i = 0;i<n;i++) {
		       results += str ;
		   }
		   return results;
		  }
		   String result = "" ;
		   for(int i = 0;i<n;i++) {
		       result += str.substring(0,FRONT) ;
		   }
		   return result ;
		}

}

Open in new window


putting the entire routine in a try{} catch(){} finally{} construction, returning the 'result' from within that finally clause

which routine. How to put it. Please advise
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40378384
Yes, well you'd have to make it static in the context you are deploying it in there, since, as you already know from other questions, you are calling the method from a static function - main().

This is illustrative of where a finally{} clause could be used  :

public static String frontTimes(String str, int n) {
String result = "" ;
final int FRONT = 3;
try{
  if(str.length()<FRONT){
   
   for(int i = 0;i<n;i++) {
       result += str ;
   }
   //return results;
  }
  else{
   //String result = "" ;
   for(int i = 0;i<n;i++) {
       result += str.substring(0,FRONT) ;
   }
   }
   }catch(Exception e){}
   finally{
   return result ;
   }
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40379056
public class Test14 {

	/**
	 * @param args
	 */
	final static int FRONT = 3;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str3=frontTimes("world",3);
		System.out.println("str3 is-->"+str3);
	}
	
	public static String frontTimes(String str, int n) {
		String result = "" ;
		final int FRONT = 3;
		try{
		  if(str.length()<FRONT){
		   
		   for(int i = 0;i<n;i++) {
		       result += str ;
		   }
		   //return results;
		  }
		  else{
		   //String result = "" ;
		   for(int i = 0;i<n;i++) {
		       result += str.substring(0,FRONT) ;
		   }
		   }
		   }catch(Exception e){}
		   finally{
		   return result ;
		   }
		}
}

Open in new window


i wrote as above got output as below in console
str3 is-->worworwor

Is it ok to put static in front of variable as below
final static int FRONT = 3;

And static in front of method as below
public static String frontTimes(String str, int n) {

Also what is importance of returning result inside the finally loop as below
 finally{
               return result ;
               }


I see one warning near finally loop(should i call loop or block or i can call either of them) as attached. I wonder why i got that warning.
please advise
FinallyWarning.jpg
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40379461
As I said you need static as the variable and the method are both in static environments themselves. If you were going into production with the code, you'd probably have an instance of the class, and so they would most likely not be static.

The try{}catch(){} finally{} structure is there to ensure that some value is always returned - finally guarantees that. As to why Eclipse doesn't like it, I can't say, as I do not use Eclipse or any other IDE as this is precisely the sort of reason that puts me off doing so.

Maybe it's not my place to say so, and maybe others will disagree, including you, but in my opinion you should try to do more coding using just Notepad and compiling and running with javac.exe and java.exe, rather than relying solely on Eclipse, because coding 'raw' will bring you closer to the JVM and what you write, and closer to the errors that we all make. At least, I would suggest you stick with Eclipse, but run your code with java.exe as well, so that in situations like this with finally{}, you can see whether the same complaints are encountered by the "horse's mouth", or not.
0
 
LVL 31

Assisted Solution

by:awking00
awking00 earned 125 total points
ID: 40379968
Since you only have two conditions (i.e. str.length <= 3 or str.length > 3) use of the ternary operator is appropriate.
public String frontTimes(String st, int n) {
      String result = "";
      String front = str.length() <= 3? str : str.substring(0,3);
      for (int i = 1; i<=n; i++) {
      result = result + front;
      }
return result
}
0
 
LVL 31

Expert Comment

by:awking00
ID: 40379973
Typo, should have been
public String frontTimes(String str, int n) {
0
 
LVL 7

Author Comment

by:gudii9
ID: 40379992
    String front = str.length() <= 3? str : str.substring(0,3);
Above ternary looks odd to me.How it work in case of true and false.

I thought ternary should be as below
condition?true_stmt:false_stmt like


str.length() <= 3? str.toUpperCase() : str.substring(0,str.length() - 3)
                                    + str.substring(str.length() - 3,str.length)).toUpperCase();

Open in new window




Since you only have two conditions (i.e. str.length <= 3 or str.length > 3) use of the ternary operator is appropriate.

If I have 1 condition what is appropriate to use.
same way if i have 3 conditions what is appropriate to use.
same way if i have more than 3 conditions what is appropriate to use.
Please advise
0
 
LVL 31

Expert Comment

by:awking00
ID: 40380021
>>String front = str.length() <= 3? str : str.substring(0,3);
Above ternary looks odd to me.How it work in case of true and false.

I thought ternary should be as below
condition?true_stmt:false_stmt<<
It really should be stated as
condition ? true_stmt value : false_stmt value
The condition is whether or not the length of the string is less than or equal to 3. If that statement is true, return the value after the "?" if not, return the value after the ":"
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 84

Expert Comment

by:ozo
ID: 40380329
If I have 1 condition what is appropriate to use.
If there is only one case to deal with, there is nothing to test, and you can just
do whatever is appropriate to the one case.
if i have 3 conditions what is appropriate to use.
same way if i have more than 3 conditions what is appropriate to use.
To distinguish between 3 or more cases would require two or more binary tests,
depending on the relationships between the cases, there may be a natural way to do this.
Or, there may be some operation you can do to make some of the cases equivalent
(for example, the Math.min operator might be used for this)
then the remainder of the code can deal with a reduced number of cases.
Or sometimes a switch statement can be a way of dealing with many different cases.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40380414
To distinguish between 3 or more cases would require two or more binary tests,
when you say binary test you mean using ternary operator right. Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40380442
The first operand of a ternary ?: operator is a binary test.
The condition in an if  statement is also a binary test.
The left operand of the && and || operators are also binary tests.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40380443
If I have 1 condition what is appropriate to use.
 same way if i have 3 conditions what is appropriate to use.
 same way if i have more than 3 conditions what is appropriate to use.
 Please advise

You can nest if statements and you can nest ternary statements also. You also have case construct, which does the same thing, but in a different way.
0
 
LVL 31

Expert Comment

by:awking00
ID: 40380568
The following demonstrates the use of nested if statements, use of nested ternary statements, and use of the switch statement, assuming 4 conditions. str <=3 return str, between 4 and 6 return str.substring(0,4), between 7 and 10 return str.substring(0,5), else return str.substring(0,6):

Nested ifs -
int len = str.length();
if (len <=3) {str
} else if (len > 3 && len < 7 {str.substring(0,4)
} else if (len > 6 && len < 11 {str.substring(0,5)
} else {str.substring(0,6)

Nested ternary operator -
len < 3? str : len >3 && len < 7? str.substring(0,4) : len > 6 && len < 11? str.substring(0,5) : str.substring(0,6

Switch method - (Note - this method is a little cumbersome when making string comparisons)
switch(len) {
  case 0:
     str;
     break;
  case 1:
     str;
     break;
  case 2:
     str;
     break;
  case 3:
     str;
     break;
  case 4:
     str.substring(0,4);
     break;
  case 5:
     str.substring(0,4);
     break;
  case 6:
     str.substring(0,4);
     break;
  case 7:
     str.substring(0,5);
     break;
  case 8:
     str.substring(0,5);
     break;
  case 9:
     str.substring(0,5);
     break;
  case 10:
     str.substring(0,5);
     break;
  default:
     str.substring(0,6)
}
0
 
LVL 84

Expert Comment

by:ozo
ID: 40381097
if (len <=3) {str
} else if (len > 3 && len < 7 {str.substring(0,4)
missing some punctuatuon
   if (len <=3) { str;
   } else if (len > 3 && len < 7 ){ str.substring(0,4);
Also missing a return or assignment
the len > 3 && is unnecessary, but is ok if it helps you to understand

Nested ternary operator -
or

int len=str.length();
return len <= 3? str : str.substring( 0,len <= 6? 4: len <= 10? 5:6);

when there are many alternatives, you might even consider a structure like:
 return str.substring(0,new int[]{0,1,2,3,4,4,4,5,5,5,5,6}[Math.min(str.length(),11)]);
0
 
LVL 7

Author Comment

by:gudii9
ID: 40381277
len < 3? str : len >3 && len < 7? str.substring(0,4) : len > 6 && len < 11? str.substring(0,5) : str.substring(0,6

Open in new window


i have not understood clearly above nested ternary statement.

Do i should focus on ? or ; to break above big line. please advise

what is meaning of

len < 3? str
0
 
LVL 84

Expert Comment

by:ozo
ID: 40381286
len < 3? str
Does not have a meaning unless it is followed by :
len < 3? str : something else
means str when len is less than 3, and something else otherwise.


One way to break up the line, to show nesting with indentation, might be
  len < 3 ?
               str
      :
                len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           len > 6 && len < 11?
                                   str.substring(0,5)
                              :
                                   str.substring(0,6)
                           
With explicit parentheses:
  len < 3 ?
               str
      :
               ( len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           (len > 6 && len < 11?
                                   str.substring(0,5)
                             :
                                   str.substring(0,6)
                            )
                )
0
 
LVL 31

Expert Comment

by:awking00
ID: 40382202
ozo,
I agree with everything you stated. I was just trying to use a little "shorthand" to keep my already lengthy response a little shorter.

qudii9,

len <= 3? str : len >3 && len < 7? str.substring(0,4) : len > 6 && len < 11? str.substring(0,5) : str.substring(0,6)
Note, I missed the equals sign.
>>i have not understood clearly above nested ternary statement.<<

In literal terms -
If the condition where the string length is less than or equal to 3 is true then return the string, where it's false test for the
condition where the string length is greater than 3 and less than 7, and if it's is true then return the first 4 characters of the string, where it's false test for the condition where the string length is greater than 6 and less than 11, and if it's is true then return the first 5 characters of the string, and where that's false (meaning none of the conditions are met), return the first 6 characters of the string,
0
 
LVL 7

Author Comment

by:gudii9
ID: 40382555
len < 3? str : something else

what is something else


whole
( len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           (len > 6 && len < 11?
                                   str.substring(0,5)
                             :
                                   str.substring(0,6)
                            )

or only till next :
 ( len >3 && len < 7 ?
                           str.substring(0,4)

please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40382565
With explicit parentheses:
  len < 3 ?
               str
      :
               ( len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           (len > 6 && len < 11?
                                   str.substring(0,5)
                             :
                                   str.substring(0,6)
                            )
                )

I feel one extra braket ) at the end. Please advise on where to put begin ( and then ) in case of explicit scenario
0
 
LVL 7

Author Comment

by:gudii9
ID: 40382571
len <= 3? str : (len >3 && len < 7)? (str.substring(0,4)) : (len > 6 && len < 11)? str.substring(0,5) : str.substring(0,6)

Above explicit paranthesis are correct or i need to modify?
please advise
0
 
LVL 84

Accepted Solution

by:
ozo earned 125 total points
ID: 40382594
They work. No need to modify if they clarify what you needed clarified.
I thought it was the nesting you wanted to clarify, whereas these clarify the operands instead.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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 …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

708 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

17 Experts available now in Live!

Get 1:1 Help Now