logo CodeStepByStep logo

collapse_sequences

Language/Type: PHP recursion string return

Write a recursive function named collapse_sequences that accepts a String of any length $s and a single-character String $ch as parameters, and returns a new String that is the same as $s but with any consecutive sequences of $ch compressed into a single occurrence of $ch.

For example, collapse_sequences("aabaaccaaaaada", "a") should return "abaccada".

Your function is case-sensitive; if the character $ch is, for example, a lowercase 'f', your function should not collapse sequences of uppercase 'F' characters. In other words, you do not need to write code to handle case issues in this problem.

The following table shows several calls and their expected return values:

Call Returns
collapse_sequences("aabaaccaaaaaada", 'a') "abaccada"
collapse_sequences("mississssipppi", 's') "misisipppi"
collapse_sequences("babbbbebbbxbbbbbb", 'b') "babebxb"
collapse_sequences("palo alto", 'o'); "palo alto"
collapse_sequences("tennessee", 'x') "tennessee"
collapse_sequences("", 'x') ""

If passed $ch with a length not equal to 1, your function should throw an Exception with the message, "Error: second argument be a single-character string".

Constraints:

  • Do not declare any global variables.
  • Do not use any loops; you must use recursion.
  • Do not use any auxiliary data structures (e.g. arrays) or strings to solve this problem.
  • (The point of this problem is to solve it recursively; do not use a library function to get around recursion.)
  • Do not call any string member functions or string library functions that traverse or search the entire string.
  • You can declare as many primitive variables (e.g. integers) as you like.
  • You are allowed to define other "helper" functions if you like; they are subject to these same constraints.
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.