Automatic increment array java - java

Hello I have got this basically fully working sorted vector , the problem here is however that I can only initialize the array to a fixed size before inserting any values , so for example I can initialize 5 but if I want to insert 6 items it gives me a null pointer exception .
I think I do understand what is happening however I would like anybody to show me a solution how the array size can be increased automatically every time I want to insert something .
( Without having to use any inbuilt java functionalities like ArrayList )
Thank you
package ads2;
public class SortedVector2
{
private int length;
private int maximum;
private int growby;
private int temp;
private int x = 0;
private int high;
private int middle;
private int low;
String[] data;
public SortedVector2()
{
length = 0;
maximum = 5;
data = new String[maximum];
}
public void AddItem(String value)
{
/*if (length == maximum)
{
maximum += 200000;
*/
data[length] = value;
length++;
// SetSorted();
// SetSorted(data);
}
public void SetSorted()
{
for (int j = 0; j < data.length - 1; j++) {
if (data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (String s : data) {
System.out.println(s);
}
// private String[] data;
/*
for(int i = data.length-1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
} for (String s : data) {
System.out.println(s);
}
*/
}
public void SetGrowBy(int growby)
{
maximum += growby;
}
public int GetCapacity()
{
return maximum;
}
public int GetNoOfItems()
{
return length;
}
public String GetItemByIndex(int index)
{
return data[index];
}
public int FindItem(String search)
{
for (x=0;x<=length; )
{
middle =((low + high)/2);
if (data[middle].compareTo(search)==0)
{
return middle;
}
else if (data[middle].compareTo(search)<0)
{
low = middle;
x++;
return FindItem(search);
}
else
{
high = middle;
x++;
return FindItem(search);
}
}
return -1;
}
public boolean Exists(String search)
{
boolean output;
int y;
y = 0;
while (data[y] != search && (length - 1) > y)
{
++y;
}
if (data[y] == search)
{
output = true;
} else
{
output = false;
}
y = 0;
return output;
}
public void InsertItem(int index, String value)
{
if (length == maximum)
{
maximum += 200000;
}
for(int i = length - 1; i >= index; --i)
{
data[i + 1] = data[i];
}
data[index] = value;
length++;
}
public void DeleteItem(int index)
{
for(int x = index; x < length - 2; ++x)
{
data[x] = data[x + 1];
}
length--;
}
public String toString()
{
String res = "";
for (int i=0; i<length; i++)
res+=data[i] + "; ";
return res;
}
}

You have to do what the implementers of ArrayList did. When you try to add an element when the array is full, you create a larger array, copy the existing elements to it and add the new element.

To increase array size dynamically use Collection framework interface List,
It has implementation ArrayList,Vector and LinkedList use any one in them.
Or, Simply create copyArray(String[]) api which will give you array with increased capacity.
public String[] copyArray(String[] oldArray){
int capacity = oldArray.length * 2;
return Arrays.copyOf(oldArray, capacity);
}
String[] data = copyArray(data) // pass array

I think you've got all the basic variables you need to do what you need to do: just check if the size equals the capacity when you are adding an item and if it does reallocate the array:
if (size == capacity) {
capacity += growby;
data = Arrays.copyOf(data, capacity);
}
That's pretty much all ArrayList does.

You need to re-allocate when increasing the size of the data buffer, for example,
public void InsertItem(int index, String value)
{
String[] data2;
if (length == (maximum-1))
{
maximum += 5; // increment size in lot of 5
data2 = new String[maximum);
for (int ii = 0; ii < length; ii++)
{
data2[ii] = date[ii];
}
data = data2; // re-assign with increased size
}
for(int i = length - 1; i >= index; --i)
{
data[i + 1] = data[i];
}
data[index] = value;
length++;
}

In software engineering there is a saying, "Don't reinvent the wheel" - which emphasizes us on using the existing archetype. Because they are tested and used by for long period of time. So it's better to use ArrayList for regular/professional purpose.
But it if it is for learning purpose then you can chose any one from the previous answers.

Related

Finding the smallest integer that appears at least k times

You are given an array A of integers and an integer k. Implement an algorithm that determines, in linear time, the smallest integer that appears at least k times in A.
I have been struggling with this problem for awhile, coding in Java, I need to use a HashTable to find the smallest integer that appears at least k times, it also must be in linear time.
This is what I attempted but it does not pass any of the tests
private static int problem1(int[] arr, int k)
{
// Implement me!
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int ans = Integer.MAX_VALUE;
for (int i=0; i < arr.length; i++) {
if(table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
if (k <= table.get(arr[i])) {
ans = Math.min(ans, arr[i]);
}
}else{
table.put(arr[i], 1);
}
}
return ans;
}
Here is the empty code with all of the test cases:
import java.io.*;
import java.util.*;
public class Lab5
{
/**
* Problem 1: Find the smallest integer that appears at least k times.
*/
private static int problem1(int[] arr, int k)
{
// Implement me!
return 0;
}
/**
* Problem 2: Find two distinct indices i and j such that A[i] = A[j] and |i - j| <= k.
*/
private static int[] problem2(int[] arr, int k)
{
// Implement me!
int i = -1;
int j = -1;
return new int[] { i, j };
}
// ---------------------------------------------------------------------
// Do not change any of the code below!
private static final int LabNo = 5;
private static final String quarter = "Fall 2020";
private static final Random rng = new Random(123456);
private static boolean testProblem1(int[][] testCase)
{
int[] arr = testCase[0];
int k = testCase[1][0];
int answer = problem1(arr.clone(), k);
Arrays.sort(arr);
for (int i = 0, j = 0; i < arr.length; i = j)
{
for (; j < arr.length && arr[i] == arr[j]; j++) { }
if (j - i >= k)
{
return answer == arr[i];
}
}
return false; // Will never happen.
}
private static boolean testProblem2(int[][] testCase)
{
int[] arr = testCase[0];
int k = testCase[1][0];
int[] answer = problem2(arr.clone(), k);
if (answer == null || answer.length != 2)
{
return false;
}
Arrays.sort(answer);
// Check answer
int i = answer[0];
int j = answer[1];
return i != j
&& j - i <= k
&& i >= 0
&& j < arr.length
&& arr[i] == arr[j];
}
public static void main(String args[])
{
System.out.println("CS 302 -- " + quarter + " -- Lab " + LabNo);
testProblems(1);
testProblems(2);
}
private static void testProblems(int prob)
{
int noOfLines = prob == 1 ? 100000 : 500000;
System.out.println("-- -- -- -- --");
System.out.println(noOfLines + " test cases for problem " + prob + ".");
boolean passedAll = true;
for (int i = 1; i <= noOfLines; i++)
{
int[][] testCase = null;
boolean passed = false;
boolean exce = false;
try
{
switch (prob)
{
case 1:
testCase = createProblem1(i);
passed = testProblem1(testCase);
break;
case 2:
testCase = createProblem2(i);
passed = testProblem2(testCase);
break;
}
}
catch (Exception ex)
{
passed = false;
exce = true;
}
if (!passed)
{
System.out.println("Test " + i + " failed!" + (exce ? " (Exception)" : ""));
passedAll = false;
break;
}
}
if (passedAll)
{
System.out.println("All test passed.");
}
}
private static int[][] createProblem1(int testNo)
{
int size = rng.nextInt(Math.min(1000, testNo)) + 5;
int[] numbers = getRandomNumbers(size, size);
Arrays.sort(numbers);
int maxK = 0;
for (int i = 0, j = 0; i < size; i = j)
{
for (; j < size && numbers[i] == numbers[j]; j++) { }
maxK = Math.max(maxK, j - i);
}
int k = rng.nextInt(maxK) + 1;
shuffle(numbers);
return new int[][] { numbers, new int[] { k } };
}
private static int[][] createProblem2(int testNo)
{
int size = rng.nextInt(Math.min(1000, testNo)) + 5;
int[] numbers = getRandomNumbers(size, size);
int i = rng.nextInt(size);
int j = rng.nextInt(size - 1);
if (i <= j) j++;
numbers[i] = numbers[j];
return new int[][] { numbers, new int[] { Math.abs(i - j) } };
}
private static void shuffle(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int rndInd = rng.nextInt(arr.length - i) + i;
int tmp = arr[i];
arr[i] = arr[rndInd];
arr[rndInd] = tmp;
}
}
private static int[] getRandomNumbers(int range, int size)
{
int numbers[] = new int[size];
for (int i = 0; i < size; i++)
{
numbers[i] = rng.nextInt(2 * range) - range;
}
return numbers;
}
}
private static int problem1(int[] arr, int k) {
// Implement me!
Map<Integer, Integer> table = new TreeMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
if (table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
} else {
table.put(arr[i], 1);
}
}
for (Map.Entry<Integer,Integer> entry : table.entrySet()) {
//As treemap is sorted, we return the first key with value >=k.
if(entry.getValue()>=k)
return entry.getKey();
}
//Not found
return -1;
}
As others have pointed out, there are a few mistakes. First, the line where you initialize ans,
int ans = 0;
You should initialize ans to Integer.MAX_VALUE so that when you find an integer that appears at least k times for the first time that ans gets set to that integer appropriately. Second, in your for loop, there's no reason to skip the first element while iterating the array so i should be initialized to 0 instead of 1. Also, in that same line, you want to iterate through the entire array, and in your loop's condition right now you have i < k when k is not the length of the array. The length of the array is denoted by arr.length so the condition should instead be i < arr.length. Third, in this line,
if (k < table.get(arr[i])){
where you are trying to check if an integer has occurred at least k times in the array so far while iterating through the array, the < operator should be changed to <= since the keyword here is at least k times, not "more than k times". Fourth, k should never change so you can get rid of this line of code,
k = table.get(arr[i]);
After applying all of those changes, your function should look like this:
private static int problem1(int[] arr, int k)
{
// Implement me!
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int ans = Integer.MAX_VALUE;
for (int i=0; i < arr.length; i++) {
if(table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
if (k <= table.get(arr[i])) {
ans = Math.min(ans, arr[i]);
}
}else{
table.put(arr[i], 1);
}
}
return ans;
}
Pseudo code:
collect frequencies of each number in a Map<Integer, Integer> (number and its count)
set least to a large value
iterate over entries
ignore entry if its value is less than k
if entry key is less than current least, store it as least
return least
One line implementation:
private static int problem1(int[] arr, int k) {
return Arrays.stream(arr).boxed()
.collect(groupingBy(identity(), counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() >= k)
.map(Map.Entry::getKey)
.reduce(MAX_VALUE, Math::min);
}
This was able to pass all the cases! Thank you to everyone who helped!!
private static int problem1(int[] arr, int k)
{
// Implement me!
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int ans = Integer.MAX_VALUE;
for (int i=0; i < arr.length; i++) {
if(table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
}else{
table.put(arr[i], 1);
}
}
Set<Integer> keys = table.keySet();
for(int i : keys){
if(table.get(i) >= k){
ans = Math.min(ans,i);
}
}
if(ans != Integer.MAX_VALUE){
return ans;
}else{
return 0;
}
}

Keeping track of Collisions per index in an array-based hash table, as well as which values resulted in a collision using OPEN ADDRESSING ONLY

Sorry for the wordy title but it explains my question pretty well.
I am working on an assignment in Java where I need to create my own Hash Table.
The specifications are such that I must use an Array, as well as open-addressing for collision handling (with both double hashing and quadratic hashing implementations).
My implementation works quite well, and using over 200,000 randomly generated Strings I end up with only ~1400 Collisions with both types of collision handling mentioned about (keeping my load factor at 0.6 and increasing my Array by 2.1 when it goes over).
Here is where I'm stumped, however... My assignment calls for 2 specifications that I cannot figure out.
1) Have an option which, when removing a value form the table, instead of using "AVAILABLE" (replacing the index in the array with a junk value that indicates it is empty), I must find another value that previously hashed to this index and resulted in a collision. For example, if value A hashed to index 2 and value B also hashed to index 2 (and was later re-hashed to index 5 using my collision handling hash function), then removing value A will actually replace it with Value B.
2) Keep track of the maximum number of collisions in a single array index. I currently keep track of all the collisions, but there's no way for me to keep track of the collisions at an individual cell.
I was able to solve this problem using Separate Chaining by having each Array Index hold a linked list of all values that have hashed to this index, so that only the first one is retrieved when I call my get(value) method, but upon removal I can easily replace it with the next value that hashed to this index. It's also an easy way to get the max number of collisions per index.
But we were specifically told not to use separate chaining... I'm actually wondering if this is even possible without completely ruining the complexity of the hash table.
Any advice would be appreciated.
edit:
Here are some examples to give you an idea of my class structure:
public class daveHash {
//Attributes
public String[] dTable;
private double loadFactor, rehashFactor;
private int size = 0;
private String emptyMarkerScheme;
private String collisionHandlingType;
private int collisionsTotal = 0;
private int collisionsCurrent = 0;
//Constructors
public daveHash()
{
dTable = new String[17];
rehashFactor = 2.1;
loadFactor = 0.6;
emptyMarkerScheme = "A";
collisionHandlingType = "D";
}
public daveHash(int size)
{
dTable = new String[size];
rehashFactor = 2.1;
loadFactor = 0.6;
emptyMarkerScheme = "A";
collisionHandlingType = "D";
}
My hashing functions:
public long getHashCode(String s, int index)
{
if (index > s.length() - 1)
return 0;
if (index == s.length()-1)
return (long)s.charAt(index);
if (s.length() >= 20)
return ((long)s.charAt(index) + 37 * getHashCode(s, index+3));
return ((long)s.charAt(index) + 37 * getHashCode(s, index+1));
}
public int compressHashCode(long hash, int arraySize)
{
int b = nextPrime(arraySize);
int index = ((int)((7*hash) % b) % arraySize);
if (index < 0)
return index*-1;
else
return index;
}
Collision handling:
private int collisionDoubleHash(int index, long hashCode, String value, String[] table)
{
int newIndex = 0;
int q = previousPrime(table.length);
int secondFunction = (q - (int)hashCode) % q;
if (secondFunction < 0)
secondFunction = secondFunction*-1;
for (int i = 0; i < table.length; i++)
{
newIndex = (index + i*secondFunction) % table.length;
//System.out.println(newIndex);
if (isAvailable(newIndex, table))
{
table[newIndex] = value;
return newIndex;
}
}
return -1;
}
private int collisionQuadraticHash(int index, long hashCode, String value, String[] table)
{
int newIndex = 0;
for (int i = 0; i < table.length; i ++)
{
newIndex = (index + i*i) % table.length;
if (isAvailable(newIndex, table))
{
table[newIndex] = value;
return newIndex;
}
}
return -1;
}
public int collisionHandling(int index, long hashCode, String value, String[] table)
{
collisionsTotal++;
collisionsCurrent++;
if (this.collisionHandlingType.equals("D"))
return collisionDoubleHash(index, hashCode, value, table);
else if (this.collisionHandlingType.equals("Q"))
return collisionQuadraticHash(index, hashCode, value, table);
else
return -1;
}
Get, Put and Remove:
private int getIndex(String k)
{
long hashCode = getHashCode(k, 0);
int index = compressHashCode(hashCode, dTable.length);
if (dTable[index] != null && dTable[index].equals(k))
return index;
else
{
if (this.collisionHandlingType.equals("D"))
{
int newIndex = 0;
int q = previousPrime(dTable.length);
int secondFunction = (q - (int)hashCode) % q;
if (secondFunction < 0)
secondFunction = secondFunction*-1;
for (int i = 0; i < dTable.length; i++)
{
newIndex = (index + i*secondFunction) % dTable.length;
if (dTable[index] != null && dTable[newIndex].equals(k))
{
return newIndex;
}
}
}
else if (this.collisionHandlingType.equals("Q"))
{
int newIndex = 0;
for (int i = 0; i < dTable.length; i ++)
{
newIndex = (index + i*i) % dTable.length;
if (dTable[index] != null && dTable[newIndex].equals(k))
{
return newIndex;
}
}
}
return -1;
}
}
public String get(String k)
{
long hashCode = getHashCode(k, 0);
int index = compressHashCode(hashCode, dTable.length);
if (dTable[index] != null && dTable[index].equals(k))
return dTable[index];
else
{
if (this.collisionHandlingType.equals("D"))
{
int newIndex = 0;
int q = previousPrime(dTable.length);
int secondFunction = (q - (int)hashCode) % q;
if (secondFunction < 0)
secondFunction = secondFunction*-1;
for (int i = 0; i < dTable.length; i++)
{
newIndex = (index + i*secondFunction) % dTable.length;
if (dTable[index] != null && dTable[newIndex].equals(k))
{
return dTable[newIndex];
}
}
}
else if (this.collisionHandlingType.equals("Q"))
{
int newIndex = 0;
for (int i = 0; i < dTable.length; i ++)
{
newIndex = (index + i*i) % dTable.length;
if (dTable[index] != null && dTable[newIndex].equals(k))
{
return dTable[newIndex];
}
}
}
return null;
}
}
public void put(String k, String v)
{
double fullFactor = (double)this.size / (double)dTable.length;
if (fullFactor >= loadFactor)
resizeTable();
long hashCode = getHashCode(k, 0);
int index = compressHashCode(hashCode, dTable.length);
if (isAvailable(index, dTable))
{
dTable[index] = v;
size++;
}
else
{
collisionHandling(index, hashCode, v, dTable);
size++;
}
}
public String remove(String k)
{
int index = getIndex(k);
if (dTable[index] == null || dTable[index].equals("AVAILABLE") || dTable[index].charAt(0) == '-')
return null;
else
{
if (this.emptyMarkerScheme.equals("A"))
{
String val = dTable[index];
dTable[index] = "AVAILABLE";
size--;
return val;
}
else if (this.emptyMarkerScheme.equals("N"))
{
String val = dTable[index];
dTable[index] = "-" + val;
size--;
return val;
}
}
return null;
}
Hopefully this can give you an idea of my approach. This does not include the Separate Chaining implementation I mentioned above. For this, I had the following inner classes:
private class hashList
{
private class hashNode
{
private String element;
private hashNode next;
public hashNode(String element, hashNode n)
{
this.element = element;
this.next = n;
}
}
private hashNode head;
private int length = 0;
public hashList()
{
head = null;
}
public void addToStart(String s)
{
head = new hashNode(s, head);
length++;
}
public int getLength()
{
return length;
}
}
And my methods were modified appropriate to access the element in the head node vs the element in the Array. I took this out, however, since we are not supposed to use Separate Chaining to solve the problem.
Thanks!!

At a total loss with java list processing code

Okay, this is probably going to come across as a really easy question, but honestly I'm new to coding and I've run up against a brick wall here. I need to insert a value into an array, shift the data to the right, and update the size of the array. The professor provided comments for us to structure our code around, and I've got most of it, but this last part is killing me. Can anyone help? Here's the code (the relevant portion is under //insert value and shift data...etc):
public class List {
// Declare variables
private int size = 0;
private int maxSize = 100;
private int[] data;
Scanner keyboard = new Scanner(System.in);
// constructors
public List() {
data = new int[maxSize];
}
public List(int maxSize) {
this.maxSize = maxSize;
data = new int[maxSize];
}
// methods
// Adds a value into the array and updates the size
public boolean add(int value) {
if (size == maxSize) {
System.out.println("Cannot add value since the list is full");
return false;
}
data[size] = value;
size++;
return true;
}
// add multiple values to the list obtained from the keyboard
public void addValues() {
// declare local variables
int count = 0;
System.out.println("Enter multiple integers separated by spaces");
String line = keyboard.nextLine();
Scanner scanLine = new Scanner(line);
try {
while (scanLine.hasNext()) {
data[size] = scanLine.nextInt();
count++;
size++;
}
} catch (ArrayIndexOutOfBoundsException aiobe) {
System.out.println("Only " + count + " values could be added before the list is full");
return;
} catch (InputMismatchException ime) {
System.out.println("Only " + count + " values could be added due to invalid input");
return;
}
}
// This will print all the elements in the list
public void print() {
System.out.println();
for (int i = 0; i < size; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
// This methods returns the index of the key value if found in the list
// and returns -1 if the key value is not in the list
public int find(int key) {
for (int i = 0; i < size; i++) {
if (data[i] == key) {
return i;
}
}
return -1;
}
// This methods deletes the given value if exists and updates the size.
public boolean delete(int value) {
int index = find(value);
if (index == -1) {
System.out.println("The specified value is not in the list");
return false;
}
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
return true;
}
// This methods inserts the value at the given index in the list
public boolean insertAt(int index, int value) {
// validate index value and insertability
if (index < 0 || index > size || size == maxSize) {
System.out.println("Invalid index or list is already full");
return false;
}
// insert value and shift data to the right and update the size
return true;
}
// This method removes the value at given index and shifts the data as needed
public boolean removeAt(int index) {
if (index >= 0 && index < size) {
for (int i=index+1; i<size; i++)
data[i-1] = data[i];
size--;
return true;
}
return false;
}
// This method sorts the values in the list using selection sort
public void sort() {
int temp;
for (int j=size; j>1; j--) {
int maxIndex = 0;
for (int i=1; i<j; i++)
if (data[maxIndex] < data[i])
maxIndex = i;
temp = data[j-1];
data[j-1] = data[maxIndex];
data[maxIndex] = temp;
}
}
}
I apologize if the code is structured really horribly as well, by the way, I was unsure how to format it on this site so it looked right.
// insert value and shift data to the right and update the size
// I think the size is globally declared right?
size++;
for(int i=size - 1; i < 0; i--) {
data[i] = data[i - 1];
}
data[index] = value;
If you have a max size there will also be a check for size <= maxSize. Hope it helps
Think below answer should help. As there is already a size check, no need to check it again
public boolean insertAt(int index, int value) {
// validate index value and insertability
if (index < 0 || index > 5) {
System.out.println("Invalid index or list is already full");
return false;
}
// insert value and shift data to the right and update the size
for(int i=index;i<size;i++) {
data[++i] = data[i];
}
data[index] = value;
return true;
}
public boolean insertAt(int index, int value) {
// validate index value and insertability
if (index < 0 || index > size || size == maxSize) {
System.out.println("Invalid index or list is already full");
return false;
}
// insert value and shift data to the right and update the size
for (int i=size - 1; i > index; i--)
data[i+1] = data[i];
data[index] = value
size++;
return true;
}

Insertion sort Numerical

I have two Arrays 1 with strings and another one with ints.
I have to use insertion sorts to print this list in acceding order numerical wise this is my code so far
these are the arrays:
String[]bn={"Cardinals","BlueJays","Albatross","Vultures","Crows","Mockingbirds","Condors","BaldEagles","Pigeons","RedHeadWoodPecker","Hummingbirds","Dodos"};
int[]bq={40,15,1,3,10,2,12,25,7,6,88,15};
public static void SortNumericalOrdernsert (String[] bn,int[] bq){
for(int i=1;i<bq.length;i++){
int next=bq[i];
String y=bn[i];
//find all the insertion location
//Move all the larger elements up
int j=i;
while(j>0 && bq[j-1]>next){
bn[j]=bn[j-1];
bq[j]=bq[j-1];
j--;
}
//insert the element
bq[j]=next;
bn[j]=y;
}
}}
Where am i doing it wrong?
// edited
You want to do like this?
public static void SortNumericalOrdernsert(String[] bn, int[] bq) {
for (int i = 1; i < bq.length; i++) {
int next = bq[i];
// find all the insertion location
// Move all the larger elements up
int j = i;
while (j > 0 && bq[j - 1] > next) {
bq[j] = bq[j - 1];
j--;
}
bq[j] = next;
}
for (int i = 1; i < bn.length; i++) {
String y = bn[i];
int j = i;
while (j > 0 && isBigger(bn[j - 1], y)) {
bn[j] = bn[j - 1];
j--;
}
bn[j] = y;
}
}
private static boolean isBigger(String left, String right) {
return left.compareTo(right) > 0;
}

How to use iterators in java?

I have implemented Priority Queue interface for making heap. Can you tell me how to implement an iterator on the top of that? point me to some apropriate tutorial,i am new to java and on a very short deadline here.
Actually i need a method to find and modify an object from heap on the basis of Object.id. I dont care if it is O(n).
public interface PriorityQueue {
/**
* The Position interface represents a type that can
* be used for the decreaseKey operation.
*/
public interface Position {
/**
* Returns the value stored at this position.
* #return the value stored at this position.
*/
Comparable getValue();
}
Position insert(Comparable x);
Comparable findMin();
Comparable deleteMin();
boolean isEmpty();
int size();
void decreaseKey(Position p, Comparable newVal);
}
// BinaryHeap class
public class OpenList implements PriorityQueue {
public OpenList() {
currentSize = 0;
array = new Comparable[DEFAULT_CAPACITY + 1];
}
public OpenList(int size) {
currentSize = 0;
array = new Comparable[DEFAULT_CAPACITY + 1];
justtocheck = new int[size];
}
public OpenList(Comparable[] items) {
currentSize = items.length;
array = new Comparable[items.length + 1];
for (int i = 0; i < items.length; i++) {
array[i + 1] = items[i];
}
buildHeap();
}
public int check(Comparable item) {
for (int i = 0; i < array.length; i++) {
if (array[1] == item) {
return 1;
}
}
return array.length;
}
public PriorityQueue.Position insert(Comparable x) {
if (currentSize + 1 == array.length) {
doubleArray();
}
// Percolate up
int hole = ++currentSize;
array[ 0] = x;
for (; x.compareTo(array[hole / 2]) < 0; hole /= 2) {
array[hole] = array[hole / 2];
}
array[hole] = x;
return null;
}
public void decreaseKey(PriorityQueue.Position p, Comparable newVal) {
throw new UnsupportedOperationException(
"Cannot use decreaseKey for binary heap");
}
public Comparable findMin() {
if (isEmpty()) {
throw new UnderflowException("Empty binary heap");
}
return array[ 1];
}
public Comparable deleteMin() {
Comparable minItem = findMin();
array[ 1] = array[currentSize--];
percolateDown(1);
return minItem;
}
private void buildHeap() {
for (int i = currentSize / 2; i > 0; i--) {
percolateDown(i);
}
}
public boolean isEmpty() {
return currentSize == 0;
}
public int size() {
return currentSize;
}
public void makeEmpty() {
currentSize = 0;
}
private static final int DEFAULT_CAPACITY = 100;
private int currentSize; // Number of elements in heap
private Comparable[] array; // The heap array
public int[] justtocheck;
private void percolateDown(int hole) {
int child;
Comparable tmp = array[hole];
for (; hole * 2 <= currentSize; hole = child) {
child = hole * 2;
if (child != currentSize &&
array[child + 1].compareTo(array[child]) < 0) {
child++;
}
if (array[child].compareTo(tmp) < 0) {
array[hole] = array[child];
} else {
break;
}
}
array[hole] = tmp;
}
private void doubleArray() {
Comparable[] newArray;
newArray = new Comparable[array.length * 2];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
array = newArray;
}
You might look at java.util.PriorityQueue. If you're in a hurry, Arrays.sort() may suffice. Once sorted, Arrays.binarySearch() becomes possible.
Your underlying data structure is an array, which is difficult to write a Java-style iterator for. You could try creating a container class implementing java.util.Iterator which holds a reference to your Comparable element and its current array index. You'll need to manually update the index when you move the container.

Categories

Resources