2011-11-17 65 views
0

我正在研究一個代碼來實現不同的搜索功能來解決農夫狼山羊白菜問題。我們給了我們的主要和FarmerWolfGoatCabbage類實現的幾個類。其中一個類別,AbstractSolver包括線如何將我的一個函數轉換爲可重用函數<T>?

 Iterable<AState> moves = s.getPossibleMoves(); 
     for (AState move : moves) 
      if (!closed.contains(move)) 
       addState(move); 

這裏是我的FarmerWolfGoatCabbage class.I基本上要

public DepthFirstSolver getPossibleMoves1(){ 

    DepthFirstSolver moves = null; 

    //use getOpposite() and addIfSafe 
    FarmerWolfGoatState fwgsParent = new FarmerWolfGoatState(); 
    FarmerWolfGoatState fwgsChild = null; 
    int hash; 
    // the farmer's current position before crossing the river 
    Side farmerCurrent = this.farmer; 

    if(this.wolf == farmerCurrent){ 
     fwgsChild = new FarmerWolfGoatState(this, this.getOpposite(this.farmer), 
        this.getOpposite(this.wolf), this.goat, this.cabbage); 
     hash = fwgsChild.hashCode(); 
     if(addIfSafe(hash)) 
      moves.addState(fwgsChild); 
     System.out.println("W"); 
    } 

    if(this.cabbage == farmerCurrent){ 
     fwgsChild = new FarmerWolfGoatState(this, this.getOpposite(this.farmer), 
        this.wolf, this.goat, this.getOpposite(this.cabbage)); 
     hash = fwgsChild.hashCode(); 
     if(addIfSafe(hash)) 
      moves.addState(fwgsChild); 
     System.out.println("C"); 
    } 

    if(this.goat == farmerCurrent){ 
     fwgsChild = new FarmerWolfGoatState(this, this.getOpposite(this.farmer), 
        this.wolf, this.getOpposite(this.goat), this.cabbage); 
     hash = fwgsChild.hashCode(); 
     fwgsChild.getPosition(); 
     // 

     if (fwgsChild == null) 
      System.out.println("NULL"); 

     if(addIfSafe(hash)) 
      //moves.addState(fwgsChild); 
     System.out.println("G"); 
    } 

    return moves; 
} 

翻譯以下功能到一個類似的功能,但與可迭代返回類型

public Iterable<AState> getPossibleMoves() 
{ 
} 
+0

如果這是一項家庭作業,您應該添加作業標籤:) – Jack

回答

1

Iterable是一個接口:

http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

您的FirstDepthSolver類需要實現該接口,因爲這是您從getPossibleMoves1()返回的接口。隨後,這意味着你將不得不實現Iterator(或者存儲你需要在一個已經提供了interator的java集合中迭代的東西,並返回它)。

我懷疑這是該任務試圖讓你做的除了解決手頭上的問題。

這太問題應該會有所幫助:How can I implement the Iterable interface?

0

讓DepthFirstSolver包裝類類型集合的一個成員變量。然後在DepthFirstSolver的構造函數中,將該成員變量實例化爲某種類型的集合(如您所願...... ArrayList)。在DepthFirstSolver類上創建一個add方法來調用成員變量add類。在DepthFirstSolver中添加一個迭代器方法來調用成員變量的迭代器。這樣你就不需要改變你的FarmerWolfGoatCabbage,除了在最後調用DepthFirstSolver的迭代器作爲返回值。