I have made a Priority Queue class with an array list, but I am having trouble with the insert and delMin (delete minimum areas). I cannot create more functions and here is my code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyMinPQ<E extends Comparable<E>> implements Iterable<E> {
private ArrayList<E> pq;
private int N;
public MyMinPQ() {
pq = new ArrayList<E>();
}
public E delMin(){
E minVal = min();
pq.remove(0);
N--;
return minVal;
}
public E min (){
if (isEmpty())
throw new NoSuchElementException();
return pq.get(0);
}
public void insert (E item){
for (int i = 0; i < N; i++){
pq.add(item);
if (pq.get(i) > pq.get(i+1)) {
E tmp = pq.get(i);
pq.set(i+1, tmp);
}
}
N++;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public Iterator<E> iterator() {
return new Iterator<E>(){
int current = 0;
public boolean hasNext() {
return current != size();
}
public E next() {
if (hasNext())
return pq.get(current++);
else throw new NoSuchElementException( );
}
public void remove() {
throw new UnsupportedOperationException( );
}
};
}
}
At the insert portion of the code, I know that I have to sort the new additions to Arraylist but I am having issues with going about this. I tried to compare the values that is within the list, but eclipse does not allow it based on how I formatted it. When I use compareTo, it does not work with my iterator and everything goes into disarray.
My question is how can I go about modifying my insert function so it can sort new items in descending order? Will my delMin() also have to change because of it?
try this
public void insert(E item) {
int i = 0;
while (i < N && pq.get(i).compareTo(item) <= 0) {
i++;
}
N++;
}
Related
I have created in class a generic class that works like ArrayList. The class included an array that gets bigger and smaller by demand by functions. Now, I have to implement the List interface and got stuck on the Iterator and ListIterator. I get only errors all the time, when I try to realize methods that depends on Iterator or ListIterator. Of course I have searched on the internet but I think I miss something.
public class EviatarList implements List, Iterable {
private E[] arr;
private static final int DEFAULT_CAPACITY = 3;
private int index = 0;
private int iteratorIndex = 0;
#Override
public Iterator<E> iterator() {Iterator<E> it = new Iterator<E>() {
#Override
public boolean hasNext() {
return index < arr.length && arr[index + 1] != null;
}
#Override
public E next() {return arr[iteratorIndex++];}
#Override
public void remove(){
E [] arr1 =(E[]) new Object [size()-1];
try {
arr[iteratorIndex] = null;
iteratorIndex--;
index--;
for (int i = 0, j = 0; i < arr.length; i++, j++) {
if (arr[i] != null)
{
arr1[j] = arr[i];
} else{
j--;
}
}
} catch (Exception e)
{
System.out.println(e.getMessage());
}
arr = arr1;
}
};
return it;
}
public ListIterator<E> listIterator() {
ListIterator<E> li = new ListIterator<E>() {
//o(1)
#Override
public boolean hasNext() {
return index < arr.length;
}
//o(1)
#Override
public E next() {
return arr[index++];
}
//o(1)
#Override
public boolean hasPrevious() {
return index > 0;
}
//o(1)
#Override
public E previous() {
return arr[index--];
}
//o(1)
#Override
public int nextIndex() {
return iteratorIndex;
}
//o(1)
#Override
public int previousIndex() {
return iteratorIndex--;
}
// o(n)
#Override
public void remove() {
E[] newArr = (E[]) new Object[arr.length - 1];
index--;
for (int i = 0, j = 0; i < index; i++, j++) {
if (i != iteratorIndex) {
newArr[i] = arr[j];
} else {
j--;
}
}
arr = newArr;
}
Sorry, but your question is a little vague so I cannot really answer. The implementation of EviatarList is not shown but used (e.g. size()) and "I get only errors all the time" is not clear about the kind of errors (from the compiler or runtime using it, ...).
Some thoughts on your implementation that may help one step further:
Why you implement your own List instead of extending AbstractList (that would offer ready to use iterators)?
You can have multiple iterators on the same collection, therefore the iteratorIndex has to be state (aka member) of the Iterator, not of the List!
There is some confusion about index and iteratorIndex in your implementation. What is the difference and what is the role of index?
As ListIterator extends Iterator it would simplify your implementation using the same for both:
public Iterator<E> iterator() {
return listIterator();
}
I would like to write a class(called Seii) that is basically a sequence of whole numbers starting from s0. s0 is set in the constructor:
se + 1 = 3*(se/2)
The catch is: A for-loop should be able to iterate through the objects of this class and spit out the elements of the sequence (without the starting number s0). Also, the sequence ends with the first element larger than 42.
For example:
for(int i:new Seii(2)){
System.out.println(i)
gives out:
3,4,6,9,10,15,16,24,36,54
I would like to do it using iterators. Can someone pls help me out?
My idea would be to rewrite the next() method so that it does the calculation for the next element of the sequence, but i'm not getting anywhere with the logic of this.
public class Seii<T> implements Iterator {
private ArrayList<Integer> list = new ArrayList<>();
Iterator<Integer> it = list.iterator();
private final int size;
public Seii(int size) {
this.size = size;
}
int seii = 0;
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
#Override
public Object next() {
if ((size % 2) == 0) {
seii = 3 * (seii/2);
return seii;
}
}
}
}
This is my implementation.
Seii should implement Iterable<Integer>, which will allow it to support the enhanced for loop syntax. The easiest way of doing that, IMHO, is just to have an inner Iterator class which implements your logic:
public class Seii implements Iterable<Integer> {
private class SeiiIterator implements Iterator<Integer> {
#Override
public boolean hasNext() {
return value <= 42;
}
#Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
value = 3 * (value / 2);
return value;
}
}
private int value;
public Seii(int value) {
this.value = value;
}
#Override
public Iterator<Integer> iterator() {
return new SeiiIterator();
}
}
You do not need to store the sequence, so the array list can be removed from your implementation. All you need is the last value, which can be set in the constructor:
// This is a wrapper class that constructs iterators.
// It is used for plugging in your code into enhanced "for" loop
class Seii implements Iterable<Integer> {
private int current;
private int max;
public Seii(int current, int max) {
this.current = current;
this.max = max;
}
#Override
public Iterator<Integer> iterator() {
return new SeiIterator(current, max);
}
}
// This is the actual iterator that maintains state
// and produces the desired sequence.
class SeiIterator implements Iterator<Integer> {
private int current;
private int max;
public SeiIterator(int current, int max) {
this.current = current;
this.max = max;
}
#Override
public boolean hasNext() {
return current < max;
}
#Override
public Integer next() {
current = (3*current)/2;
return current;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Note that in order to use your iterator in an enhanced for loop you need to wrap it in an Iterable<Integer>.
Demo.
Your Seii class should implement Iterable<Integer> not Iterator, since that's the interface required by the enhanced for loop. It would have an iterator method that returns an instance of a class that implements the Iterator<Integer> interface.
public X get(int index)
{
if (index >= 0)
{
Node<X> i = head;
int c = 0;
while (c < index)
{
i = i.getLink();
c++;
}
return i.getValue();
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
.
#Test
public void testGet12()
{
LList<String> b = new LList<String>();
b.add("str1");
b.add("str2");
b.add("str3");
b.add("str4");
b.add("str5");
b.add("str6");
b.add("str7");
b.add("str8");
b.add("str9");
b.add("str10");
b.add("str11");
b.add("str12");
assertEquals("str8", b.get(7));
assertEquals("str12", b.get(11));
assertEquals("str1", b.get(0));
}
It is saying that it's expecting str8, but is getting str5, why is my index off by 3? Am i missing something here? To me it seems when it doesnt reach the index it goes up one link until it finally reaches it then spits out the value.
Just an idea
import java.util.ArrayList;
import java.util.List;
public class list {
static List<String> a=new ArrayList<String>();
public String getvalue(int index)
{
return a.get(index);
}
public static void main(String args[]){
list e=new list();
a.add("Str0");
a.add("Str1");
a.add("Str2");
a.add("Str3");
a.add("Str4");
a.add("Str5");
a.add("Str6");
a.add("Str7");
a.add("Str8");
if("Str6".equals(e.getvalue(6))){
System.out.println("true");
}
else
System.out.println("Wrong");
}
}
Flatten an iterator of iterators in Java. If the input is [ [1,2], [3,[4,5]], 6], it should return [1,2,3,4,5,6]. Implement hasNext() and next(). Be careful when the inner iterator or list is empty.
I don't think my code works for multiple levels of inner lists.
public class FlattenList {
int index = 0; // keep an index to indicate where the current accessed element is
List<Integer> flattenedList = new ArrayList<>(); // flattenedList
public FlattenList(List<List<Integer>> lists){
for(List<Integer> list : lists){ // add all inner list to our underlying list.
flattenedList.addAll(list);
}
}
public boolean hasNext(){ // check if the index has exceeded the list size
return flattenedList.size() > index? true : false;
}
public Integer next(){ // return the next element, and increment the index
Integer result = flattenedList.get(index);
index++;
return result;
}
}
So basically this is like writing a depth first traversal of a tree. Leaf nodes of this tree are numbers, all interior nodes are modeled as Iterators. Here is some pseudo code:
void flatten(Iterator<Object> iterator, List<Integer> flattenedList) {
for (Object o : iterator) {
if (o instanceof Iterator) {
flatten((Iterator) o, flattenedList);
} else {
flattenedList.add((Integer) o);
}
}
}
Here, I'll start it for you:
public <T> Iterator<T> flatten(final Iterator<Iterator<T>> iterators) {
if (iterators == null) {
throw new IllegalArgumentException("iterators can't be null");
}
return new Iterator<>() {
#Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not implemented: hasNext");
}
#Override
public T next() {
throw new UnsupportedOperationException("Not implemented: next");
}
};
}
Now you just do that pesky brainwork and you'll be done.
EDIT
If you're not used to that syntax, here's a slightly easier one:
public <T> Iterator<T> flatten(final Iterator<Iterator<T>> iterators) {
return new MyFlatteningIterator<>(iterators);
}
public class MyFlatteningIterator<T> implements Iterator<T> {
private final Iterator<Iterator<T>> iterators;
public MyFlatteningIterator(final Iterator<Iterator<T>> iterators) {
if (iterators == null) {
throw new IllegalArgumentException("iterators can't be null");
}
this.iterators = iterators;
}
#Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not implemented: hasNext");
}
#Override
public T next() {
throw new UnsupportedOperationException("Not implemented: next");
}
}
You should not treat this as a list, rather as Jon stated this is more suitable when you are talking about trees. If you infect looking for a solution to get a flatted iterator of list of lists (something that looks like [[1],[1,2,3],[8,9]]) then I think that the following solution will work better
import java.util.Collection;
import java.util.Iterator;
public class FlattedIterator<T> implements Iterator<T> {
private Iterator<T>[] iteratorsArray;
public FlattedIterator(Collection<T>[] items) {
this.iteratorsArray = new Iterator[items.length];
for(int index = 0; index < items.length; index++) {
this.iteratorsArray[index] = items[index].iterator();
}
}
#Override
public boolean hasNext() {
boolean hasNext = false;
for(int index = 0; index < this.iteratorsArray.length; index++) {
hasNext |= this.iteratorsArray[index].hasNext();
}
return hasNext;
}
#Override
public T next() {
int index = 0;
while(index < this.iteratorsArray.length && !this.iteratorsArray[index].hasNext()) {
index++;
}
if(index >= this.iteratorsArray.length ) {
throw new IndexOutOfBoundsException("Reached end of iterator");
}
return this.iteratorsArray[index].next();
}
}
Bear in mind that the reason that I think this solution will work better is due to the fact that in your solution you initialized flattenedList by adding all the data from the given lists meaning that if in some point of the program one of those lists will received more data after you initialized FlattenList then the new data wont appear while you read the iterator.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java how to: Generic Array creation
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack<E> extends Vector<E> {
private E a[];
private int top;
public void Stack() {
a = new E[100];
top = -1;
}
public void Stack(int n) {
a = new E[n];
top = -1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
}
This is my stack generics class in java. I am getting an error in array declaration inside the two constructor i.e Stack() and Stack(int n). The error is "generic array creation" in both cases. please help
generic array is can not be created. so use Object array.
import java.io.*;
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack extends Vector
{
private Object a[];
private int top;
public void Stack()
{
a=new Object[100];
top=-1;
}
public void Stack(int n)
{
a=new Object[n];
top=-1;
}
public E pop()
{
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj=(E) a[top--];
return obj;
}
public void push(E e)
{
if(e==null)
throw new NullPointerException();
else if(top==size()-1)
System.out.println("Stack full");
else
{
a[++top]=e;
System.out.println("pushed :"+e);
}
}
public int size()
{
int i;
for(i=0;a[i]!=null;i++);
return i;
}
}
You do not have constructors in your class these are methods. for construtors remove the void type. Constructors don't have return types. Also your class name starts with lower letter stack and constructors start with Stack . Rename your class to Stack and remove void types.
You need to do it like this
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
see Generic Array
Following is your working class with object creation in main method.
class Stack<E> extends Vector<E> {
private E a[];
private int top;
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
public static void main(String...strings ){
Stack<Integer> st=new Stack<Integer>(Integer.class,n);
}
}