Cannot insert multiple elements in PriorityQueue - heapsort

I'm trying to implement a heap sorting algorithm.
My problem is when I try to insert Elements to my PriorityQueue, it only works for one element. When I add multiple elements to it, I get these errors
Exception in thread "main" java.lang.ClassCastException: Element cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
at PQHeap.insert(PQHeap.java:47)
at PQHeap.main(PQHeap.java:17)
This is my Element class
public class Element {
public int key;
public Object data;
public Element(int i, Object o) {
this.key = i;
this.data = o;
}}
The interface:
public interface PQ {
public Element extractMin();
public void insert(Element e);
}
And this is the class, which generates the heap. Note that the main class is located here just to debug with. When I only insert Element e, it works. But when I insert f aswell, it give's me the errors above.
import java.util.*;
public class PQHeap implements PQ{
public static void main(String[] args) {
PQHeap hq = new PQHeap(5);
Element e = new Element(5, null);
hq.insert(e);
hq.insert(f);
for(int in = 0; in<hq.pq.size();in++){
System.out.println(hq.pq.remove());
}
}// end of main method
public PriorityQueue<Element> pq;
public PQHeap(int maxElms) {
this.pq = new PriorityQueue<Element>(maxElms);
}
#Override
public Element extractMin() {
Element min = pq.remove();
System.out.println(min.key);
return min;
}
#Override
public void insert(Element e) {
this.pq.add(e);
}

Related

create an application that prompts the user for a set of five integer numbers using data structure

*Using the ArrayBoundedStack class,create an application named EditNumbers that prompts the user for a set of five integer numbers, push its content into a stack, and then repeatedly prompts the user for changes to numbers, until the user enters an X, indicating the end of changes. Legal change operations are: M, A, R, and C.
• Option M return the maximum value in the set
• Option A v1 means add v1 to each number in the set
• Option R means reverse the numbers in the set
• Option C v1 v2 means change all occurrences of v1 to v2
*
(arrayboundedstack) using this codes bellow
**1)** package stack;
public class ArrayBoundedStack <T> implements StackInterface <T> {
private final int DEFSIZE=100;
private int index=-1;
private T[] arr;
public ArrayBoundedStack()
{
arr=(T[])new Object[DEFSIZE];
}
public ArrayBoundedStack(int size)
{
arr=(T[])new Object[size];
}
public boolean isFull()
{
return index == (arr.length-1);
}
public boolean isEmpty()
{
return index == -1;
}
public void push(T element)
{
if(!isFull())
{
index++;
arr[index]=element;
}
else{
throw new OverflowStackException("The stack is fill , you cannot push");
}
}
public void pop()
{
if(!isEmpty())
{
arr[index]=null;
index--;
}
else{
throw new UnderflowStackException("The stack is empty , you cannot pop");
}
}
public T top()
{
T temp=null;
if (!isEmpty())
temp=arr[index];
else{
throw new UnderflowStackException("The stack is empty , there is no top");
}
return temp;
}
}
**2) ** package stack;
public class MyApp1 {
public static void printStack(ArrayBoundedStack<Integer> st)
{
ArrayBoundedStack<Integer> temp=new ArrayBoundedStack<>(10);
System.out.println("the stack contains:");
while(!st.isEmpty())
{
System.out.println(st.top());
temp.push(st.top());
st.pop();
}
while(!temp.isEmpty())
{
st.push(temp.top());
temp.pop();
}
}
public static void nonNegativeStack(ArrayBoundedStack<Integer> st)
{
ArrayBoundedStack<Integer> temp=new ArrayBoundedStack<>();
while(!st.isEmpty())
{
if(st.top()>=0)
temp.push(st.top());
st.pop();
}
while(!temp.isEmpty())
{
st.push(temp.top());
temp.pop();
}
}
public static void main(String[] args)
{
ArrayBoundedStack<Integer> st=new ArrayBoundedStack<>(10);
st.push(10);
st.push(15);
st.push(30);
printStack(st);
System.out.println("the top of stack is " + st.top());
st.pop();
st.pop();
st.pop();
System.out.println("the top of stack is " + st.top());
}
}
**3) ** package stack;
public class MyApp2 {
public static void main(String[] args)
{
System.out.println("This is a test for exception");
throw new OverflowStackException("the stack is full");
}
}
**4)** package stack;
public class OverflowStackException extends RuntimeException{
public OverflowStackException()
{
super();
}
public OverflowStackException(String msg)
{
super(msg);
}
}
**5) ** package stack;
public interface StackInterface <T> {
public void push(T element) throws OverflowStackException;
public void pop() throws UnderflowStackException;
public T top()throws UnderflowStackException;
public boolean isFull();
public boolean isEmpty();
}
**6)**package stack;
public class UnderflowStackException extends RuntimeException{
public UnderflowStackException()
{
super();
}
public UnderflowStackException(String msg)
{
super(msg);
}
}
i made all the class up and i didnt know how to make a main class

add dynamic row content to vaadin grid

In vaadin7, I used GeneratedPropertyContainer to do this, eg adding row number:
wrappedContainer = new GeneratedPropertyContainer(_container);
wrappedContainer.addGeneratedProperty("#",
new PropertyValueGenerator<Integer>() {
#Override
public Integer getValue(Item item, Object itemId, Object propertyId) {
return (int) _container.indexOfId(itemId) + 1;
}
#Override
public Class<Integer> getType() {
return java.lang.Integer.class;
}
}
);
setContainerDataSource(wrappedContainer);
In vaadin8, since GeneratedPropertyContainer is deprecated, I tried to do like this:
grid.addColumn((v)->((List)_container.getData().getItems()).indexOf(v)+1);
But the index is static, when I sort the rows ascending and descending, the row number is moving too.
What I need is the first row is row number 1 and the last row is row number N, no matter how I sort the rows.
Thanks.
Unfortunately, as far as I can tell there is no simple solution out of the box. However, you can do like the following code:
Grid<MyBean> grid = new Grid<>();
grid.setDataProvider(new RowIndexDataProviderWrapper<>(DataProvider.ofItems(new MyBean("Item 1"), new MyBean("Item 2"), new MyBean("Item 3"))));
grid.addColumn(MyBean::getRowIndex).setCaption("#");
grid.addColumn(MyBean::getName).setCaption("Name");
public interface RowIndexAware {
void setRowIndex(int rowIndex);
int getRowIndex();
}
public class MyBean implements RowIndexAware {
// implement the interface (e.g. store row index in field)
// and add your bean properties
}
public class RowIndexDataProviderWrapper<T extends RowIndexAware, F> implements DataProvider<T, F> {
private DataProvider<T, F> wrapped;
public RowIndexDataProviderWrapper(DataProvider<T, F> wrapped) {
this.wrapped = wrapped;
}
// delegate all methods to be implemented for DataProvider interface
// to wrapped DataProvider with the exception of "fetch":
#Override
public Stream<T> fetch(Query<T, F> query) {
List<T> result = wrapped.fetch(query).collect(Collectors.toCollection(ArrayList::new));
for (int i = 0; i < result.size(); i++) {
result.get(i).setRowIndex(query.getOffset() + i);
}
return result.stream();
}
}
The idea is to get the row index when rows are fetched within the DataProvider and to store them in your bean.

Custom object as value for Mapper output

I have object have constructed as following:
Class ObjExample {
String s;
Object[] objArray; // element in this array can be primitive type or array of primitive type.
}
I know that to using it as output type for mapper or reducer, we have to implement WritableComparable for it.
But I really get confused how to write readFields(), write(), compareTo() for this kind of class?
You can wrap field s in Text and objArray in ArrayWritable. Each element of the objArray would be an array (also ArrayWritable) of primitives. Here is possible implementation:
public static final class ObjExample implements WritableComparable<ObjExample> {
public final Text s = new Text(); // wrapped String
public final ArrayOfArrays objArray = new ArrayOfArrays();
#Override
public int compareTo(ObjExample o) {
// your logic here, example:
return s.compareTo(o.s);
}
#Override
public void write(DataOutput dataOutput) throws IOException {
s.write(dataOutput);
objArray.write(dataOutput);
}
#Override
public void readFields(DataInput dataInput) throws IOException {
s.readFields(dataInput);
objArray.readFields(dataInput);
}
// set size of the objArray
public void setSize(int n) {
objArray.set(new IntArray[n]);
}
// set i-th element of the objArray to an array of elements
public void setElement(int i, IntWritable... elements) {
IntArray subArr = new IntArray();
subArr.set(elements);
objArray.get()[i] = subArr;
}
}
You will need two more classes to make it work:
// array of primitives
public static final class IntArray extends ArrayWritable {
public IntArray() {
// you can specify any other primitive wrapper (DoubleWritable, Text, ...)
super(IntWritable.class);
}
}
// array of arrays
public static final class ArrayOfArrays extends ArrayWritable {
public ArrayOfArrays() {
super(IntArray.class);
}
}
Example of construction of the object:
ObjExample o = new ObjExample();
o.s.set("hello");
o.setSize(2);
o.setElement(0, new IntWritable(0)); // single primitive
o.setElement(1, new IntWritable(1), new IntWritable(2)); // array of primitives

Accessing class variables from private actionPerformed method

In the code below, I don't know why the values of variables uNomba and list are NULL when accessed from jButton1ActionPerformed method. I would appreciate your help, on how I can successfully execute "new NewPlayer(uNomba, count, check, list).load();" such that all the values are passed to NewPlayer class. Thank you.
The first class - i.e The NewPlayer class
package mysound;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class NewPlayer extends JPanel implements KeyListener, Runnable{
boolean isUpPressed, isDownPressed, isSpacePressed, isDone;
static JFrame f;
int spacebars=0;
boolean within;
public List spacebarLogMs = new ArrayList();
public List numSbar = new ArrayList();
Calendar cal = Calendar.getInstance();
LogResult logNow = new LogResult();
String directory;
String tabname; //table name used in the database connection
String bdir;
private int uNomba; //user number obtained from NewSound class
private String target;
private int incr;
private int userno;
private boolean moveon=true;
private List randlist;
private List numlist;
public void load() {
f = new JFrame();
f.setSize(600,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(this);
f.setVisible(true);
setFocusable(true);
addKeyListener(this);
new Thread(this).start();
}
public NewPlayer() {
}
public NewPlayer(int UNOMBA, List NUMLIST){
this.uNomba = UNOMBA; //user number obtained from NewSound class
this.numlist=NUMLIST;
}
public NewPlayer(int USERNO, int INCR, boolean MOVEON, List NUMLIST){
this.userno=USERNO;
this.incr=INCR;
this.moveon=MOVEON;
this.numlist=NUMLIST;
}
public void keyTyped(KeyEvent ke) {
}
public void keyPressed(KeyEvent ke) {
switch(ke.getKeyCode()) {
case KeyEvent.VK_UP: isUpPressed = true; break;
case KeyEvent.VK_DOWN: isDownPressed = true; break;
case KeyEvent.VK_SPACE: isSpacePressed = true;
numSbar.add(System.currentTimeMillis());
System.out.println("That was a spacebar. "+spacebars++);
System.out.println("Current time: "+numSbar);
break;
}
}
public void keyReleased(KeyEvent ke) {
switch(ke.getKeyCode()) {
case KeyEvent.VK_UP: isUpPressed = false; break;
case KeyEvent.VK_DOWN: isDownPressed = false; break;
case KeyEvent.VK_SPACE: isSpacePressed = false; break;
}
}
public void closePrj(){
f.dispose();
}
public void run() { //introduce a target sound
String targetChoice;
int tIndex;
int i;
bdir="C:\\Users\\Abiodun\\Desktop\\testdata\\main\\zero\\atext\\"; //dir for text files
MainPlayer items = new MainPlayer (uNomba);
i=incr;
while(moveon){
System.out.println("Counter i: "+i+" Numlist: "+numlist);
if (i<numlist.size()){
int num = (int) numlist.get(i);
System.out.println("Num :"+num);
items.selectTarget(num);
items.selectChallenge(num);
items.playChallenge();
new WriteTime(bdir).tagTime(numSbar);
items.dataLogger();
moveon=false;
new Continue (uNomba, i, moveon, numlist).load();
}
}
}
}
The second class i.e the Continue class
public class Continue extends javax.swing.JDialog {
private int count;
private int usernumb;
private boolean check;
private int uNomba;
private String cdirectory;
private String cbdir;
private String ctabname;
private String ctarget;
private List list;
/**
* Creates new form Continue
*/
public Continue(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public Continue(int CUNOMBA, int COUNT, boolean CHECK, List NLIST){
this.uNomba = CUNOMBA; //user number obtained from NewSound class
this.count=COUNT;
this.check=CHECK;
this.list=NLIST;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
new NewPlayer().setVisible(false);//closePrj();
count++;
check=true;
new NewPlayer(uNomba, count, check, list).load();
System.out.println("Continue: UserNumber: "+uNumb+", Count: "+count+", Check: "+check+", nList"+lst);
this.setVisible(false);
}
Thanks sgroh. Here is what I just added: I created the following in
In NewPlayer class:
Continue ct = new Continue (new NewPlayer(uNomba, i, moveon, numlist));
In Continue Class,
private NewPlayer np;
public Continue (NewPlayer npy){
this.npy=np;
}
Just a recap, the main problem I am having is that I cannot access the values I passed from NewPlayer class from Continue class. I tested the values in side the following constructor in Continue class but not anywhere else in Continue class.
public Continue(int CUNOMBA, int COUNT, boolean CHECK, List NLIST){
this.uNomba = CUNOMBA; //user number obtained from NewSound class
this.count=COUNT;
this.check=CHECK;
this.nlist=NLIST;
System.out.println("Continue-constructor - uNomba: "+uNomba+", nList: "+list); //works fine! but not outside this constructor.
}
This code even compile, You haven't a constructor default (without fields).
this:
public Continue(java.awt.Frame parent, boolean modal) {
and This:
public Continue(int CUNOMBA, int COUNT, boolean CHECK, List NLIST){
this woun't compile:
Continue ctn = new Continue();
You have to create the Continue object using the right constructor or create the Default constructor.
You want also to print the variable uNumb in the System.out.println that doesn't exists.

Using a custom Object as key emitted by mapper

I have a situation in which mapper emits as key an object of custom type.
It has two fields an intWritable ID, and a data array IntArrayWritable.
The implementation is as follows.
`
import java.io.*;
import org.apache.hadoop.io.*;
public class PairDocIdPerm implements WritableComparable<PairDocIdPerm> {
public PairDocIdPerm(){
this.permId = new IntWritable(-1);
this.SignaturePerm = new IntArrayWritable();
}
public IntWritable getPermId() {
return permId;
}
public void setPermId(IntWritable permId) {
this.permId = permId;
}
public IntArrayWritable getSignaturePerm() {
return SignaturePerm;
}
public void setSignaturePerm(IntArrayWritable signaturePerm) {
SignaturePerm = signaturePerm;
}
private IntWritable permId;
private IntArrayWritable SignaturePerm;
public PairDocIdPerm(IntWritable permId,IntArrayWritable SignaturePerm) {
this.permId = permId;
this.SignaturePerm = SignaturePerm;
}
#Override
public void write(DataOutput out) throws IOException {
permId.write(out);
SignaturePerm.write(out);
}
#Override
public void readFields(DataInput in) throws IOException {
permId.readFields(in);
SignaturePerm.readFields(in);
}
#Override
public int hashCode() { // same permId must go to same reducer. there fore just permId
return permId.get();//.hashCode();
}
#Override
public boolean equals(Object o) {
if (o instanceof PairDocIdPerm) {
PairDocIdPerm tp = (PairDocIdPerm) o;
return permId.equals(tp.permId) && SignaturePerm.equals(tp.SignaturePerm);
}
return false;
}
#Override
public String toString() {
return permId + "\t" +SignaturePerm.toString();
}
#Override
public int compareTo(PairDocIdPerm tp) {
int cmp = permId.compareTo(tp.permId);
Writable[] ar, other;
ar = this.SignaturePerm.get();
other = tp.SignaturePerm.get();
if (cmp == 0) {
for(int i=0;i<ar.length;i++){
if(((IntWritable)ar[i]).get() == ((IntWritable)other[i]).get()){cmp= 0;continue;}
else if(((IntWritable)ar[i]).get() < ((IntWritable)other[i]).get()){ return -1;}
else if(((IntWritable)ar[i]).get() > ((IntWritable)other[i]).get()){return 1;}
}
}
return cmp;
//return 1;
}
}`
I require the keys with same Id to go to the same reducer with their sort order as coded in the compareTo method.
However when i use this, my job execution status is always map100% reduce 0%.
The reduce never runs to completion. Is there any thing wrong in this implementation?
In general what is the likely problem if reducer status is always 0%.
I think this might be a possible null pointer exception in the read method:
#Override
public void readFields(DataInput in) throws IOException {
permId.readFields(in);
SignaturePerm.readFields(in);
}
permId is null in this case.
So what you have to do is this:
IntWritable permId = new IntWritable();
Either in the field initializer or before the read.
However, your code is horrible to read.

Resources