Problem solution · Turing

CCC 2005 J5 - Bananas

CCC 2005 J5 - Bananas: a Turing solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Depth-first search
Source
CCCSolutions
Length
57 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For CCC 2005 J5 - Bananas, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 57 lines of Turing from the credited upstream file ccc05j5.t.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 2005 J5 - Bananas · TuringTuring
Use this to learn the idea, then write your own version.
% CCC 2005 Junior problem 5% Bananas%% this is an exercise in recursion.% it involved a pair of mutually recursive methods.%% This is quite beyond all but the best "junior" programmers% and would stump many "senior" high school programmers. :-) forward function monkeyWord (s : string) : boolean % an a-word is either:% the letter A  OR% the letter B + monkey language word + Sfunction aWord (s : string) : boolean    if s = "A" then        result true    elsif length (s) >= 3 and s (1) = "B" and            monkeyWord (s (2 .. * - 1)) and s (*) = "S" then        result true    else        result false    end ifend aWord % an monkey language word is either:% an a-word   or% an a-word + N + monkey language wordbody monkeyWord     if aWord (s) then        result true    else        % try all combos for the more complex version        var found : boolean := false        for i : 2 .. length (s) - 1                    found := found or                (aWord (s (1 .. i - 1)) and                s (i) = "N" and                monkeyWord (s (i + 1 .. *)))        end for        result found    end ifend monkeyWord  var s : stringloop    get s    exit when s = "X"    if monkeyWord (s) then        put "YES"    else        put "NO"    end ifend loop  

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗