I want to crate a Heap structure that each node have 2 data , 1) string 2) int
so i think that each node must be a Class that's name is "heapNode" , but i have a trouble in swap method ,
please help me
import java.util.ArrayList;
public class MainHeap {
ArrayList<heapNode> heap;
MainHeap (){
new ArrayList<heapNode>();
}
public int getMin(){
return heap.get(0).data ;
}
private int parent(int pos) {
return pos / 2;
}
private void swap(int pos1, int pos2) {
heapNode temp =new heapNode();
temp = heap.get(pos1);
heap.get(pos1) = heap.get(pos2);
heap.get(pos2) = temp;
}
public void insert(int elem) {
int max = heap.size();
heap.get(max).data = elem ;
int current = heap.size() ;
while (heap.get(current).data < heap.get(parent(current)).data){
swap ( current , parent(current));
}
}
}
and this is my heapNode class
public class heapNode {
int data;
String fileName;
}
the swap method has error but i cant solve errors
Your swap code actually makes the objects point to different objects. It does not modify the positions in the arraylist itself. If using arraylist, you will have to remove an object from an index and set that object at a new index to swap or else you can use other data structure.
java.util.PriorityQueue<YourClass>
Related
How can I solve this error (the error is in bold):
What I need to do is hash the elements when I copy them to the temp array
public class LinearProbingHashTable<E> {
private Entry[] hashArray;
private Entry defunct;
public LinearProbingHashTable(int size) {
hashArray = new Entry[size];
defunct = new Entry(-1, null);
}
public int hashFunc(int key) {
return key % hashArray.length;
}
private void expand(int newCapacity) {
Entry<E> temp[];
temp = new Entry[newCapacity];
// add you code here
for( int i=0; i< hashArray.length; i++) {
int index = **hashFunc**(hashArray[i]);
while(**temp[index]!=0**) {
index = (index+1)% temp.length;
}
temp[index]=hashArray[i];
}
hashArray = temp;
}
// INCLUDED FOR TESTING
public int getCapacity() {
return hashArray.length;
}
public class Entry<E> {
private int key;
private E data;
public Entry(int k, E d) {
key = k;
data = d;
}
public int getKey() {
return key;
}
public E getData() {
return data;
}
public void display() {
System.out.print(key + ":");
System.out.println(data);
}
}
}
I need to fix the bold error but I couldn't.
The error I get is: The method hashFunc(int) in the type LinearProbingHashTable is not applicable for the arguments (LinearProbingHashTable.Entry)
And the error for the second line is: Incompatible operand types LinearProbingHashTable.Entry and int
The errors you are getting are because you are passing an Entry object into a method that expects an int, and because you try to compare an Entry object with an int.
Your class Entry and the objects of it are not int objects and can't be used like one. But your class has an int field private int key that I would guess you probably meant to use in both cases.
So you need to change your code to use that field by using the getter of your class:
change
int index = hashFunc(hashArray[i]);
to
int index = hashFunc(hashArray[i].getKey());
and change
while(temp[index]!=0)
to
while(temp[index].getKey() != 0)
That will make your code syntactically correct. I can't say anything about whether it will be logically correct as I haven't tested that aspect.
I've read up on the wiki page on creating a extendable hashtable Extendable Hashing. And now i'm trying to implement that into a program to better understand it but I can't figure out how to actually point the directories towards the buckets.
Directory class:
int GlobalDepth = 1;
int directories[];
public Directory() {
int temp = (int)Math.pow(2, GlobalDepth);
loadDirectories(temp);
}
public void loadDirectories(int n) {
for (int i = 0; i < n; i ++) {
String BinaryKey = Integer.toBinaryString(i);
String tempKey = BinaryKey.substring(0, this.GlobalDepth); // LSB
int depthKey = Integer.parseUnsignedInt(tempKey);
this.directories[i] = depthKey;
}
}
public void increaseGlobalDepth() {
this.GlobalDepth ++;
loadDirectories((int)(Math.pow(2, this.GlobalDepth))); // This method might throw an error because i think im changing the array size illegally and should instead create a temp array and copy/equal that array to this.directories
}
Bucket class:
private SomeObject[] item; // Class I'm using to hold all the information of something
private int Key, MaxBucketsize, LocalDepth = 1;
//Bucket next;
public Bucket() {
}
public Bucket(int BucketSize) {
this.item = new SomeObject[BucketSize]; // Initalises the number of items held in the bucket
this.MaxBucketsize = BucketSize; // Stores the max number of items that can be held in the bucket
}
public SomeObject[] getObjects() {
return this.item;
}
public boolean addObjects(int key, SomeObject item) {
boolean inserted = false;
for (int i = 0; i < this.MaxBucketsize; i ++) {
if (this.item[i] == null) { // only inserts if there is an empty spot in the bucket
this.item[i] = item;
this.item[i].setKey(key);
inserted = true;
break;
}
}
return inserted;
}
After doing all this, I'm not sure how to now link the 2 together like in the wiki page.
I try to make an array of nodes with a node on a specific place in the array.
For example:
I add a node in the array and set its number to 1.
I add another node in the array on the next position and set its number to 2.
Both nodes got the number 2 now.
Sample of the code:
public static String run(InputStream in) {
Scanner sc = new Scanner(in);
//indicating values
sc.nextInt(); /* int vertices = */
int edge = sc.nextInt();
int start = sc.nextInt();
int end = sc.nextInt();
if (start == end) {
sc.close();
Path = "yes";
} else {
nodes = new Node[edge + 1];
for (int i = 1; i < edge; i++) {
//Node values
int number = sc.nextInt();
int next = sc.nextInt();
sc.nextInt(); /* int distance = */
Node node = new Node(number, next);
if (nodes[number] == null) {
nodes[number] = (node);
} else {
nodes[number].addChild(next);
}
}
hasPath(nodes[start], end);
}
sc.close();
return Path;
}
Sample of the Node code:
import java.util.ArrayList;
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private static int number;
public Node(int n, int next){
number = n;
childs.add(next);
}
public int getNumber(){
return number;
}
public void addChild(int child){
childs.add(child);
}
Can anyone please help me?
The problem is with declaring the number member static. This means there's only one such member for the Node class, instead of each instance having its own member. Just define it as an instance variable, and you should be fine:
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private int number; // Note the static was removed
// rest of the class
So I'm setting a node class that shows links between one node and another to find the shortest route. I decided to use a seperate object class to store the links between node A and B to avoid using two-dimensional arrays.
After saving the project in eclipse, just as a checkpoint so I don't lose my data, all of a sudden red lines appeared under any calls of DistanceBetween, saying that the method doesn't exist in that object class, although it does, as you'll see.
Note: Any bolded part is throwing an error, in Node. Generally it states that the method doesn't exist in DistanceBetween, or that the constructor (int, int) is wrong, when it is not.
Should I use extend, a package?
public class DistanceBetween{
private int thisAddress;
private int distanceBetween;
public DistanceBetween(int myAddress, int myDistance){
thisAddress = myAddress;
myDistance = distanceBetween;
}
public int getAddress(){
return thisAddress;
}
public void setAddress(int newAddress){
thisAddress = newAddress;
}
public int getDistance(){
return distanceBetween;
}
public void setDistance(int newDistance){
distanceBetween = newDistance;
}
}
public class Node{
private int address;
private int distance;
private Node[] connectedNodes;
private DistanceBetween[] distances;
private boolean intersection;
public Node(int myAddress, Node[] myConnected, DistanceBetween[]
myDistances, boolean isIntersection){
address = myAddress;
connectedNodes = myConnected;
distances = myDistances;
intersection = isIntersection;
}
public int getThisAddress(){
return address;
}
public void setThisAddress(int newAddress){
address = newAddress;
}
public Node[] getConnected(){
return connectedNodes;
}
public void connectTwo(Node a, Node b){
for(int x = 0; x < a.getConnected().length; x++){
if(a.getConnected()[x].getThisAddress() == 0){
}
}
}
public DistanceBetween[] getDistances(){
return distances;
}
public void setDistances(DistanceBetween[] newDistances){
distances = newDistances;
}
public void addLink(Node a, Node b, int thisDistance){
DistanceBetween[] holderDistanceA = a.getDistances();
DistanceBetween[] holderDistanceB = a.getDistances();
int flags = 0;
for(int x = 0; x < holderDistanceA.length; x++){
if(holderDistanceA[x].**getAddress()** == 0){
DistanceBetween aAndB = new **DistanceBetween(b.getThisAddress(),thisDistance);**
holderDistanceA[x] = aAndB;
flags++;
break;
}
}
for(int x = 0; x < holderDistanceB.length; x++){
if(holderDistanceB[x].**getAddress()** == 0){
DistanceBetween bAndA = new **DistanceBetween(a.getThisAddress(),thisDistance);**
holderDistanceB[x] = bAndA;
break;
}
}
if(flags < 1){
System.out.println("Error, cannot add a link, link load is full.");
}
a.setDistances(holderDistanceA);
b.setDistances(holderDistanceB);
}
public int getDistanceBetween(Node a, Node b){
int result = 0;
for(int x = 0; x < a.getDistances().length; x++){
if(a.getDistances()[x].**getAddress()** == b.getThisAddress()){
result = a.getDistances()[x].**getDistance()**;
}
}
return result;
}
public boolean equals(Node a, Node b){
if(a.address == b.address){
return true;
}else
return false;
}
}
Your code compiles fine, it would appear that you have the 2 classes in different packages. To fix you can:
put the 2 classes into the same package
import the DistanceBetween package into the Node class.
import yourpackagename.DistanceBetween;
Make sure you do not have a class named DistanceBetween somewhere else in your project, or, in case you do, that you're importing the right one where the DistanceBetween code you posted is intended to be used.
The Open Type tool in Eclipse (Ctrl + Shift + T) allows you to search for the location of classes along your workspace.
Hey guys, am trying to write to do type casting in java, but i keep getting
run:
[(E,1), (H,1), (F,2), (G,2), (I,5), ( ,7)]
(H,1)
class datacompression.tuple
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to datacompression.tuple
at datacompression.Chap3.huffman(Chap3.java:79)
at datacompression.Chap3.histogram(Chap3.java:37)
at datacompression.Main.main(Main.java:18)
Java Result: 1
this the source code:
import java.util.ArrayList;
/**
*
* #author Cubearth
*/
public class Chap3 {
public static void huffman(ArrayList<tuple> list){
//creates an huffman tree
ArrayList<Node> huff = new ArrayList<Node>();
for(int i = 0; i<list.size(); i++){
huff.add(i, new Node(list.get(i), 2));
huff.get(i).setScore(list.get(i).getB());
}
System.out.println(huff.get(1).getData().toString());
System.out.println(huff.get(1).getData().getClass());
while(huff.size()>1){
String msg = ((tuple)(huff.get(0).getData())).getA()+ ((tuple)(huff.get(1).getData())).getA();
Node tmp = new Node(msg, 2);
tmp.setChild(huff.get(0), 1);
tmp.setChild(huff.get(1), 1);
tmp.setScore((huff.get(0).getScore()+huff.get(1).getScore()));
huff.set(0, tmp);
huff.remove(1);
sort2(huff);
}
System.out.println(huff);
Tree tmp = new Tree(huff.get(0));
tmp.print(2);
}
public static void sort2(ArrayList<Node> list){
//sort an arrayList of node, uesing insertion sort
int pos, min;
for(pos = 0; pos<list.size()-1; pos++){
min = pos;
for(int i = pos+1; i<list.size(); i++){
if(list.get(i).getScore()< list.get(pos).getScore())
min = i;
}
if(min!=pos){
swap2(list, pos, min);
}
}
}
public static void swap2(ArrayList<Node> list, int a, int b){
//swap two indexes of list
Node bucket = new Node(list.get(a).getData(), list.get(a).getNoc());
list.set(a, list.get(b));
list.set(b, bucket);
}
}
why my check for class in the huffman method comes up as a tuple(), but am unable to cast it as one?
well, initially huff.get(0).getData() might come as a 'tuple', but in this line:
huff.set(0, tmp);
you set it to be a String (as tmp is a String), so in the next iteration it will complain