Sunday, December 18, 2011

String Puzzles

Recursion puzzles. There are solutions.

Also if you like math-related puzzles Project Euler has some good ones.

  1. Print out every letter in a string, one on each line, using recursion.

  2. Calculate 1 + 2 + ... + N using recursion.

  3. Calculate 1 * 2 * ... * N using recursion

  4. Calculate 1/1² + 1/2² + ... + 1/N² (≈ π²/6) using recursion.

  5. Calculate 1 / 2 / ... / N using recursion.

  6. Calculate 1/1! + 1/2! + ... + 1/N! using recursion.

  7. Make a string of N 'x's using recursion.

  8. Make a string of N 'a's followed by N 'b's using recursion.

  9. Perform an n-place rotation of a string using recursion.

    That is, "abcdef" rotated | 0 is "abcdef" | 1 is "bcdefa" | 2 is "cdefab" | 3 is "defabc" | etc

  10. Interleave (like riffle-shuffling a deck) two strings, using recursion:

    interleave("ABCD", "abcd") = "AaBbCcDd"
    
The two strings will be the same length.
  1. Interleave two strings, like the last one, except the two strings might not be the same length:

    interleave("aaaaa", "bb") = "ababaaa"
    
  2. Find sin(sin(sin(...sin(x)))) (N times) using recursion.

  3. Find out how many times you have to divide a number by 2 until it becomes 0, using recursion.

    So for example:

    4 / 2 / 2 / 2 = 0   3 times
    20 / 2 / 2 / 2 / 2 / 2 = 0   5 times
    
  4. Find how many steps it takes the 3n+1 sequence to reach 1, using recursion:

    n[k+1] = 3*n + 1   if n is odd
             n/2       if n is even
    
  5. Strip out all of the letter 'a' in a string, using recursion.

No comments:

Post a Comment