私はオブジェクト指向プログラミングには新しく、概念を使用する私のプログラムの設計に少し問題があります。私はチュートリアルを行ったが、まだ問題がある。クラス変数をカウントするデザインの問題
私は、項目の値をとる(この例では何も、株式ことができる)と(このコード100で)特定の値を等しくするために必要なそれらのどのような数の割り出し再帰を持っています。この部分は機能しますが、在庫の重み付けがしきい値を超えているかどうかを知りたいと思います。もともと、私はforループを行い、値のリスト全体を計算する方法でこの問題に近づいたが、これは再帰のすべてのループでそれを実行するので非常に効率が悪い。私はクラスを使って状態情報を保持し、各ループの値を増やすことができるので、クラスを学習しようとすると良い時だと思っていました。
私は、コードを持っていると思うが、私は完全にクラスで、この問題をどのように設計するかを理解していません。これまでは、再帰の各段階でループを実行しています。なぜなら、私は当初そこのクラスでしたからです。これを設計するより良い方法はありますか?私の最終目標は、重み付けが超過したときに通知されることです(これはやや前もってできます)が、最小限のリソースを使用するようにしたい(非効率的/不要なループを避ける)
コードコード全体)私は学ぶために使用されていますが、問題はカウンターのクラスとfindVariablesメソッド内の位置である:
import java.util.Arrays;
public class LearningClassCounting {
public static int[] stock_price = new int[]{ 20,5,20};
public static int target = 100;
public static void main(String[] args) {
// takes items from the first list
findVariables(stock_price, 100, new int[] {0,0,0}, 0, 0);
}
public static void findVariables(int[] constants, int sum,
int[] variables, int n, int result) {
Counter Checker = new Counter(stock_price, variables);
if (n == constants.length) {
if (result == sum) {
System.out.println(Arrays.toString(variables));
}
} else if (result <= sum){ //keep going
for (int i = 0; i <= 100; i++) {
variables[n] = i;
Checker.check_total_percent(n, i);
findVariables(constants, sum, variables, n+1, result+constants[n]*i);
}
}
}
}
class Counter {
private int[] stock_price;
private int[] variables;
private int value_so_far;
public Counter(int[] stock_price, int[] variables) {
this.stock_price = stock_price;
this.variables = variables;
for (int location = 0; location < variables.length; location++) {
//System.out.println(variables[location] + " * " + stock_price[location] + " = " + (variables[location] * stock_price[location]));
value_so_far = value_so_far + (variables[location] * stock_price[location]);
}
//System.out.println("Total value so far is " + value_so_far);
//System.out.println("************");
}
public void check_total_percent(int current_location, int percent) {
// Check to see if weight exceeds threshold
//System.out.println("we are at " + current_location + " and " + percent + " and " + Arrays.toString(variables));
//System.out.println("value is " + stock_price[current_location] * percent);
//formula I think I need to use is:
if (percent == 0) {
return;
}
int current_value = (stock_price[current_location] * percent);
int overall_percent = current_value/(value_so_far + current_value);
if (overall_percent > 50) {
System.out.println("item " + current_location + " is over 50%");
}
}
}
このコードを正しく読むためには、 'findVariables'メソッドは' {20,5,20} 'の集合から100を越える株式追加の集合を決定することになっていますか?それは貪欲なアルゴリズムの一種ですか?このコードは全く読むのが簡単ではありません。 – Tejs
@Tejsはい正しい。クラスのデザインを理解するために私が見つけたサンプル。コードの見た目を残念に思って、私はかなり新しい(そして自分自身のためのコードですが)ポインタがあれば、私はdefになります。コードを読みやすくするためにそれらを適用してください。 –