バッグ内で最も頻度の高いオブジェクトを見つける、バッグ内の mostFrequent という名前のメソッドを実装しようとしています。たとえば、B = {Bob、Joe、Bob、Ned、Bob、Bob} の場合、メソッドは Bob を返します。ヒント: メソッドは O(n^2) です。
public E MostFrequent (Bag<E> B){
// implementation here
}
バッグの広告は次のとおりです。
package edu.uprm.ece.icom4035.bag;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StaticBag implements Bag {
private int currentSize;
private Object elements[];
private class BagIterator implements Iterator {
private int currentPosition;
public BagIterator(){
this.currentPosition = 0;
}
@Override
public boolean hasNext() {
return this.currentPosition < currentSize;
}
@Override
public Object next() {
if (hasNext()){
return elements[this.currentPosition++];
}
else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public StaticBag(int maxSize){
if (maxSize < 1){
throw new IllegalArgumentException("Max size must be at least 1.");
}
this.currentSize = 0;
this.elements = new Object[maxSize];
}
@Override
public void add(Object obj) {
if (obj == null){
throw new IllegalArgumentException("Value cannot be null.");
}
else if (this.size() == this.elements.length){
throw new IllegalStateException("Bag is full.");
}
else {
this.elements[this.currentSize++] = obj;
}
}
@Override
public boolean erase(Object obj) {
int target = -1;
for (int i=0; i < this.size(); ++i){
if (this.elements[i].equals(obj)){
target = i;
break;
}
}
if (target == -1){
return false;
}
else {
this.elements[target] = this.elements[this.currentSize-1];
this.elements[this.currentSize-1] = null;
this.currentSize--;
return true;
}
}
@Override
public int eraseAll(Object obj) {
int copies = 0;
while(this.erase(obj)){
copies++;
}
return copies;
}
@Override
public int count(Object obj) {
int counter = 0;
for (int i=0; i < this.size(); ++i){
if (elements[i].equals(obj)){
counter++;
}
}
return counter;
}
@Override
public void clear() {
for (int i=0; i < this.size(); ++i){
this.elements[i] = null;
}
this.currentSize = 0;
}
@Override
public boolean isEmpty() {
return this.size() == 0;
}
@Override
public int size() {
return this.currentSize;
}
@Override
public boolean isMember(Object obj) {
return this.count(obj) > 0;
}
@Override
public Iterator iterator() {
return new BagIterator();
}
}
メソッドは最も効率的な方法で実装する必要があり、可能であれば、バッグ adt で既に指定されているメソッドを使用する必要があります
私が試してきたのは次のとおりです。
public E MostFrequent(Bag<E> B){
for(E e : B){
int counter = B.count(e)
}
}
しかし、ループ内でより多くの周波数でオブジェクトを返す方法を考えていないようです