ローカルコミュニティカレッジでJavaクラスを使用してデータ構造とアルゴリズムを使用していますが、私は現在の宿題に完全に固執しています。問題は次のとおりです。欲張りアルゴリズムJava/firstFitメソッド
さまざまな重みのオブジェクトをコンテナにパックするプログラムを作成します。各容器は最大10ポンドを保持できます。
このプログラムでは、欲しいアルゴリズムを使用して、オブジェクトが収まる最初のビンにオブジェクトを配置します。
私は自分の宿題が私のために行われることを求めているわけではありません。正しい方向を指し示すことを本当に望んでいます。私はプログラムが本当に仕事に近いですが、私はそれを100%正しく機能させることができません。私は正しい量の重量を保持する最初の容器を得ることができますが、その後、残りの容器はコンテナ当たり1つの重量値を保持します。ここで
import java.util.ArrayList;
public class Lab20 {
public static void main(String[] args) {
final java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the number of objects: ");
double[] items = new double[input.nextInt()];
System.out.print("Enter the weight of the objects: ");
for (int i = 0; i < items.length; i++) {
items[i] = input.nextDouble();
}
ArrayList<Bin> containers = firstFit(items);
//Display results
for (int i = 0; i < containers.size(); i++) {
System.out.println("Container " + (i + 1)
+ " contains objects with weight " + containers.get(i));
}
input.close();
}
//Greedy Algorithm??
public static ArrayList<Bin> firstFit(double[] items) {
ArrayList<Bin> list = new ArrayList<>();
Bin bin = new Bin();
list.add(bin);
for (int i = 0; i < items.length; i++) {
if (!bin.addItem(items[i])) {
Bin bin2 = new Bin();
list.add(bin2);
bin2.addItem(items[i]);
}
}
return list;
}
}
//Bin Class
class Bin {
private ArrayList<Double> objects = new ArrayList<>();
private double maxWeight = 10;
private double totalWeight = 0;
public Bin() {
}
public Bin(double maxWeight) {
this.maxWeight = maxWeight;
}
//Or is this supposed to be the Greedy algorithm??
public boolean addItem(double weight) {
if ((totalWeight+weight) <= maxWeight) {
objects.add(weight);
totalWeight += weight;
return true;
}
else {
return false;
}
}
public int getNumberOfObjects() {
return objects.size();
}
@Override
public String toString() {
return objects.toString();
}
}
そして、ここでは私が取得しています出力されます....私がこれまで持っているものです...
は、オブジェクトの数を入力します。6
の重量を入力します。オブジェクト:7 5 2 3 5 8
容器1は、容器2の重量を有するオブジェクトが含ま
重量[2.0 7.0]を持つオブジェクトが含まれている[5.0]
容器3は、重量を持つオブジェクトが含まれている[3.0]
容器4重量を持つオブジェクトが含まれている[5.0]
容器5重量を持つオブジェクトが含まれている[8.0]
そして、これは何ですか出力は...
オブジェクトの数を入力してください:6
オブジェクトの重量:7 5 2 3 5 8
容器1は重量でオブジェクトが含ま[7.0、2.0]
容器2は、重量でオブジェクトが含ま[5.0、3.0]
容器3を持つオブジェクトが含まれてい重量[5.0]
コンテナ4は、あなたのfirstFit方法に問題があります重量[8.0]
外部ループの次の繰り返しに直接進むには、 'break'の代わりに' continue items_loop; 'というラベルを付けて' added'変数を取り除くことができます。 – Thilo