How do I test delete() in the class growingArray - java

I'm learning the Growing Array in Java, and I implemented the method delete() in the following Code.
Now I want to test this method for a example array [1,2,3,4,5,6,7]
What do I have to write in the Main method?
import java.util.Arrays;
public abstract class GrowingArray {
protected Object[] array;
protected static final int primaryQty = 10;
protected static final int secondaryQty = 5;
protected int index = 0;
public GrowingArray() {
array = new Object[primaryQty];
}
public GrowingArray(int size) {
array = new Object[size];
}
protected void grow() {
int oldsize = array.length;
int newsize = oldsize + secondaryQty;
Object[] loc = new Object[newsize];
for (int i = 0; i < oldsize; i++)
loc[i] = array[i];
array = loc;
}
public Object get(int at) {
return array[at];
}
public int getLength() {
return array.length;
}
public void add(Object obj) {
if (index < array.length)
array[index++] = obj;
else {
grow();
array[index++] = obj;
}
}
public void delete(int x) {
for (int i = x; i < array.length; i++) {
if (i == array.length - 1) {
array[i] = null;
System.out.println(array.toString());
} else {
array[i] = array[i + 1];
System.out.println(array.toString());
}
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GrowingArray) {
return Arrays.equals(array, ((GrowingArray) obj).array);
}
return false;
}
#Override
public String toString() {
return Arrays.toString(array);
}
public static void main(String args[]) {
//test ?????
}
}

Your class is abstract. Remove abstract from the class definition.

Related

How to display all elements in a Prefix tree?

I'm trying to print all the word in my prefix tree. I can insert, it's working, but when I try to print all elements of the tree using a preorder way it just gets all messed up. There's some problem on the recursive method PREORDER that I'm using to display all elements.
How can I recursively display all the word on my prefix tree???
public class TrieMain {
public static void main(String[] args) {
TrieTree tree = new TrieTree();
tree.treeInsert("cat");
tree.treeInsert("cattle");
tree.treeInsert("hell");
tree.treeInsert("hello");
tree.treeInsert("rip");
tree.treeInsert("rap");
tree.preorder(tree.getRoot(), "");
}
}
public class TrieTree {
private TrieNode root;
private int wordCount;
public TrieTree() {
this.root = null;
this.wordCount = 0;
}
public TrieNode getRoot() {
return this.root;
}
public void setRoot(TrieNode newRoot) {
this.root = newRoot;
}
public int getWordCount() {
return this.wordCount;
}
public void preorder(TrieNode root, String prefix) {
if (root.getTerminal()) {
System.out.println(prefix);
}
for (int i = 0; i < 26; i++) {
if (root.getCharacters()[i] != '\u0000') {
prefix += root.getCharacters()[i];
preorder(root.getPointers()[i], prefix);
}
}
}
public boolean treeInsert(String word) {
if (this.root == null) {
this.root = new TrieNode();
}
TrieNode temp;
temp = this.root;
int lengthWord = word.length();
for (int i = 0; i < lengthWord; i++) {
int index = getIndex(word.charAt(i));
if (temp.getCharacters()[index] == '\u0000') {
temp.getCharacters()[index] = word.charAt(i);
temp.getPointers()[index] = new TrieNode();
}
temp = temp.getPointers()[index];
}
if (temp.getTerminal()) {
return false;
}
else {
temp.setTerminal(true);
return true;
}
}
public int getIndex(char character) {
int index = ((int) character) - 97;
return index;
}
}
public class TrieNode {
private final int NUM_CHARS = 26;
private char[] characters;
private TrieNode[] pointers;
private boolean terminal;
public TrieNode() {
this.characters = new char[this.NUM_CHARS];
this.pointers = new TrieNode[this.NUM_CHARS];
for (int i = 0; i < this.NUM_CHARS; i++) {
this.characters[i] = '\u0000';
this.pointers[i] = null;
}
this.terminal = false;
}
public char[] getCharacters() {
return this.characters;
}
public TrieNode[] getPointers() {
return this.pointers;
}
public boolean getTerminal() {
return this.terminal;
}
public void setTerminal(boolean newTerminal) {
this.terminal = newTerminal;
}
}

Can I add elements to a java queue using array without defining the front and the rear? I am having trouble with this

I am having trouble using enqueue and dequeue functions. I want to add elements without defining the front and rear in my scope.
public class MyStaticQueue
{
private int items[] ;
private int noOfItems = 0;
private int maxItems;
public MyStaticQueue(int m)
{
this.maxItems = m;
this.items = new int[maxItems];
this.noOfItems = 0;
}
public boolean isEmpty()
{
if(noOfItems == 0)
{
return true;
}
else
{
return false;
}
}
public int first()
{
return items[0];
}
public void add(int item)
{
for (int i=0; i<items[maxItems]; i++)
{
if (items[i] == 0)
{
items[i] = item;
}
noOfItems++;
}
}
}

mostFrequent method bags adt(abstract data types)

I am trying to implement a method named mostFrequent in a bag that finds the most frequent object in a bag For example, if B = {Bob, Joe, Bob, Ned, Bob, Bob}, then the method
returns Bob. Hint: The method is O(n^2).
public E MostFrequent (Bag<E> B){
// implementation here
}
The adt of the bag is the following:
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();
}
}
the method must be implemented in the most efficient way and if possible using the methods already given in the bag adt
What I've been trying is the following:
public E MostFrequent(Bag<E> B){
for(E e : B){
int counter = B.count(e)
}
}
but I don't seem to think of a way to return the object with more frequencies inside the loop

Java Hashtable Chaining

I am supposed to write a Java Hashtable function being able to import java.util.Iterator, java.util.NoSuchElementException, and java.util.ConcurrentModificationException. There is no specific on what type of Hashing function to use. SO how do I write my getHashCode function. My code so far:
package data_structures;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import data_structures.LinkedListDS.IteratorHelper;
public class Hashtable<K,V> implements DictionaryADT<K,V> {
private int currentSize,maxSize,tableSize;
private long modCounter;
private LinkedListDS <DictionaryNode<K,V>> [] list;
class DictionaryNode<K,V> implements Comparable<DictionaryNode<K,V>> {
K key;
V value;
public DictionaryNode(K k, V v) {
key = k;
value = v;
}
public int compareTo(DictionaryNode<K,V> node) {
return ((Comparable<K>)key).compareTo((K)node.key);
}
}
public Hashtable(int n) {
currentSize = 0;
maxSize = n;
modCounter = 0;
tableSize = (int) (maxSize * 1.3f);
list = new LinkedListDS[tableSize];
for (int i=0; i < tableSize; i++)
list[i] = new LinkedListDS<DictionaryNode<K,V>>();
}
public boolean contains(K key) {
return list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null));
}
private int getHashCode(K key) {
// TODO Auto-generated method stub
return 0;
}
public boolean insert(K key, V value) {
if (isFull())
return false;
if (list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].addLast(new DictionaryNode<K,V>(key,value));
currentSize++;
modCounter++;
return true;
}
#Override
public boolean remove(K key) {
if (isEmpty())
return false;
if (!list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].remove(new DictionaryNode<K,V>(key,null));
currentSize--;
modCounter++;
return true;
}
public V getValue(K key) {
DictionaryNode<K,V> tmp = list[getHashCode(key)].find(new DictionaryNode<K,V>(key,null));
if (tmp == null)
return null;
return tmp.value;
}
#Override
public K getKey(V value) {
DictionaryNode<K,V> tmp = list[getHashCode(value)].find(new DictionaryNode<K,V>(null,value));
if (tmp == null)
return null;
return tmp.key;
}
public int size() {
return currentSize;
}
#Override
public boolean isFull() {
return currentSize == maxSize;
}
public boolean isEmpty() {
return currentSize == 0;
}
#Override
public void clear() {
currentSize = 0;
modCounter++;
for (int i=0; i<tableSize; i++)
list[i].makeEmpty();
}
public Iterator<K> keys() {
return new KeyIteratorHelper();
}
public Iterator<V> values() {
return new ValueIteratorHelper();
}
abstract class IteratorHelper<E> implements Iterator<E> {
protected DictionaryNode<K,V> [] nodes;
protected int idx;
protected long modCheck;
public IteratorHelper() {
nodes = new DictionaryNode[currentSize];
idx = 0;
int j = 0;
for (int i=0; i < tableSize; i++)
for (DictionaryNode n : list[i])
nodes[j++] = n;
nodes = (DictionaryNode<K,V>[]) ObjectSorter.quickSort(nodes);
}
public boolean hasNext() {
if (modCheck != modCounter)
throw new ConcurrentModificationException();
return idx < currentSize;
}
public abstract E next();
public void remove() {
throw new UnsupportedOperationException();
}
}
class KeyIteratorHelper<K> extends IteratorHelper<K> {
public KeyIteratorHelper() {
super();
}
public K next() {
return (K) nodes[idx++].key;
}
}
class ValueIteratorHelper<V> extends IteratorHelper<V> {
public ValueIteratorHelper() {
super();
}
public V next() {
return (V) nodes[idx++].value;
}
}
}

Problem Adding incremented class member variable to arraylist inside loop

Trying to add an incremented class member variable 'nNodeIndex' to arraylist, but at the end of the loop all the values stored are identical to the last iteration increment??
Class with member variable:
import java.util.ArrayList;
public class Graph {
private static ArrayList<GraphNode> Nodes = new ArrayList<GraphNode>();
private static ArrayList<GraphEdge> Edges = new ArrayList<GraphEdge>();
private static boolean diGraph;
private static int nNodeIndex;
private boolean uniqueEdge(int from, int to)
{
for(int i=0; i< Edges.size(); i++){
if(Edges.get(i).from() == from && Edges.get(i).to() == to)
return false;
}
return true;
}
private void removeInvalidEdges(int nodeIndex)
{
for(int i=0; i<Edges.size(); i++)
{
if(Edges.get(i).from() == nodeIndex)
Edges.remove(i);
if(Edges.get(i).to() == nodeIndex)
Edges.remove(i);
}
}
Graph(boolean directionalGraph)
{
diGraph = directionalGraph;
nNodeIndex = 1;
}
public GraphNode getNode(int nodeIndex)
{
return Nodes.get(nodeIndex);
}
public int getIndexByVector(int x, int y)
{
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).x() == x && Nodes.get(i).y() == y)
return i;
}
return -1;
}
public int nextFreeNodeIndex(){ return nNodeIndex; }
public void addNode(GraphNode node)
{
if(Nodes.size() > 0)
Nodes.add(node.index()-1, node);
else
Nodes.add(node);
nNodeIndex++;
}
public void removeNode(int index)
{
Nodes.get(index).setIndex(-1);
removeInvalidEdges(index);
}
public void addEdge(GraphEdge edge)
{
if(uniqueEdge(edge.from(), edge.to()))
Edges.add(edge);
if(!diGraph)
{
if(uniqueEdge(edge.to(), edge.from()))
Edges.add(new GraphEdge(edge.to(), edge.from()));
}
}
public void removeEdge(GraphEdge edge)
{
for(int i=0; i<Edges.size(); i++)
if(Edges.get(i).from() == edge.from() &&
Edges.get(i).to() == edge.to())
{
Edges.remove(i);
}
}
public int totalNodes(){ return Nodes.size(); }
public int totalEdges(){ return Edges.size(); }
public int nActiveNodes()
{
int count = 0;
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).index() != -1 )
count++;
}
return count;
}
public void reset()
{
nNodeIndex = 1;
Nodes.clear();
Edges.clear();
}
}
Use within main class:
for(int row = 1; row <= boardWidth; row++){
for(int col = 1; col <= boardHeight; col++){
graph.addNode(new GraphNode(graph.nextFreeNodeIndex(), row, col));
}
}
Graph Node class:
public class GraphNode extends Square {
private static int indexNum;
GraphNode(int n, int x, int y)
{
super(x,y);
indexNum = n;
}
public int index(){ return indexNum; }
public void setIndex(int index){ indexNum = index; }
}
Do you need to show us the GraphNode class? I wonder if the node index held by it (set by the first parameter passed in its constructor) is a static variable.

Categories