2012-02-23 3 views
3

재귀 연구를 시작하기 때문에 프로젝트를 진행 중입니다. 나는 이것에 아주 새롭다 그래서 나는이 수수께끼를 달려 들기 위하여 어떻게 확실하지 않다. 이것은 책의 문제이며이 문제를 해결하기위한 아이디어를 제안하는 데 도움이 될 수있는 모든 단계 (1 단계, 2 단계 ...)에 감사드립니다. 또한 어느 누구와도 공유 할 수 있다면 정말 고맙습니다. 재귀를 이해하고, 여전히 나에게 많은 의미를 가지지 않으므로이 주제를 더 잘 이해하는 방법에 대한 조언을 주시면 감사하겠습니다. 좋습니다, 이것들이 지시 사항입니다. 고맙습니다.자바의 재귀 추가 패키지

AdditionPuzzle의 형식은 2BCD + BCDE = DA01입니다. 우리는 A, B, C, D가 퍼즐의 모든 숫자와 다른 구별 숫자 인 모든 솔루션을 찾고자합니다. 여기서, 해는 2345 + 3456 = 5801입니다. 일반적으로 퍼즐에는 최대 10 자리 숫자의 조합이있을 수 있습니다. 이 두 클래스를 사용하여 퍼즐에 대한 해결책을 계산하는 재귀 적 방법을 쓰기 :

클래스 # 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를 호출해야합니다. 아이디어는 재귀의 각 레벨 내에서 더 쉬운 퍼즐을 풀려고 시도해야한다는 것입니다. 시행 착오를 생각해보십시오.