この質問は、コードの構文についてではなく、実際にメソッドを作成する方法についてです。
プログラムの開始時に、組み合わせ内のスイッチの数を入力します。各組み合わせは、オン/オフ値を持つことができるスイッチの数で構成されます。次に、プログラムはすべての異なる組み合わせを調べて、可能な金額を出力します。
助けが必要な部分は nextCombination メソッドです。今のところ、ランダムな組み合わせの生成を使用しているため、大きな数値に対して不正確で一貫性のない出力が得られます。これを行うための体系的な方法を作成する方法を知りたいです。
「2」を入力する例を次に示します。
> Enter the length of the combination: 2
> FT
> FF
> TF
> TT
> Number of combinations: 4
組み合わせクラスは次のとおりです。
public class Combination {
private int number;
private boolean[] values;
public Combination(int number) {
this.number = number;
values = new boolean[number];
}
public Combination(boolean[] values) {
this.number = values.length;
this.values = values;
}
public void setValue(int i, boolean value) {
values[i] = value;
}
@Override
public boolean equals(Object o) {
if (o instanceof Combination) {
if (((Combination) o).number != number) {
return false;
}
for (int i = 0; i < ((Combination) o).number; i++) {
if (values[i] != ((Combination) o).values[i]) {
return false;
}
}
return true;
}
return super.equals(o);
}
@Override
public String toString() {
String s = "";
for (boolean b : values) {
s = s + (b ? "T" : "F");
}
return s;
}
}
メインクラスは次のとおりです。
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private final static int MAXIMUM_ATTEMPTS = 500;
private static int attempts;
private static int number;
private static ArrayList<Combination> cache = new ArrayList<Combination>();
private static Scanner myScanner = new Scanner(System.in);
public static void main(String... s) {
System.out.print("Enter the length of the combination: ");
number = myScanner.nextInt();
Combination combination = nextCombination();
while (combination != null) {
if (!hasCombinationBeenUsed(combination)) {
cache.add(combination);
System.out.println(combination);
}
combination = nextCombination();
}
System.out.println("Number of combinations: " + Integer.toString(cache.size()));
}
private static Combination nextCombination() {
boolean[] values = new boolean[number];
for (int i = 0; i < number; i++) {
values[(int) (Math.random() * number)] = ((int) (Math.random() * (2))) == 1;
}
Combination combo = new Combination(values);
if (!hasCombinationBeenUsed(combo)) {
return combo;
} else if (attempts < MAXIMUM_ATTEMPTS) {
attempts++;
return nextCombination();
} else {
return null;
}
}
private static boolean hasCombinationBeenUsed(Combination combo) {
for (Combination c : cache) {
if (c.equals(combo)) {
return true;
}
}
return false;
}
}
私のコードをより良く/より短く/より効率的にすることができれば、私もそれを望みます。ありがとう :)
編集: 私はまだ 15 歳なので、学校に行ったことはありません。あまり厳しくしないでください。