Solved

strCopies  challenge

Posted on 2016-09-23
17
73 Views
Last Modified: 2016-09-29
Hi,

I am working on below challenge.
http://codingbat.com/prob/p118182
Psedo code:
1. check number of occurence of sub is n
2. if yes retrun true if no return false

I wrote my code as below and not passing all tests
public boolean strCopies(String str, String sub, int n) {
  int count=0;
    if (str.length() <2){ 
	    	return 0;
	    		}
	    if (str.startsWith( sub) {
	    	count =1 + strCopies (str.substring(2));//check count is n or not
	    	}
	    	else {
		   rcount= strCopies (str.substring(1));
	    	  
	    	}
}

Open in new window


getting below error
ompile problems:


Error:      if (str.startsWith( sub) {
                             ^
Syntax error on token ")", ) expected after this token


see Example Code to help with compile problems

Any improvements or alternate approaches?      

please advise
0
Comment
Question by:gudii9
  • 10
  • 5
  • 2
17 Comments
 
LVL 35

Accepted Solution

by:
Kimputer earned 250 total points
ID: 41812630
The error is regarding a missing closing )

As for the upcoming errors, you don't recurse correctly (you're changing types). Keeping the same type will make you think differently (harder though).
0
 
LVL 7

Author Comment

by:gudii9
ID: 41812766
public boolean strCopies(String str, String sub, int n) {
  int count=0;
  int count2=0;
    if (str.length() <sub.length()){ 
	    	return false;
	    		}
	    if ((str.substring(0,sub.length()).equals(sub))) {
	    	count= 1 + strCopies(str.substring(sub.length()),sub);
	    	}
	    	else {
		   count2= strCopies(str.substring(1),sub);
	    	  
	    	}
	    	if(count==n){
	    	  return true;
	    	}
	    	else{
	    	  return false;
	    	}
}

Open in new window


tried as above getting below error.
Compile problems:


Error:      count= 1 + strCopies(str.substring(sub.length()),sub);
                 ^^^^^^^^^
The method strCopies(String, String, int) in the type Shell is not applicable for the arguments (String, String)


see Example Code to help with compile problems

just pass smae n to recursion?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41812773
public boolean strCopies(String str, String sub, int n) {
  int count=0;
  int count2=0;
    if (str.length() <sub.length()){ 
	    	return false;
	    		}
	    if ((str.substring(0,sub.length()).equals(sub))) {
	    	count= 1 + strCopies(str.substring(sub.length()),sub,n);
	    	}
	    	else {
		   count2= strCopies(str.substring(1),sub,n);
	    	  
	    	}
	    	if(count==n){
	    	  return true;
	    	}
	    	else{
	    	  return false;
	    	}
}

Open in new window



above gives below err

Compile problems:


Error:      count= 1 + strCopies(str.substring(sub.length()),sub,n);
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The operator + is undefined for the argument type(s) int, boolean


see Example Code to help with compile problems
0
 
LVL 7

Author Comment

by:gudii9
ID: 41813354
public boolean strCopies(String str, String sub, int n) {
  int count=0;  int count2=0;
    if (str.length() <sub.length()){ 
	    	return false;
	    		}
	    if ((str.substring(0,sub.length()).equals(sub))) {
	    	return strCopies(str.substring(1),sub,n-1);
	    	}
	    	else {
		   return strCopies(str.substring(1),sub,n);
	    	  
	    	}
	    	
} 
	    	

Open in new window


above fails below tests

Expected      Run            
strCopies("catcowcat", "cat", 2) → true      false      X      
strCopies("catcowcat", "cow", 2) → false      false      OK      
strCopies("catcowcat", "cow", 1) → true      false      X      
strCopies("iiijjj", "i", 3) → true      false      X      
strCopies("iiijjj", "i", 4) → false      false      OK      
strCopies("iiijjj", "ii", 2) → true      false      X      
strCopies("iiijjj", "ii", 3) → false      false      OK      
strCopies("iiijjj", "x", 3) → false      false      OK      
strCopies("iiijjj", "x", 0) → true      false      X      
strCopies("iiiiij", "iii", 3) → true      false      X      
strCopies("iiiiij", "iii", 4) → false      false      OK      
strCopies("ijiiiiij", "iiii", 2) → true      false      X      
strCopies("ijiiiiij", "iiii", 3) → false      false      OK      
strCopies("dogcatdogcat", "dog", 2) → true      false      X      
other tests
X      

please advise
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 41813693
If you walk through the whole code, you'll find you never accounted for a "true" result. Fix it, and you may be closer to the correct answer.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41813874
let me think
0
 
LVL 7

Author Comment

by:gudii9
ID: 41815245
you'll find you never accounted for a "true" result.

how to account for that in my code? do i need to modify my base case?
 if (str.length() <sub.length()){
                return false;
                      }

if yes how?
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 41815866
First, you shouldn't code yet. You should write down in human language what you want to achieve. After that, you have to fun through some scenarios in your head if the human language is correctly put or not. If in your mind, MANY of the MOSTLY EDGE scenarios are correct, you can start changing the human language to Java code.

In this case, you need to figure out a few EDGE cases,
meaning if n=0 what to do.
If n=0 coming from an earlier run, what to do.
Test this in your head first:

strCopies("cow", "cow", 0)
strCopies("cow", "cow", 1)

Then slowly think about the loop. How to continue the loop. You figured out the the n-1 loop correct.
But is the n loop correct (loop it on your head with several examples)?
What should return true, what should return false.
Even if you have the n==0 nailed, how about if this is the termination loop? Is it still correct?
When looping in your head, also try to write down every loop on paper so you know how your code progresses, as in

strCopies("cow", "cow", 4)
strCopies("ow", "cow", 3)
etc etc all the way till the final one.

Also now, there are always more way to solve this puzzle. I had a totally different approach then the answer given (but still works). It's just how your brain is wired. There's never really just one solution.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 32

Expert Comment

by:sarabande
ID: 41817690
   if (str.length() <sub.length()){
                return false;
if length is not sufficient for a further match you should return true in case n is equal to 0. (n == 0) means that you found exactly the requested occurrances of sub in the str.

if n is negative you can return false, since you have more occurrences found than required.

Sara
0
 
LVL 7

Author Comment

by:gudii9
ID: 41817976
public boolean strCopies(String str, String sub, int n) {
 
    if (funcTest(str, sub) == n) {
      return true;
    }
     else {
       return false;
     }
  }
  

  
  
  int funcTest(String a, String b){
    int strLength=a.length();  
    int subLength=b.length();
    if (subLength <subLength){ 
	    	return 0;
	    		}
	    if ( a.substring(0,subLength).equals(b) )  {
	    	return 1+funcTest(a.substring(1),b);
	    	}
	    	else {
		   return funcTest(a.substring(1),b);
	    	}
} 

Open in new window


tried as above getting below errors

Expected      Run            
strCopies("catcowcat", "cat", 2) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:20)      X      
strCopies("catcowcat", "cow", 2) → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:20)      X      
strCopies("catcowcat", "cow", 1) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:20)      X      
strCopies("iiijjj", "i", 3) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:20)      X      
strCopies("iiijjj", "i", 4) → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:20)      X      
strCopies("iiijjj", "ii", 2) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:20)      X      
strCopies("iiijjj", "ii", 3) → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:20)      X      
strCopies("iiijjj", "x", 3) → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:20)      X      
strCopies("iiijjj", "x", 0) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:20)      X      
strCopies("iiiiij", "iii", 3) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:20)      X      
strCopies("iiiiij", "iii", 4) → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:20)      X      
strCopies("ijiiiiij", "iiii", 2) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:20)      X      
strCopies("ijiiiiij", "iiii", 3) → false      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:20)      X      
strCopies("dogcatdogcat", "dog", 2) → true      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:20)      X      
other tests
X      
Your progress graph for this problem


please advise
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 41818013
Try this solution without creating a new function. The point of the exercise is to get your brains to tune into this problem where with one function with only returning true or false will be complete enough. By using helper functions, you beat the whole purpose of the test. Even using extra variables will beat the whole exercise.
If you run the exercise in your head with only true and false, it should work as well.
It should look like your attempt with ID: 41813354 (without the extra variables though). Think that one through and try to think which paths lead to true and which to false.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41818075
public boolean strCopies(String str, String sub, int n) {
    if (funcTest(str, sub) == n) {
      return true;    }     else {
       return false;     }  }
  int funcTest(String a, String b){
    int strLength=a.length();  
    int subLength=b.length();
    if (strLength <subLength){ 
	    	return 0;
	    		}
	    if ( a.substring(0,subLength).equals(b) )  {
	    	return 1+funcTest(a.substring(1),b);
	    	}
	    	else {
		   return funcTest(a.substring(1),b);
	    	}} 

Open in new window


above passed all tests. i took subLength instead of strLength while doing < in fist condition

Try this solution without creating a new function. The point of the exercise is to get your brains to tune into this problem where with one function with only returning true or false will be complete enough. By using helper functions, you beat the whole purpose of the test. Even using extra variables will beat the whole exercise.
If you run the exercise in your head with only true and false, it should work as well.
It should look like your attempt with ID: 41813354 (without the extra variables though). Think that one through and try to think which paths lead to true and which to false.

let me think and try this approach also
0
 
LVL 32

Assisted Solution

by:sarabande
sarabande earned 250 total points
ID: 41818336
with little effort and changes you could use the code of functtest to be executed in function StrCopies.

- omit the test on functest in StrCopies and also the else branch.
- instead determine lengths as in functest.
- if str length is less than sub length then return true if n == 0 else return false.
- the first recursive call of StrCopies would not return "1 + StrCopies(..." but
  call StrCopies passing Substring(1) and n decremented by 1.
- the second recursive call lets the n unchanged (since it was not a hit).

if you do that way, each occurrence of sub would decrease the n by 1. if there are too Little occurrences, the n finally would be greater 0, if it is more than required, the n goes negative (you could break then if you want, but it would work anyway).

Sara
0
 
LVL 7

Author Comment

by:gudii9
ID: 41818372
I will try
0
 
LVL 7

Author Comment

by:gudii9
ID: 41821023
public boolean strCopies(String str, String sub, int n) {
    if (str.length() < sub.length()) {
      return (n == 0);
    }
    if (str.substring(0, sub.length()).equals(sub)){
        return strCopies(str.substring(1), sub, n - 1);
    }
    return strCopies(str.substring(1), sub, n);
}

Open in new window


like above?
it passes all tests
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 41821416
Yes, totally correct. But as I said, with programming, just like the brain, there are other solutions.
Another challenge would be for you to try the other approach. It has to do with skipping more than just one (and hence, code are a few lines more), but theoretically, with longer strings where there aren't many occurrences, it will run faster.
This kind of thinking is only necessary if you already know the input is always like that.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41821953
will try
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

Suggested Solutions

This article will show, step by step, how to integrate R code into a R Sweave document
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.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

760 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

18 Experts available now in Live!

Get 1:1 Help Now