#how to solve this without loops at all

14 messages · Page 1 of 1 (latest)

lime relic
#

is there a way to solve this without any loops at all? (no for loops)

feral quartzBOT
#

This post has been reserved for your question.

Hey @lime relic! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

cursive tendon
#

You can call the count11 with let's say substrings and when it starts with "11" you return 1 + count11(11) or count11() otherwise

#

And when substring is of length 1 you terminate recursion by returning 0

dark zealot
#

Sure something like this should work

public static int count(String str, String toCount)
{
if (str.length() < toCount.length())
{
  return 0;
}
if (str.startsWith(toCount))
{
  return 1 + count(str.substring(toCount.length()), toCount);
}
  return count(str.substring(1), toCount);
}

Should work ig

#

/run

public class A{
    public static void main(String[] args){
        System.out.println(count("11abc11"));
        System.out.println(count("abc11x11x11"));
        System.out.println(count("111"));
    }

public static int count(String str)
{
if (str.length() < 2)
{
  return 0;
}
if (str.startsWith("11"))
{
  return 1 + count(str.substring(2));
}
  return count(str.substring(1));
}

}
limpid steepleBOT
#

Here is your java(15.0.2) output @dark zealot

2
3
1
cursive tendon
#

@dark zealot in the assignment it looks like count can only take one parameter

#

It'd be something like this:

public static int count11(String str) {
  if (str.length() < 2) return 0;
  if (str.startsWith("11")) return 1 + count11(str.substring(1));
  return count(str.substring(1));
}
halcyon remnant
cursive tendon
#

Yea that's right, I haven't noticed the last sentence

lime relic
#

do you see what could be the problem with this attempt at the question?

#
  //what happens when all 1s
   if(str.length() < 2){ //cannot possibly have 11 which is 2 chracters long if string less than 2
    return 0; 
  }
  //going through string using substrings (passing substrings into the recursive function)
    
   if(str.substring(0,1) == "11"){   
     if(str.length() == 2){
       return count11(str.substring(1)) + 1;
        }
     else if (str.substring(2,2) == "1") {
        return count11(str.substring(1)); 
          }
        else    {
        return count11(str.substring(1))+1; 
          }
      }
   else{
     return count11(str.substring(1)); 
   } 
}```