2012-02-23 19 views
3

私は再帰を勉強し始めているので、私はプロジェクトに取り組んでいます。私はこれについて非常に新しいので、私はこのパズルにどのように取り組むか分かりません。これは本の問題であり、私はこの問題を解決するためのアイデアを思いつくのに役立つステップ(step1、step2、...)に感謝します。また、誰かが私と共有することができれば感謝します。再帰を理解するにはまだそれほど意味がありませんので、このトピックをよりよく理解する方法についてアドバイスをいただければ幸いです。これは指示です。ありがとうございました。再帰Javaでの追加の追加

AdditionPuzzleの形式は、2BCD + BCDE = DA01です。我々は、A、B、C、Dがパズルの任意の数字とは異なる別個の数字であるすべての解を見つけたいと思う。ここで、解は2345 + 3456 = 5801である。一般に、パズルには10桁までの任意の数字と数字を組み合わせることができます。これら2つのクラスを使用してパズルにソリューションを計算する再帰的な方法を書く:

クラス#1

public class ThisPuzzle 
{ 
/** 
    Returns a solution to a puzzle. 
    @param p a puzzle 
    @return a solution or null if none exists 
*/ 
public static Puzzle solvePuzzle(Puzzle p) 
{ 
    // ... 
    return null; 
} 

public static void main(String[] args) 
{ 
    Puzzle p = new Puzzle("3A6", "36B", "71C"); 
    System.out.println(solvePuzzle(p)); 
} 
} 

クラス#2

public class Puzzle 
{ 
    private String add1; 
    private String add2; 
    private String result; 

    /** 
     Constructs a puzzle. 
     @param add1 a string containing digits 0 - 9 and letters 
     @param add2 a string containing digits 0 - 9 and letters 
     @param result a string containing digits 0 - 9 and letters 
    */ 
    public Puzzle(String add1, String add2, String result) 
    { 
     this.add1 = add1; 
     this.add2 = add2; 
     this.result = result; 
    } 

    /** 
     Makes a new puzzle by replacing a letter with a digit. 
     @param letter the letter to be replaced 
     @param digit the digit to replace it with 
     @return the new puzzle 
    */ 
    public Puzzle replace(String letter, int digit) 
    { 
     // ... 
    } 

    /** 
     Returns true if the puzzle is solved. 
     @return true if the puzzle has no letters and the 
     first two numbers add up to the third 
    */ 
    public boolean isSolved() 
    { 
     // ... 
    } 

    /** 
     Gets the first letter in this puzzle. 
     @return the first letter, or "" if there are no letters. 
    */ 
    public String firstLetter() 
    { 
     // ... 
    } 

    /** 
     Checks whether this puzzle contains a given digit. 
     @param digit a digit 
     @return true if this puzzle returns digit 
    */ 
    public boolean contains(int digit) 
    { 
     // ... 
    } 

    public String toString() 
    { 
     return add1 + "+" + add2 + "=" + result; 
    }  
} 

答えて

2

あなたはそれ自身の内部のメソッドを呼び出すときに再帰があります定義。

非常に単純な無限再帰は次のとおりです。

public static void recurse(){ 
    recurse(); 
} 

このメソッドを呼び出すと、スタックオーバーフロー例外が発生します。再帰の内部でメッセージを印刷すると、エラーが発生する理由を想像するのが簡単かもしれません。あなたは、印刷を打つ前に、マシンが、内側再帰が終了しますと、それはあなたのメッセージを印刷できることを無駄希望のすべてのメソッド呼び出しのスタックを維持する必要があるため

public static void recurse(){ 
    recurse(); 
    System.out.println("finished recursing") 
} 

エラーがスローされます。

あなたの問題については、solvePuzzleの中でsolvePuzzleを呼び出す必要があります。考え方は、再帰の各レベルの中で簡単にパズルを解くようにしなければならないということです。試行錯誤を考えてください。

関連する問題