I have ONE pre-compile error - java

Here is the assignment:
Modify the maze problem in Chapter 4 so that it can start from a user defined starting position (other than 0, 0) and search for a user defined ending point.
The whole program seems to look fine, and I still have to mess with the user-inputted part, but there is one line that has an error and I don't know how to get rid of it. Any help would be appreciated.
The line that has the error is:
StackADT stack = new LinkedStackADT ();
And it is telling me that LinkedStackADT cannot be resolved to a type.
Also, how do I get the maze to take in user-defined starting positions and ending points? Thanks for any possible help!
public class Maze
{
public interface StackADT<T> {
public void push (T element);
public T pop();
public T peek();
public boolean isEmpty();
public int size();
public String toString();
}
public static void main(String[] args){
abstract class LinkedStack<T> implements StackADT<T>
{
private int count;
private LinearNode<T> top;
public LinkedStack()
{
count = 0;
top = null;
}
class LinearNode<T>
{
private LinearNode<T> next;
private T element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode(T elem)
{
next = null;
element = elem;
}
public LinearNode<T> getNext()
{
return next;
}
public void setNext(LinearNode<T> node)
{
next = node;
}
public T getElement()
{
return element;
}
public void setElement(T elem)
{
element = elem;
}
}
class Position
{
private int x;
private int y;
Position ()
{
x = 0;
y = 0;
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
public void setx1(int a)
{
x = a;
}
public void sety(int a)
{
y = a;
}
public void setx(int x2) {
}
}
private final int TRIED = 3;
private final int PATH = 7;
private int [][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,0,1,1,0,1,1,1,1,0,0,1},
{1,1,1,1,1,0,1,0,1,0,1,0,0},
{0,0,0,0,1,1,1,0,1,0,1,1,1},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1}};
public StackADT<Position> push_new_pos(int x, int y,
StackADT<Position> stack)
{
Position npos = new Position();
npos.setx1(x);
npos.sety(y);
if (valid(npos.getx(),npos.gety()))
stack.push(npos);
return stack;
}
public boolean traverse ()
{
boolean done = false;
Position pos = new Position();
Object dispose;
StackADT<Position> stack = new LinkedStackADT<Position> ();
stack.push(pos);
while (!(done))
{
pos = stack.pop();
grid[pos.getx()][pos.gety()] = TRIED; // this cell has been tried
if (pos.getx() == grid.length-1 && pos.gety() == grid[0].length-1)
done = true; // the maze is solved
else
{
stack = push_new_pos(pos.getx(),pos.gety() - 1, stack);
stack = push_new_pos(pos.getx(),pos.gety() + 1, stack);
stack = push_new_pos(pos.getx() - 1,pos.gety(), stack);
stack = push_new_pos(pos.getx() + 1,pos.gety(), stack);
}
}
return done;
}
private boolean valid (int row, int column)
{
boolean result = false;
if (row >= 0 && row < grid.length &&
column >= 0 && column < grid[row].length)
if (grid[row][column] == 1)
result = true;
return result;
}
public String toString ()
{
String result = "\n";
for (int row=0; row < grid.length; row++)
{
for (int column=0; column < grid[row].length; column++)
result += grid[row][column] + "";
result += "\n";
}
return result;
}
}
}
}

You don't have a type (or a class) defined as LinkedStackADT. You do have a type LinkedStack, but it's abstract so the new will fail. If you remove the abstract keyword from LinkedStack, it should be instantiatable. (note: instantiatable is not a real word)

Related

Why do we want to use a helper method in Java?

I came across this block of code when I was studying for java CS61b, which used a helper method. As to why we use helper method, the explanation I got is that it makes it easier to do the recursive task. But I have trouble visualizing the alternative options where we don't use a helper method because I have difficulting write the solution. Does that mean using a helper method is the only way? I wish I could compare the two solutions and better understand the usage of a helper method.
here's the code in question:
//Same as get, but uses recursion.
public int getRecursive(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel;
return getRecursiveHelper(p, index);
}
public int getRecursiveHelper(node p, int i) {
if (i==0) {
return p.next.item;
} else {
p = p.next;
i -= 1;
}
return getRecursiveHelper(p, i);
}
the below is the full code:
public class LinkedListDeque {
public node sentinel;
public int size;
public class node {
public node prev;
public int item;
public node next;
public node(node p, int i, node n) {
prev = p;
item = i;
next = n;
}
}
// Creates an empty list
public LinkedListDeque() {
sentinel = new node(null, 63, null);
sentinel.prev = sentinel;
sentinel.next = sentinel;
size = 0;
}
// Adds an item of type T to the front of the deque.
public void addFirst(int x) {
sentinel.next = new node(sentinel, x, sentinel.next);
sentinel.next.next.prev = sentinel.next;
size += 1;
}
// Adds an item of type T to the back of the deque.
public void addLast(int x) {
sentinel.prev = new node(sentinel.prev, x, sentinel);
sentinel.prev.prev.next = sentinel.prev;
size += 1;
}
// Returns true if deque is empty, false otherwise.
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
// Returns the number of items in the deque.
public int size() {
return size;
}
// Prints the items in the deque from first to last, separated by a space. Once all the items have been printed, print out a new line.
public void printDeque() {
node p = sentinel.next;
for (int i=0; i<size; i++) {
System.out.print(p.item + " ");
p = p.next;
}
System.out.println();
}
// Removes and returns the item at the front of the deque. If no such item exists, returns null.
public int removeFirst() {
if (size==0) {
return 0;
}
int x = sentinel.next.item;
sentinel.next = sentinel.next.next;
sentinel.next.prev = sentinel;
size -= 1;
return x;
}
// Removes and returns the item at the back of the deque. If no such item exists, returns null.
public int removeLast() {
if (size==0) {
return 0;
}
int x = sentinel.prev.item;
sentinel.prev = sentinel.prev.prev;
sentinel.prev.next = sentinel;
size -= 1;
return x;
}
// Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth. If no such item e
public int get(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel.next;
for (int i=0; i<index; i++) {
p = p.next;
}
return p.item;
}
//Same as get, but uses recursion.
public int getRecursive(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel;
return getRecursiveHelper(p, index);
}
public int getRecursiveHelper(node p, int i) {
if (i==0) {
return p.next.item;
} else {
p = p.next;
i -= 1;
}
return getRecursiveHelper(p, i);
}
public static void main(String[] args) {
LinkedListDeque L = new LinkedListDeque();
L.addFirst(2);
L.addFirst(1);
L.addFirst(0);
L.addLast(3);
L.addLast(4);
L.addLast(5);
System.out.println(L.get(7));
}
}

How do I fill an array with user-defined objects?

I am writing a program that creates an object (Line) that contains a name and two nodes (x,y,z coordinates) which are then stored in a separate object (class LineModel). Within the class LineModel a method, getNodes(), is created that should return an array containing all the nodes.
My problem lies within the method getNodes(), as I am struggling to populate the array. My code is below.
public class LineModel {
// Object attributes
private String name;
private Line[] lines;
private int numLines;
// Constructor
public LineModel(String name, int maxLines) {
this.name = name;
lines = new Line[maxLines];
numLines = 0;
}
public void addLine(Line line) {
if (contains(line)) {
System.out.println("Line " + line.getName() + " already in model");
return;
}
if (numLines < lines.length) {
lines[numLines] = line;
numLines++;
} else {
System.out.println("Increase lines array size.");
System.exit(1);
}
}
public boolean contains(Line line) {
for (int i = 0; i < numLines; i++) {
if (line == lines[i])
return true;
}
return false;
}
public Line getLine(String name) {
for (int i = 0; i < numLines; i++) {
if (lines[i].getName().equals(name))
return lines[i];
}
System.out.println("Line " + name + " not found");
return null;
}
public void printModel() {
System.out.println('\n' + "Line model: " + name);
for (int i = 0; i < numLines; i++) {
System.out.println(lines[i]);
}
}
public Node getNode(String name) {
// Loop through lines
for (int i = 0; i <= numLines; i++) {
// Check if node 1 is contained in the line and returns if true
if (lines[i].getN1().getName().equals(name)) {
return lines[i].getN1();
}
// Check if node 2 is contained in the line and returns if true
else if (lines[i].getN2().getName().equals(name)) {
return lines[i].getN2();
}
}
return null;
}
public Node[] getNodes() {
Node[] nodes = new Node[2 * numLines];
for (int i = 0; i < numLines; i++) {
Node start = lines[i].getN1();
Node end = lines[i].getN2();
for (int j = 0; j < nodes.length - 1; j++) {
nodes[j] = start;
for (int k = 1; k <= nodes.length - 1; k++) {
nodes[k] = end;
}
}
}
return nodes;
}
}
Classes Node and Line are below
public class Node {
// Object attributes
private String name;
private double[] coordinates;
// Constructor(s)
public Node(String name, double x) {
this.name = name;
coordinates = new double[1];
coordinates[0] = x;
}
public Node(String name, double x, double y) {
this.name = name;
coordinates = new double[2];
coordinates[0] = x; coordinates[1] = y;
}
public Node(String name, double x, double y, double z) {
this.name = name;
coordinates = new double[3];
coordinates[0] = x; coordinates[1] = y; coordinates[2] = z;
}
// Object methods
public String getName(){
return name;
}
public double[] getCoordinates(){
return coordinates;
}
public double getX() {
if (coordinates.length > 0){
return coordinates[0];
} else {
return Double.NaN;
}
}
public double getY() {
if (coordinates.length > 1){
return coordinates[1];
} else {
return Double.NaN;
}
}
public double getZ() {
if (coordinates.length > 2){
return coordinates[2];
} else {
return Double.NaN;
}
}
public String toString() {
return "Node "+name+" "+Arrays.toString(coordinates);
}
}
public class Line {
// Object attributes
private String name;
private Node n1, n2;
// Constructor(s)
public Line(String name, Node n1, Node n2){
this.name = name;
this.n1 = n1;
this.n2 = n2;
}
public String getName(){ return name; }
// Object methods
public double length(){
double[] n1C = n1.getCoordinates();
double[] n2C = n2.getCoordinates();
if(n1C.length == n2C.length){
double pythagoras = 0;
for (int i = 0; i < n1C.length; i++) {
double dv = n2C[i] - n1C[i];
pythagoras += dv*dv;
}
return Math.sqrt(pythagoras);
}
return Double.NaN;
}
#Override
public String toString(){
return "Line "+name+" "+n1.getName()+"-->"+n2.getName()+" Length = "+length();
}
My current output is this:
[L_22751459.Node;#7530d0a
You just need to replace your getNodes() method with below code.
Need to introduce extra variable count and for every added node simply increment it. So automatically for two lines it will add four nodes like node[0],node[1],node[2],node[3]
public Node[] getNodes() {
int count=0;
Node[] nodes = new Node[2 * numLines];
for (int i = 0; i < numLines; i++) {
nodes[count]=lines[i].getN1();
nodes[count+1]=lines[i].getN2();
count=count+2;
}
return nodes;
}
public static void main(String[] args) {
LineModel obj2=new LineModel("l2",2);
obj2.addLine(new Line("name1",new Node("x",1.0),new Node("y",2.0)));
obj2.addLine(new Line("name2",new Node("x",2.0),new Node("y",3.0)));
Node[] arr=obj2.getNodes();
Arrays.stream(arr).forEach(node -> System.out.println(node.toString()));
}
Above code printing below Output which is perfectly fine.
Node x [1.0]
Node y [2.0]
Node x [2.0]
Node y [3.0]

Implement a Set class using an array

My Java assignment is to implement a set class by using an array.
The assignment won't allow me import the set class from the library, so I have to make it on my own. When I tried to print out the array, it prints out numbers in repeats, not unique numbers. I don't know where the problem is, so if you guys can find any errors in my code, it would be great. I tried to add numbers 2, 3, and 4 to the set, so the result should be 2 3 4, but the code shows me 2 3 2 3 2.
I think the source of the problem is from the add method from the set class, but I don't know what the problem is exactly.
import java.util.Arrays;
public final class Set implements SetInterface
{
private int[] set;
private int size;
private int capacity;
public Set(int c)
{
capacity = c;
set = new int[capacity];
size = 0;
}
public boolean contains(int x)
{
boolean contains = false;
for(int i = 0; i<capacity; i++)
{
if(x == set[i])
contains = true;
else
contains = false;
}
return contains;
}
public void add(int x)
{
for(int i = 0; i<capacity; i++)
{
if(!contains(x))
{
if(size == capacity)
{
set = Arrays.copyOf(set,size*2);
}
if(set[i]==0)
{
set[i++] = x;
}
}
}
size++;
}
public boolean remove(int x)
{
boolean remove = false;
for(int i = 0; i < capacity; i++)
{
if(x == set[i])
{
set[i] = set[size -1];
size--;
remove = true;
}
if(isEmpty())
{
remove = false;
}
}
return remove;
}
public void clear()
{
set = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
if(size == 0)
return true;
else
return false;
}
public int[] toArray()
{
return Arrays.copyOf(set, capacity);
}
}
This is the driver class that I test my class.
import java.util.Arrays;
public class SetDriver
{
public static void main(String[] args)
{
SetDriver driver = new SetDriver();
Set s1 = new Set(5);
s1.add(2);
s1.add(3);
s1.add(4);
driver.print(s1);
System.out.println("Size: "+s1.size());
}
public static void print(Set s)
{
for(int i = 0; i<s.toArray().length; i++)
{
System.out.print(s.toArray()[i]+" ");
}
System.out.println("");
}
}
The outputs are here:
2 3 2 3 2
Size: 3
There's a likely problem with your contains method. Suppose that you did find a duplicate. What happens is that you assign your variable to true and you continue to iterate. This stomps over the logic entirely; you could have a duplicate but never act on it because your boolean code precludes you from doing so.
Ideally, when you find a match, you must stop iterating and return immediately.
public boolean contains(int value) {
for(int setItem : set) {
if(setItem == value) {
return true;
}
}
return false;
}
You should change add method like this.
public void add(int x) {
if (contains(x))
return;
if (size >= capacity) {
capacity *= 2;
set = Arrays.copyOf(set, capacity);
}
set[size++] = x;
}

Sorting sets of 4 ints in circular list

I am playing around with circular linked list to represent polynomials with it.
Here is what I have so far:
Class for parts of polynomial:
public class Wielomian {
int wsp;
int a;
int b;
int c;
public Wielomian(){
wsp=0;
a=-1;
b=-1;
c=-1;
}
public Wielomian(int wsp, int a, int b, int c){
this.wsp = wsp;
this.a = a;
this.b = b;
this.c = c;
}
public String toString(){
return wsp+"(x^"+a+")(y^"+b+")(z^"+c+")";
}
}
wsp is coefficient and a,b,c are exponents of x, y and z.
Node:
public class Node {
protected Object data;
protected Node link;
public Node() {
link = null;
data = 0;
}
public Node(Object d,Node n) {
data = d;
link = n;
}
public void setLink(Node n) {
link = n;
}
public void setData(Object d) {
data = d;
}
public Node getLink() {
return link;
}
public Object getData() {
return data;
}
}
List:
class linkedList {
protected Node start ;
protected Node end ;
public int size ;
public linkedList() {
start = null;
end = null;
size = 0;
}
public boolean isEmpty() {
return start == null;
}
public int getSize() {
return size;
}
public void insertAtStart(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Object val , int pos) {
Node nptr = new Node(val,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void deleteAtPos(int pos) {
if (size == 1 && pos == 1) {
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1) {
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size) {
Node s = start;
Node t = start;
while (s != end) {
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++) {
if (i == pos) {
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
}
And I realised I need another add method that will and sort those parts of polynomial while adding - first by exponent of x, if 2 will have equal then by exponent of y and so on.
The elements of list will be parts of polynomial and there also will be "head" which will be linked to the part with highest exponent at "x" and the last part of polynomial will be linked to this "head" making whole list circular. Head will have coefficient that equals 0 and exponats that equal -1 each. But I have no idea how to implement such method without ruining all the links etc. etc. I hope You guys can help me :)
I would also like to know best way to display my polynomial later. Will it be some kind of iteration through parts of polynomial and adding them to String until i reach "head"?

Huffman Encoding - how do I reference to the node in the top of the huffman tree ?

This program should take a file and compress it with the huffman code. My problem is that I have to have Element X to reference to the top of the huffman tree, in my Coder method:
public static String Coder(Element Z){
Element X = Z;
if(Z != null){
Coder(Z.left);
if(Z.isleaf()){
Element K = Z;
Code = "";
while(K != X){ //here I want X to be reference the top of my huffman tree
if(K == K.parent.left){
Code = Code+0;
}else{
Code = Code+1;
}
K = K.parent;
}
}Coder(Z.right);
}
return Code;
}
}
So that X doesn't gets override while running Coder recursively.
Nodes in this program is called Element. pq is part of another program that is a prioritycue with a heap structure.
This is the hole Encode Class
import java.io.FileInputStream;
public class Encode{
static int[] Freq=new int[256];
static PQ pq = new PQHeap(256);
static String Code;
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("C:\\Java\\testfilen.txt");
Inputstream.Inputs(fis);
for(int i=0; i<Freq.length; i++){
pq.insert(new Element(Freq[i],new Integer(i)));
}
Element Z = Huffman();
String K = Coder(Z);
System.out.println(K);
}
public static Element Huffman(){
int n = Freq.length;
for(int i=1; i<=n-1; i++){
Element z = new Element(0, 0);
Element x=pq.extractMin();
z.left=x;
Element y=pq.extractMin();
z.right=y;
z.key = y.key+x.key;
pq.insert(z);
}
return pq.extractMin();
}
public static String Coder(Element Z){
Element X = Z;
if(Z != null){
Coder(Z.left);
if(Z.isleaf()){
Element K = Z;
Code = "";
while(K != X){
if(K == K.parent.left){
Code = Code+0;
}else{
Code = Code+1;
}
K = K.parent;
}
}Coder(Z.right);
}
return Code;
}
}
This is the Element class
public class Element {
public int key;
public Object data;
public Element parent;
public Element left;
public Element right;
public Element(int i, Object o){
this.key = i;
this.data = o;
this.parent = null;
this.left=null;
this.right=null;
}
public boolean isleaf(){
if(this.left == null && this.right == null){
return true;
}else{
return false;
}
}
}

Categories