11/2 課題講評


問題(一般化数当てゲーム)/h2>

講評


解答例とコメント

// Randomを使うため
import java.util.*;
// 
class GameSolver{
    static int solve(Problem problem){
        Random r=new Random();
        // index 番目が解である可能性があることを保持
        boolean canBeAnswer[]=new boolean[problem.size()];
        // 最初はすべて解である可能性がある.
        for(int i=0;i< problem.size();i++)canBeAnswer[i]=true;
        for(int count=1;;count++){
            int numCanBeAnswer=0;
            for(int j=0;j< problem.size();j++)
                if(canBeAnswer[j]) {
                    // numCanBeAnswerを1増やす
                    numCanBeAnswer++;
                }
            // kに[0 .. numCanBeAnswer-1]の乱数を入れる
            int k=r.nextInt(numCanBeAnswer);
            String nextQuestion="";
            for(int j=0;j< problem.size();j++){
                if(canBeAnswer[j]){
                    if(k==0) {
                        // nextQuestionに問題の解集合のj番目を入れる
                        nextQuestion=problem.get(j) ;
                        break;
                    }
                    else k--;
                }
            }
            System.out.println(nextQuestion);
            // nextQuestion と正解集合との間の関係を求める
            int type=problem.answerType(nextQuestion);
            System.out.println(problem.answerStrings()[type]);
            if(type==0) return count;
            for(int j=0;j< problem.size();j++){
                if(canBeAnswer[j] && 
                   problem.answerType(problem.get(j),nextQuestion)!=type){
                    // canBeAnswer[j]をfalseにする
                    canBeAnswer[j]=false;
                }
            }
        }
    }
    static public void main(String[] args){
        System.out.println(solve(new MooProblem()));
        
    }
}
穴埋め問題なのでほとんどの人がこれと同じ答えを書いてくれました.