3

そのため、次の質問に対する答えを概念化するのに非常に苦労しています。私は答えを探しているのではなく、自分で答えを提示できるようにするために実行できる便利な手順を探しています. 注: これらの質問に答えるために、参照されるクラスとドライバー プログラムが与えられます。質問は次のとおりです。

Q.1 現在バッグ内にある任意のオブジェクトを特定のオブジェクトに置き換えて返す ADT バッグのメソッド replace を実装してください。

Q.2. ArrayBag 内の要素のすべてのインスタンスを削除する remove メソッドを作成します。

Q.3. 固定バッグが適切な状況の例を少なくとも 2 つ、サイズ変更可能なバッグが適切な状況の例を 2 つ挙げてください。

次のコードは私が始めたものですが、正しい方向に進んでいるかどうかはわかりません:

a.1 public T replace(T theItem) {
    Random generator = new Random();
    int randomPosition = generator.nextInt(numberOfEntries);

    T result = null;

    if (!isEmpty() && (randomPosition >= 0)) {
        result = bag[randomPosition]; // Entry to remove
        bag[randomPosition] = theItem; // Replace entry to remove with
                                // last entry

    }
    return result;
 a.2 public void clear(T theItem) {
    while (!this.isEmpty(ArrayBag))
        this.remove();

 a.3 not sure it should be related to coding examples or something else.

さらに、ArrayBag のクラスは参照用に以下に示します。

import java.util.Arrays;
import java.util.Random;

public final class ArrayBag<T> implements  BagInterface<T> {
private final T[] bag;
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;

/** Creates an empty bag whose initial capacity is 25. */
public ArrayBag() {
    this(DEFAULT_CAPACITY);
} // end default constructor

/**
 * Creates an empty bag having a given capacity.
 * 
 * @param desiredCapacity
 *            The integer capacity desired.
 */
public ArrayBag(int desiredCapacity) {
    if (desiredCapacity <= MAX_CAPACITY) {
        // The cast is safe because the new array contains null entries
        @SuppressWarnings("unchecked")
        T[] tempBag = (T[]) new Object[desiredCapacity]; // Unchecked cast
        bag = tempBag;
        numberOfEntries = 0;
        initialized = true;
    } else
        throw new IllegalStateException("Attempt to create a bag "
                + "whose capacity exceeds " + "allowed maximum.");
  } // end constructor

  /**
   * Adds a new entry to this bag.
   * 
   * @param newEntry
  *            The object to be added as a new entry.
  * @return True if the addition is successful, or false if not.
 * /
  public boolean add(T newEntry) {
    checkInitialization();
    boolean result = true;
    if (isArrayFull()) {
        result = false;
    } else { // Assertion: result is true here
        bag[numberOfEntries] = newEntry;
        numberOfEntries++;
    } // end if

    return result;
  } // end add

 /**
 * Retrieves all entries that are in this bag.
 * 
 * @return A newly allocated array of all the entries in this bag.
 */
public T[] toArray() {
    checkInitialization();

    // The cast is safe because the new array contains null entries.
    @SuppressWarnings("unchecked")
    T[] result = (T[]) new Object[numberOfEntries]; // Unchecked cast

    for (int index = 0; index < numberOfEntries; index++) {
        result[index] = bag[index];
    } // end for

    return result;
    // Note: The body of this method could consist of one return statement,
    // if you call Arrays.copyOf
} // end toArray

/**
 * Sees whether this bag is empty.
 * 
 * @return True if this bag is empty, or false if not.
 */
public boolean isEmpty() {
    return numberOfEntries == 0;
} // end isEmpty

/**
 * Gets the current number of entries in this bag.
 * 
 * @return The integer number of entries currently in this bag.
 */
public int getCurrentSize() {
    return numberOfEntries;
} // end getCurrentSize

/**
 * Counts the number of times a given entry appears in this bag.
 * 
 * @param anEntry
 *            The entry to be counted.
 * @return The number of times anEntry appears in this ba.
 */
public int getFrequencyOf(T anEntry) {
    checkInitialization();
    int counter = 0;

    for (int index = 0; index < numberOfEntries; index++) {
        if (anEntry.equals(bag[index])) {
            counter++;
        } // end if
    } // end for

    return counter;
} // end getFrequencyOf

/**
 * Tests whether this bag contains a given entry.
 * 
 * @param anEntry
 *            The entry to locate.
 * @return True if this bag contains anEntry, or false otherwise.
 */
public boolean contains(T anEntry) {
    checkInitialization();
    return getIndexOf(anEntry) > -1; // or >= 0
} // end contains

/** Removes all entries from this bag. */
public void clear() {
    while (!this.isEmpty())
        this.remove();
} // end clear

/**
 * Removes one unspecified entry from this bag, if possible.
 * 
 * @return Either the removed entry, if the removal was successful, or null.
 */
public T remove() {
    checkInitialization();
    T result = removeEntry(numberOfEntries - 1);
    return result;
} // end remove

/**
 * Removes one occurrence of a given entry from this bag.
 * 
 * @param anEntry
 *            The entry to be removed.
 * @return True if the removal was successful, or false if not.
 */
public boolean remove(T anEntry) {
    checkInitialization();
    int index = getIndexOf(anEntry);
    T result = removeEntry(index);
    return anEntry.equals(result);
} // end remove

public boolean removeRandom() {
    Random generator = new Random();
    int randomPosition = generator.nextInt(numberOfEntries);
    T result = removeEntry(randomPosition);
    if (result == null) {
        return false;
    } else {
        return true;
    }

}

@Override
public boolean equals(Object obj) {
    if (obj instanceof ArrayBag) {
        ArrayBag<T> otherArrayBag = (ArrayBag<T>) obj;

        if (numberOfEntries == otherArrayBag.numberOfEntries) {

            // I create new arrays so that I can manipulate them
            // and it will not alter this.bag or otherArrayBag.bag
            T[] currentBagTempArray = toArray();
            T[] otherBagTempArray = otherArrayBag.toArray();

            Arrays.sort(currentBagTempArray);
            Arrays.sort(otherBagTempArray);

            for (int i = 0; i < numberOfEntries; i++) {
                if (!currentBagTempArray[i].equals(otherBagTempArray[i])) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }
}

public ResizableArrayBag<T> createResizableArray() {
    T[] currentBagContents = toArray();
    ResizableArrayBag<T> newBag = new ResizableArrayBag<T>(currentBagContents);
    return newBag;
}

// Returns true if the array bag is full, or false if not.
private boolean isArrayFull() {
    return numberOfEntries >= bag.length;
} // end isArrayFull

// Locates a given entry within the array bag.
// Returns the index of the entry, if located,
// or -1 otherwise.
// Precondition: checkInitialization has been called.
private int getIndexOf(T anEntry) {
    int where = -1;
    boolean found = false;
    int index = 0;

    while (!found && (index < numberOfEntries)) {
        if (anEntry.equals(bag[index])) {
            found = true;
            where = index;
        } // end if
        index++;
    } // end while

    // Assertion: If where > -1, anEntry is in the array bag, and it
    // equals bag[where]; otherwise, anEntry is not in the array.

    return where;
} // end getIndexOf

// Removes and returns the entry at a given index within the array.
// If no such entry exists, returns null.
// Precondition: 0 <= givenIndex < numberOfEntries.
// Precondition: checkInitialization has been called.
private T removeEntry(int givenIndex) {
    T result = null;

    if (!isEmpty() && (givenIndex >= 0)) {
        result = bag[givenIndex]; // Entry to remove
        int lastIndex = numberOfEntries - 1;
        bag[givenIndex] = bag[lastIndex]; // Replace entry to remove with
                                            // last entry
        bag[lastIndex] = null; // Remove reference to last entry
        numberOfEntries--;
    } // end if

    return result;
} // end removeEntry

// Throws an exception if this object is not initialized.
private void checkInitialization() {
    if (!initialized)
        throw new SecurityException(
                "ArrayBag object is not initialized properly.");
} // end checkInitialization

} // ArrayBag を終了します

4

2 に答える 2

1

他の誰かがBag Class Implementation in Java/Using Array で Array を使用して Bag を実装しました。コードをちらりと見ただけなので、混合バッグかもしれません。

同じオブジェクトを複数回格納できることを除けば、Bag は Set のようなものだと思います。ある種のプライベート コレクション (おそらく上記のような配列) を実装したいと思うでしょう。myBagとしましょう。ジェネリック型 T を使用しているため、 Bag には型 T のオブジェクトのみが含まれます

Q1 の場合、replace() メソッドは 2 つのパラメーターを取る必要がある場合がありfindMeます。置き換えられるオブジェクト (たとえば ) と、置き換えるオブジェクト (たとえばreplacement) です。バッグに重複を保持できる場合は、一致する最初のオブジェクトを置き換えたいと思うでしょう。Random() を使用するのではなく、myBag を介して要素ごとに移動し、見つかった要素を置き換える要素に置き換える必要がある場合があります。findMeが見つからない場合は、エラーをスローすることができます。したがって、メソッド宣言は次のようになります。

public boolean replace(T findMe, T replacement)

findMeが見つかった場合は true、そうでない場合は false を返します。

Q2 では、myBag のサイズが > 0 のときに myBag の最初の要素を削除する while ループを作成できます。

第 3 四半期については、コーディングは含まれていません。これは思考の問題です。一般に、固定サイズのバッグは、サイズが最初から変わらないことがわかっている場合に役立ちます。

サイズ変更可能なバッグは、クラスの待機リストなど、最初はサイズがわからず、縮小または拡大する可能性が高い場合に適しています。

于 2015-02-05T21:44:14.803 に答える
0

開始コードとクラスを見ましたが、実行しませんでした。しかし、あなたは正しい方向に進んでいると言えます。

Q2の場合、配列内の特定の要素を検索し、それぞれを削除する必要があります。質問は「要素のすべてのインスタンスを削除する」と明確に言っているため、 getIndexOf() メソッドを確認してください。検索と要素の方法を確認できます。一致するものを見つけたら、それを削除します。反復処理中に要素を削除する場合は注意してください。反復中に 1 つの要素を削除すると、サイズが変わります。一致する各一致を配列に格納することをお勧めします。繰り返しの後、見つかった要素ごとに remove(index) メソッドを使用します

Give at least two examples of a situation where a fixed bag is appropriate and two examples of a situation where a resizable bag is appropriate.

この項目について、説明とサンプル コードまたはアルゴリズムを追加できます。私はあなたに2つのことを提供できます:

1.  If the array is not getting full too fast fixed size is good. But if array is getting full too fast you should resize new array and copy all elements again and again. Overhead amount is important.
2. Amount of capacity is important. How you will decide initial size ? Big size or small size ? Think that

これが役立つことを願っています

于 2015-02-05T21:12:32.233 に答える