これに取り組むために、複数の方法があります。
1つのオプションは、ダイナミックアレイ(ArrayListを参照)で前の試行を追跡することです。ここでは概念を説明するためのコードのビット:
//create a new list of integers
ArrayList<Integer> guesses = new ArrayList<Integer>();
//in your check function, test if the new value already exists
if(guesses.contains(NEW_GUESS_HERE)){
println("you've already tried this number");
}else{//otherwise add the current guess to keep track of for next time
guesses.add(NEW_GUESS_HERE);
}
別のオプションは、HashMapを使用しています。これは、インデックスベースの配列ではなく、連想配列です。この方法はより効率的で、値ごとに試行回数を把握することもできます。 HashMapsの詳細はこちらをご覧ください。長期的に役立ち、短期間で教師に感動を与える可能性があります。
は、ここでの考え方説明するための基本的なスケッチです:
//create a new hashmap of integers (key = guess, value = number of times tried)
HashMap<Integer,Integer> guesses = new HashMap<Integer,Integer>();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//check if the value was already recorded
try{
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.get(newValue);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.put(newValue,numberOfTries+1);
}catch(NullPointerException e){
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.put(newValue,1);
}
}
}
同様のオプションを、少しより多くのハックJSONObjectを使用することでしょう。連想配列(キーはintの代わりに、文字列であるが)、しかし、あなたが最初のインデックスに文字列にそれを推測した数を変換する必要があるだろう: コンセプトは似て
JSONObject guesses = new JSONObject();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//hacky int to string
String newValueStr = newValue+"";
//check if the value was already recorded
if(guesses.hasKey(newValueStr)){
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.getInt(newValueStr);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.setInt(newValueStr,numberOfTries+1);
}else{
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.setInt(newValueStr,1);
}
}
}
一つ素敵なあなたはsaveディスクに推測することができる、次にloadそれはプログラムがそれが再起動された場合でも、以前の推測を思い出すことができることです。 スケッチの開始時にデータを読み込み、スケッチが存在するときにデータを保存しようとすると楽しい演習をします。
ありがとうございます。私は実際にこれを投稿した直後にコードを手に入れましたが、後の家事に気を取られ、投稿を変更するのを忘れました。あなたが答えたことは確かに私のクラスメートを助けるでしょう。彼らはあまりにも立ち往生しています:D – Angus