Polynomials in Java - java

My add method works, however when I create a new SparsePolynomial object (at the bottom of the add method), the value of the newSparePolynomial changes when I debug it and I can't figure out where the extra information is coming from. Can someone help me?
Here is a copy of my code:
import java.util.ArrayList;
public class SparsePolynomial {
private ArrayList<Polynomial> polynomialarraylist = new ArrayList<Polynomial>();
/**
* Constructor to get values of an arraylist of integers
* #param arraylist that contains the integer values used for the polynomials
*/
public SparsePolynomial(ArrayList<Integer> arrayList)
{
//MODIFIDED: polynomialarraylist
//EFFECT: constructs the arraylist of polynomials based off the arraylist of integers
insertIntoPolynomialArray(arrayList);
}
/**
* Converts the elements of the integer array into polynomials
* #param arrayList that contains the polynomials contents
*/
private void insertIntoPolynomialArray(ArrayList<Integer> arrayList)
{
//MODIFIED: polynomialarray
//EFFECT: inputs the values of the arrayList into the polynomial array based on the position of the digits
for(int i = 0; i < arrayList.size(); i++)
{
Polynomial polynomial = new Polynomial(arrayList.get(i), arrayList.get(i+1));
polynomialarraylist.add(polynomial);
System.out.println("coef" + arrayList.get(i));
System.out.println("degree" + arrayList.get(i+1));
i++;
}
}
/**
*
*/
#Override
public String toString()
{
String result = "";
sort();
if (getDegree(0) == 0)
return "" + getCoefficient(0);
if (getDegree(0) == 1)
return getCoefficient(0) + "x + " + getCoefficient(0);
result = getCoefficient(0) + "x^" + getDegree(0);
for (int j = 1; j < polynomialarraylist.size(); j++)
{
if(j > polynomialarraylist.size())
{
break;
}
if
(getCoefficient(j) == 0) continue;
else if
(getCoefficient(j) > 0) result = result+ " + " + ( getCoefficient(j));
else if
(getCoefficient(j) < 0) result = result+ " - " + (-getCoefficient(j));
if(getDegree(j) == 1) result = result + "x";
else if (getDegree(j) > 1) result = result + "x^" + getDegree(j);
}
return result;
}
/**
* Sorts array
* #param array to sort
*/
private void sort()
{
ArrayList<Polynomial> temp = polynomialarraylist;
ArrayList<Polynomial> temp2 = new ArrayList<Polynomial>();
int polydegreemain = polynomialarraylist.get(0).degree();
temp2.add(polynomialarraylist.get(0));
for(int i = 1; i < polynomialarraylist.size(); i++)
{
if(i > polynomialarraylist.size())
{
break;
}
int polydegreesecondary = polynomialarraylist.get(i).degree();
if(polydegreemain < polydegreesecondary)
{
temp.set(i-1, polynomialarraylist.get(i));
temp.set(i, temp2.get(0));
}
}
polynomialarraylist = temp;
}
/**
* Makes object hashable
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((polynomialarraylist == null) ? 0 : polynomialarraylist
.hashCode());
return result;
}
/**
* Checks for equality of two objects
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SparsePolynomial other = (SparsePolynomial) obj;
if (polynomialarraylist == null) {
if (other.polynomialarraylist != null)
return false;
} else if (!polynomialarraylist.equals(other.polynomialarraylist))
return false;
return true;
}
public boolean equals(SparsePolynomial Sparse)
{
if(this == Sparse)
{
return true;
}
else
{
return false;
}
}
public SparsePolynomial add(SparsePolynomial other)
{
ArrayList<Polynomial> thisPolynomial = createPolynomial();
SparsePolynomial newSparsePolynomial;
ArrayList<Polynomial> otherPolynomial = other.createPolynomial();
Polynomial oldsum = new Polynomial();
Polynomial newsum = new Polynomial();
for(int i = 0; i < thisPolynomial.size();i++)
{
if(thisPolynomial.size() == 1)
{
newsum = thisPolynomial.get(i);
oldsum = newsum;
break;
}
if(i == 0)
{
newsum = thisPolynomial.get(i).add(thisPolynomial.get(i+1));
oldsum = newsum;
i++;
}
else
{
newsum = oldsum.add(thisPolynomial.get(i));
oldsum = newsum;
}
}
for(int i = 0; i < otherPolynomial.size(); i++)
{
newsum = oldsum.add(otherPolynomial.get(i));
oldsum = newsum;
}
ArrayList<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < oldsum.degree()+1; i++)
{
ints.add(oldsum.coefficient(i));
ints.add(i);
}
newSparsePolynomial = new SparsePolynomial(ints);
return newSparsePolynomial;
}
public SparsePolynomial subtract(SparsePolynomial other)
{
ArrayList<Polynomial> thisPolynomial = createPolynomial();
ArrayList<Polynomial> otherPolynomial = other.createPolynomial();
Polynomial olddifference = new Polynomial();
Polynomial newdifference = new Polynomial();
for(int i = 0; i < thisPolynomial.size()+1;i++)
{
if(i == 0)
{
newdifference = thisPolynomial.get(i).subtract(thisPolynomial.get(i+1));
olddifference = newdifference;
i++;
}
else
{
newdifference = olddifference.subtract(thisPolynomial.get(i));
olddifference = newdifference;
}
}
for(int i = 0; i < otherPolynomial.size(); i++)
{
newdifference = olddifference.add(otherPolynomial.get(i));
olddifference = newdifference;
}
ArrayList<Polynomial> polyarray = createArrayListOfPolynomialsFromPolynomials(olddifference);
ArrayList<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < polyarray.size(); i++)
{
ints.add(polyarray.get(i).coefficient(polyarray.get(i).degree()));
ints.add(polyarray.get(i).degree());
}
SparsePolynomial newSparsePolynomial = new SparsePolynomial(ints);
return newSparsePolynomial;
}
private int getDegree(int index)
{
int degree;
degree = polynomialarraylist.get(index).degree();
return degree;
}
private int getCoefficient(int index)
{
int coefficient;
coefficient = polynomialarraylist.get(index).coefficient(polynomialarraylist.get(index).degree());
return coefficient;
}
private ArrayList<Polynomial> createPolynomial()
{
Polynomial polynomial = null;
ArrayList<Polynomial> polynomialArray = new ArrayList<Polynomial>();
for(int i = 0; i < polynomialarraylist.size(); i++)
{
polynomial = new Polynomial(getCoefficient(i), getDegree(i));
polynomialArray.add(polynomial);
}
return polynomialArray;
}
Polynomial class
public class Polynomial {
// Overview: ...
private int[] terms;
private int degree;
// Constructors
public Polynomial() {
// Effects: Initializes this to be the zero polynomial
terms = new int[1];
degree = 0;
}
public Polynomial(int constant, int power) {
// Effects: if n < 0 throws IllegalArgumentException else
// initializes this to be the polynomial c*x^n
if(power < 0){
throw new IllegalArgumentException("Polynomial(int, int) constructor");
}
if(constant == 0) {
terms = new int[1];
degree = 0;
return;
}
terms = new int[power+1];
for(int i=0; i<power; i++) {
terms[i] = 0;
}
terms[power] = constant;
degree = power;
}
private Polynomial(int power) {
terms = new int[power+1];
degree = power;
}
// Methods
public int degree() {
// Effects: Returns the degree of this, i.e., the largest exponent
// with a non-zero coefficient. Returns 0 is this is the zero polynomial
return degree;
}
public int coefficient(int degree) {
// Effects: Returns the coefficient of the term of this whose exponent is degree
if(degree < 0 || degree > this.degree) {
return 0;
}
else {
return terms[degree];
}
}
public Polynomial subtract(Polynomial other) throws NullPointerException {
// Effects: if other is null throws a NullPointerException else
// returns the Polynomial this - other
return add(other.minus());
}
public Polynomial minus() {
// Effects: Returns the polynomial - this
Polynomial result = new Polynomial(degree);
for(int i=0; i<=degree; i++) {
result.terms[i] = -this.terms[i];
}
return result;
}
public Polynomial add(Polynomial other) throws NullPointerException {
// Effects: If other is null throws NullPointerException else
// returns the Polynomial this + other
Polynomial larger, smaller;
if (degree > other.degree){
larger = this;
smaller = other;
}
else {
larger = other;
smaller = this;
}
int newDegree = larger.degree;
if (degree == other.degree) {
for(int k = degree; k > 0 ; k--) {
if (this.terms[k] + other.terms[k] != 0) {
break;
}
else {
newDegree --;
}
}
}
Polynomial newPoly = new Polynomial(newDegree);
int i;
for (i=0; i <= smaller.degree && i <= newDegree; i++){
newPoly.terms[i] = smaller.terms[i] + larger.terms[i];
}
for(int j=i; j <= newDegree; j++) {
newPoly.terms[j] = larger.terms[j];
}
return newPoly;
}
public Polynomial multiply(Polynomial other) throws NullPointerException {
// Effects: If other is null throws NullPointerException else
// returns the Polynomial this * other
if ((other.degree == 0 && other.terms[0] == 0) ||
(this.degree==0 && this.terms[0] == 0)) {
return new Polynomial();
}
Polynomial newPoly = new Polynomial(degree + other.degree);
newPoly.terms[degree + other.degree] = 0;
for(int i=0; i<=degree; i++) {
for (int j=0; j<= other.degree; j++) {
newPoly.terms[i+j] = newPoly.terms[i+j] + this.terms[i] * other.terms[j];
}
}
return newPoly;
}

At quick glance, looks like this is a problem
for(int i = 0; i < arrayList.size(); i++)
{
Polynomial polynomial = new Polynomial(arrayList.get(i), arrayList.get(i+1));
polynomialarraylist.add(polynomial);
System.out.println("coef" + arrayList.get(i));
System.out.println("degree" + arrayList.get(i+1));
i++;
}
You're doing i++ twice here.
Also, you posted WAY too much code. No one wants to read that much. You're just lucky that, assuming this is the problem, I happened to glance at that.
Also that will throw an arrayindexoutofboundserror since you're doing .get(i+1)

the constructor is set up the way it is because the get(i) gets you the coefficient and the i+1 gets you the degree from the arraylist parameter since when you call add, without those the arraylist contents would be off
THe constructor is suppose to take an Arraylist and put them inisde of an arraylist of polynomials. using the odds as the coefficient and the evens as the degrees of the polynomials.

Related

Implementing Huffman class into another class

I almost have a working Huffman algorithm but I'm having trouble figuring out how to implement it / or make it work together with the Code class. It is my method generateHuffmanCode that needs to be working with the Code class.
I don't know if I'm missing something or if I'm just using the wrong approach.
My Huffman class
package code;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import code.Code;
import application.TCode;
class Node{
Character ch;
Integer freq;
Node left = null, right = null;
Node(Character ch, Integer freq){
this.ch = ch;
this.freq = freq;
}
public Node (Character ch, Integer freq, Node left, Node right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
}
public class Huffman {
public static void encode(Node root, String str, Map<Character, String> huffmanCode) {
if (root == null) {
return;
}
if(isLeaf(root)) {
huffmanCode.put(root.ch, str.length() > 0 ? str : "1");
}
encode(root.left, str + '0', huffmanCode);
encode(root.right, str + '1', huffmanCode);
}
public static int decode(Node root, int index, StringBuilder sb) {
if(root == null) {
return index;
}
index++;
if(isLeaf(root)) {
System.out.println(root.ch);
}
index++;
root = (sb.charAt(index) == '0') ? root.left : root.right;
index = decode(root, index, sb);
return index;
}
public static boolean isLeaf(Node root) {
return root.left == null && root.right == null;
}
public static void generateHuffmanCode(Code c) {
// if(c == null || c.length() == 0) {
// return;
// }
Map<Character, double> freq = new HashMap<>(); // why can't I use a double in Map<Character, double>??
for(char s : probability.toCharArry()){
freq.put(s, freq.getOrDefault(s, 0) + 1);
}
PriorityQueue<Node> pq;
pq = new PriorityQueue<>(Comparator.comparingInt(l -> l.freq));
for(var entry: freq.entrySet()) {
pq.add(new Node(entry.getKey(), entry.getValue()));
}
while (pq.size() != 1) {
Node left = pq.poll();
Node right = pq.poll();
int sum = left.freq + right.freq;
pq.add(new Node(null, sum, left, right));
}
Node root = pq.peek();
Map<Character, String> huffmanCode = new HashMap<>();
encode(root, "", huffmanCode);
System.out.println("Huffman Codes are: " + huffmanCode);
System.out.println(probability);
StringBuilder sb = new StringBuilder();
for(char s : probability.toCharArray()) {
sb.append(huffmanCode.get(s));
}
System.out.println("The endcoded String is: " + sb);
System.out.println("The decoded String is: " );
if (isLeaf(root)) {
while (root.freq-- > 0) {
System.out.println(root.ch);
}
} else {
int index = -1;
while(index < sb.length() - 1) {
index = decode(root, index, sb);
}
}
}
public static void main(String[] args) {
generateHuffmanCode(Code probability);
// Code.CodeItem[] ci = {
// new Code.CodeItem("A", 0.12),
// new Code.CodeItem("B", 0.19),
// new Code.CodeItem("C", 0.40),
// new Code.CodeItem("D", 0.13),
// new Code.CodeItem("E", 0.16)
// };
// Code c = new Code(ci);
}
}
And my Code class
package code;
public final class Code {
private CodeItem[] item = null;
public final static class CodeItem {
private String symbol;
private double probability; // the sum of all probabilities must be approx. 1
private String encoding; // a string containing only '0' and '1'
public CodeItem(String symbol, double probability, String encoding) {
this.symbol = symbol.trim();
this.probability = probability;
this.encoding = encoding;
if (!is01() || this.symbol == null || this.symbol.length() == 0 || this.probability < 0.0)
throw new IllegalArgumentException();
}
public CodeItem(String symbol, double probability) {
this(symbol, probability, null);
}
public String getSymbol() {
return symbol;
}
public double getProbability() {
return probability;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public boolean is01() {
if (encoding == null || encoding.length() == 0)
return true;
for (int i = 0; i < encoding.length(); ++i)
if ("01".indexOf(encoding.charAt(i)) < 0)
return false;
return true;
}
}
public Code(CodeItem[] codeItem) {
if (codeItem == null || codeItem.length == 0)
throw new IllegalArgumentException();
double sum = 0.0;
for (int i = 0; i < codeItem.length; ++i) {
sum += codeItem[i].probability;
if (codeItem[i].probability == 0.0)
throw new IllegalArgumentException();
}
if (Math.abs(sum - 1.0) > 1e-10)
throw new IllegalArgumentException();
item = new CodeItem[codeItem.length];
for (int i = 0; i < codeItem.length; ++i)
item[i] = codeItem[i];
}
public boolean is01() {
for (int i = 0; i < item.length; ++i)
if (!item[i].is01())
return false;
return true;
}
public double entropy() {
double result = 0.0;
for(int i = 0; i < item.length; ++i)
result += item[i].probability * (-Math.log(item[i].probability) / Math.log(2.0));
return result;
}
public double averageWordLength() {
double result = 0.0;
for(int i = 0; i < item.length; ++i)
result += item[i].encoding.length() * item[i].probability;
return result;
}
public boolean isPrefixCode() {
for(int i = 1; i < item.length; ++i)
for(int j = 0; j < i; ++j)
if (item[i].encoding.startsWith(item[j].encoding) || item[j].encoding.startsWith(item[i].encoding))
return false;
return true;
}
public int size() {
return item.length;
}
public CodeItem getAt(int index) {
return item[index];
}
public CodeItem getBySymbol(String symbol) {
for (int i = 0; i < item.length; ++i) {
if (item[i].symbol.equals(symbol))
return item[i];
}
return null;
}
public String toString() {
String result = "";
for(int i = 0; i < item.length; ++i) {
result += item[i].symbol + " (" + item[i].probability + ") ---> " + item[i].encoding + "\n";
}
return result.substring(0, result.length()-1);
}
}

Java assignment to use Dijkstras search method, breath-first and depth first

Hello StackOverflow community, need your help. I have a final for my java class and its asking for:
Generate a graph with 100,000 nodes, where each node randomly has between 1 and 5 connections to other nodes. Each node should contain within it a random value between 1 and 300,000. (So generally about 1 in 3 searches will yield a query match). Allow the user to enter a number to search for, and implement each of the following three types of searching algorithms. Breadth-First. (30 points) Depth-First. (30 points) Dijkstra's Algorithm. (40 points)
Do not allow back-tracking in your searches. (Mark nodes that you already searched as complete, and do not re-visit them in the same search). Each search should return the following: The Success/Failure of your search. The length of the shortest path to the found node. The total number of nodes examined during the search. Optionally you may return the exhaustive display of the shortest path, for testing and verification.
For some reason, my IDE shows that BFS and Dijkstras has "duplicated code fragment 17 lines long" can someone look at tell me how to fix it or maybe a better way to implement it? Also, if i try to do nodesNum > 30k in "Driver Class" i get a memory leak.
Here is the code:
Class Graph:
import java.util.*;
import javax.swing.JOptionPane;
class Graph
{
private Listing[] vertex;
private int[][] edge;
private int max;
private int numberOfVertices;
private int nodeCheck = 0;
private int selectNum = 0;
Graph(int g)
{
vertex = new Listing[g];
edge = new int[g][g];
max = g;
numberOfVertices = 0;
}
private void depthFirstSearch(int firstVertex)
{
int v;
Stack<Integer> nodeStack = new Stack<>();
for(int i = 0; i<numberOfVertices; i++)
{
if (vertex[i] != null) {
vertex[i].setPushed(false);
}
}
nodeStack.push(firstVertex);
vertex[firstVertex].setPushed(true);
while (!nodeStack.empty())
{
v = nodeStack.pop();
vertex[v].visit();
nodeCheck++;
for (int column = 0; column < numberOfVertices; column++)
{
if(edge[v][column] == 1 && vertex[column].getPushed())
{
nodeStack.push(column);
vertex[column].setPushed(true);
}
}
}
}
private void breathFirstSearch(int firstVertex)
{
int V;
Queue<Integer> nodeQueue = new LinkedList<>();
for(int i = 0; i < numberOfVertices; i++)
{
if(vertex[i] != null)
vertex[i].setPushed(false);
}
nodeQueue.add(firstVertex);
vertex[firstVertex].setPushed(true);
while(!nodeQueue.isEmpty())
{
V = nodeQueue.remove();
vertex[V].visit();
nodeCheck++;
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[V][column] == 1 && vertex[column].getPushed())
{
nodeQueue.add(column);
vertex[column].setPushed(true);
}
}
}
}
private void Dijkstra(int firstVertex)
{
int v;
LinkedList<Integer> nodeQueue = new LinkedList<>();
int i = 0;
while (i < numberOfVertices)
{
if(vertex[i] != null)
vertex[i].setPushed(false);
i++;
}
nodeQueue.add(firstVertex);
vertex[firstVertex].setPushed(true);
while(!nodeQueue.isEmpty())
{
v = nodeQueue.remove();
vertex[v].visit();
nodeCheck++;
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[v][column] == 1 && vertex[column].getPushed())
{
nodeQueue.add(column);
vertex[column].setPushed(true);
}
}
}
}
private void insertVertex(int vertexNumber, Listing newListing)
{
if(vertexNumber >= max)
{
return;
}
vertex[vertexNumber] = newListing.deepCopy();
numberOfVertices++;
}
private void insertEdge(int fromVertex, int toVertex)
{
if(vertex[fromVertex] == null || vertex[toVertex] == null)
return;
edge[fromVertex][toVertex] = 1;
}
void showVertex(int vertexNumber)
{
System.out.print(vertex[vertexNumber]);
}
void showEdges(int vertexNumber)
{
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[vertexNumber][column] == 1)
{
System.out.println(vertexNumber + "," + column);
}
}
System.out.println();
}
void InitializeNodes(Graph G, int nodesNum)
{
Random random = new Random();
for (int i = 0; i < nodesNum; i++ )
{
Listing v = new Listing(random.nextInt(300000) + 1);
G.insertVertex(i, v);
}
int vertexListNumber = G.vertex.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nodesNum; i++ )
{
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < vertexListNumber; i++ )
{
int randnum = random.nextInt(5);
for (int j = 0; j < randnum; j++ )
{
int rand = random.nextInt(5);
G.insertEdge(i, list.get(rand));
}
}
}
int Search()
{
String search = JOptionPane.showInputDialog("Enter Node to search:");
try
{
if(search != null)
{
selectNum = Integer.parseInt(search);
}
}
catch (NumberFormatException e)
{
selectNum = 0;
}
return selectNum;
}
private int SelectPane()
{
String paneSelect = JOptionPane.showInputDialog("Choose a search method:" +
"\n\t1: Use Depth-First Search" +
"\n\t2: Use Breadth-First Search" +
"\n\t3: Use Dijkstra's Search" +
"\n\t4: Close Program");
int selectNum = 0;
try{
if(paneSelect != null)
{
selectNum = Integer.parseInt(paneSelect);
}
}
catch (NumberFormatException ignored)
{
}
return selectNum;
}
void algorithmChoice(Graph graph, int vertexStart)
{
int paneNum = 0;
while (paneNum != 4)
{
paneNum = SelectPane();
switch (paneNum)
{
case 1:
graph.depthFirstSearch(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 2:
graph.breathFirstSearch(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 3:
graph.Dijkstra(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 4:
break;
default:
JOptionPane.showMessageDialog(null, "Enter 4 to quit.");
break;
}
}
}
}
Class Listing:
public class Listing
{
private int value;
private boolean pushed;
Listing(int v)
{
value = v;
}
public String toString()
{
return ("Vertex: " + value + "\n" );
}
Listing deepCopy()
{
return new Listing(value);
}
boolean getPushed()
{
return !pushed;
}
void setPushed(boolean value)
{
pushed = value;
}
void visit()
{
System.out.println(this);
}
}
Class Driver:
public class Driver
{
public static void main(String[] args)
{
int nodesNum = 30000; //Can go up to 30k nodes, otherwise causes memory leak.
Graph graph = new Graph(nodesNum);
graph.InitializeNodes(graph, nodesNum);
for(int i = 0; i<5; i++)
{
System.out.print("Node " + i + "\'s ");
graph.showVertex(i);
System.out.print("Its routes are:\n");
graph.showEdges(i);
}
int select = graph.Search();
graph.algorithmChoice(graph, select);
}
}
Thanks alot for your help!
The error you get is due to exceeding max heap size when creating a edge = new int[g][g]; where g can be as high as 100,000 in your case.
I would suggest avoiding the use of such huge matrix.
Instead introduce an Edge object :
class Edge{
private final int fromVertex, toVertex;
Edge(int fromVertex, int toVertex){
this.fromVertex = fromVertex;
this.toVertex = toVertex;
}
#Override
public boolean equals(Object obj) {
if( ! (obj instanceof Edge)) return false;
Edge other = (Edge)obj;
return connects(other.fromVertex, other.toVertex);
}
boolean connects(int fromVertex, int toVertex){
return fromVertex == this.fromVertex && toVertex == this.toVertex ||
fromVertex == this.toVertex && toVertex == this.fromVertex;
}
}
and use it in Graph.
Instead of private int[][] edge; use a collection of Edges:
private final Set<Edge> edges = new HashSet<>();
Change insertEdge to:
private void insertEdge(int fromVertex, int toVertex)
{
if(vertex[fromVertex] == null || vertex[toVertex] == null)
return;
edges.add(new Edge(fromVertex, toVertex));
}
and add a method to check if there is an edge between two vertices:
private boolean isEdgeBetween(int fromVertex, int toVertex)
{
for(Edge edge : edges){
if(edge.connects(fromVertex, toVertex)) return true;
}
return false;
}
Usage : if( isEdgeBetween(v,column) && vertex[column].getPushed())
instead of: if(edge[v][column] == 1 && vertex[column].getPushed())

I'm trying to perform integer division on numbers greater than size of any data type available

As far big numbers are concerned, i know there is a class available in java BigInteger, but i have a constraint that i can't use this and i have to perform division without using library.
This is what i have tried so far, but got memory leakage issues and not getting any answer
private Integer getDivisionResult(ArrayList<Integer> first, ArrayList<Integer> second) {
int firstLength = first.size();
int secondLength = second.size();
int counter = 0;
if (firstLength < secondLength) {
return counter;
}
do {
int carry = 0, cursor1 = firstLength - 1, cursor2 = secondLength - 1;
for (int i = firstLength - 1; i >= 0; i--, cursor1--, secondLength--) {
int value = 0, from = 0;
from = first.get(cursor1) - carry;
if (from < (cursor2 < 0 ? 0 : second.get(cursor2))) {
if (cursor1 > 0) {
from = 10 + from;
}
carry = 1;
} else {
carry = 0;
}
value = from - (cursor2 < 0 ? 0 : second.get(cursor2));
first.set(i, value);
}
counter++;
}while (isLesserThan(second,first));
return counter;
}
private boolean isLesserThan(ArrayList<Integer> list, ArrayList<Integer> firstList) {
boolean result = true;
if (list.size() < firstList.size()) {
return true;
}
for (int i = 0; i < list.size(); i++) {
if (firstList.get(i) > list.get(i)) {
result = true;
break;
} else if (firstList.get(i) == list.get(i)) {
continue;
} else {
result = false;
break;
}
}
return result;
}
I'm calling getDivisionResult inside this method, after passing certain error cases:
/**
* #param numOne
* #param numTwo
* #return sign : true (negative) , false (positive)
*/
public Result getResult(String numOne, String numTwo) {
Result result = new Result();
int res = 0;
boolean sign = false;
ArrayList<Integer> firstNum;
ArrayList<Integer> secondNum;
if (isNegative(numOne)) {
firstNum = getArray(numOne.substring(1));
if (isNegative(numTwo)) {
sign = false;
secondNum = getArray(numTwo.substring(1));
} else {
secondNum = getArray(numTwo);
sign = true;
}
} else {
firstNum = getArray(numOne);
if (isNegative(numTwo)) {
sign = true;
secondNum = getArray(numTwo.substring(1));
} else {
secondNum = getArray(numTwo);
}
}
if (isNull(secondNum)) {
result.setSign("Division by 0 is not permissable");
result.setValue(res);
return result;
} else {
if (isNull(firstNum)) {
result.setSign("");
result.setValue(res);
return result;
}
firstNum = getNumberWithoutZeroes(firstNum);
secondNum = getNumberWithoutZeroes(secondNum);
res = getDivisionResult(firstNum, secondNum);
if (sign) {
result.setSign("-");
} else {
result.setSign("");
}
result.setValue(res);
}
return result;
}
private ArrayList<Integer> getNumberWithoutZeroes(ArrayList<Integer> num) {
ArrayList<Integer> list = new ArrayList<>();
for (Integer x : num) {
if (x == 0) {
continue;
} else {
list.add(x);
}
}
return list;
}
private boolean isNegative(String num) {
boolean result = false;
if (num.startsWith("-")) {
result = true;
}
return result;
}
private boolean isNull(ArrayList<Integer> num) {
boolean result = true;
for (Integer x : num) {
if (x > 0) {
result = false;
}
}
return result;
}
private ArrayList<Integer> getArray(String num) {
ArrayList<Integer> list = new ArrayList<>();
char[] arr = num.toCharArray();
for (int i = 0; i < num.length(); i++) {
list.add(Integer.valueOf(arr[i]));
}
return list;
}
if someone can help me to give a better solution to my problem, I would be grateful
I've made the solution to my own problem, but the problem now is its processing speed.

Java, constructor not working

So in a few words i made a class extending the RandomGenerator to randomly giving back PRIME, POWER OF 2(2,4,8,16,32,64,128 etc) , FIBONACCI AND SQUARE NUMBERS (1,4,9,16,25,36 etc). Then i made a simple program to call my class and giving back random numbers while the user defines the space (1,n). Both programs compile just fine. My problem is that when i run the program it always returns 0 for each value. I'm new to java. Can anyone help me?
import acm.util.*;
public class RandomGeneratorImproved2 extends RandomGenerator
{
private int i,j,a,c,d,e,temp,n,Pnumber,Fnumber,number2,numbersq;
private long b;
boolean flag,flag2,flag3,flag4,flag5;
private double temp1;
public RandomGeneratorImproved2 (int n)
{
this.n = n;
}
public void nextPrime(int n) // PRIME NUMBERS
{
Pnumber = rgen.nextInt(1, n);
i=2;
flag2 = false;
if ( Pnumber == 1 ) // Check for value 1 cause it cannot check it inside the loop
{
flag2=true;
}
while ( (i<n) && (flag2 == false) )
{
flag = true;
j=2;
do
{
a = i%j;
if ( (a == 0) && (i != j) )
{
flag = false;
}
if (i!=j-1)
{
j = j+1;
}
} while ( j<i );
if ((flag == true) && (Pnumber==i)) //
{
flag2 = true;
}
if ((i==99) && (flag2==false)) // restart if the number is not prime
{
i = 1;
Pnumber = rgen.nextInt(1, n);
}
i = i + 1;
}
}
public int getPrime() //POWER OF 2 NUMBERS
{
return Pnumber;
}
public void nextPowerof2(int n)
{
number2 = rgen.nextInt(1, n);
i=1;
b=2;
flag3 = false;
while ( i<n ) // n <= 31
{
if (number2 == b)
{
flag3 = true;
}
b = 2*b;
if ((i == n-1) && (flag3==false))
{
i=1;
number2 = rgen.nextInt(1,n);
b=2;
}
i=i+1;
}
}
public int getPowerof2()
{
return number2;
}
public void nextFibonacciNumber(int n) // FIBONACCI NUMBERS
{
Fnumber = rgen.nextInt(1, n);
c=0;
d=1;
flag4 = false;
i=1;
while ( i<n && flag4==false )
{
temp = d;
d = d + c;
c = temp;
i=i+1;
if (Fnumber == d)
{
flag4 = true;
}
if ((flag4 == false) && (i==n))
{
i=1;
c=0;
d=1;
Fnumber = rgen.nextInt(1, n);
}
}
}
public int getFibonacciNumber()
{
return Fnumber;
}
public void setSquareNumber(int n) // SQUARE NUMBERS
{
numbersq = rgen.nextInt(1, n);
flag5 = false;
i=1;
temp1 = Math.sqrt(n);
while ( i<temp1 && flag5 == false )
{
e = i*i;
i = i + 1;
if ( numbersq == e )
{
flag5 = true;
}
if ( i == 20 && flag5 == false )
{
i=1;
numbersq = rgen.nextInt(1, n);
}
}
}
public int getSquareNumber()
{
return numbersq;
}
public String toString()
{
return "Your Prime number is : " + Pnumber + "\nYour Power of 2 number is : " + number2 + "\nYour Fibonacci number is : " + Fnumber + "\nYour square number is : " + numbersq;
}
private RandomGenerator rgen = RandomGenerator.getInstance();
}
import acm.program.*;
public class caller2 extends Program
{
public void run()
{
int n = readInt("Please give me an integer to define the space that i'll look for numbers : ");
RandomGeneratorImproved2 r1 = new RandomGeneratorImproved2(n);
println(r1);
}
}
As stated you've only defined those method. You never call any of the methods that are setting those values so all are still in their initialized state. Try adding the following to the constructor after setting n;
nextPrime(n);
nextFibonaccitNumber(n);
nextPowerof2(n);

Odd return on PEMDAS calculator

It seems that this calculator works for all other cases, except cases like this:
(2*3^4)
It does not return 162, instead, it returns 0.0.
I identified that the error must be from the method public static double operation, since the default return statement is 0.0
Here is the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StackC<Item> implements Stack<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
public StackC() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4)
resize(a.length/2);
return item;
}
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
return a[N-1];
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
public ReverseArrayIterator() {
i = N;
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
//---------------------------------------------------------------------
public static void main(String[] args) {
StackC<String> Operator = new StackC<String>();
StackC<Double> Values = new StackC<Double>();
while (!StdIn.isEmpty()) {
String token = StdIn.readString();
try {
Double x = Double.parseDouble(token);
Values.push(x);
}
catch(NumberFormatException nFE) {
}
if (token.equals("("))
Operator.push(token);
if (token.equals(")"))
{
if (Operator.peek() != "(")
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
Operator.pop();
}
if(token.equals("*") || token.equals("+") || token.equals("/") || token.equals("-") || token.equals("^") )
{
if(!Operator.isEmpty())
{
String prev = Operator.peek();
int x = comparePrecedence(token, Operator.peek()); // You need to compare precedence first
if(x == -1 || x == 0)
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
}
Operator.push(token);
}
}
while(!Operator.isEmpty())
{
String prev = Operator.peek();
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
System.out.println(Values.pop());
}
public static double operation(String operator, double a, double b) {
if (operator.equals("+"))
return a + b;
else if (operator.equals("-"))
return a - b;
else if (operator.equals("*"))
return a * b;
else if (operator.equals("/"))
return a / b;
else if (operator.equals("^"))
return Math.pow(a,b);
return 0.0;
}
public static int comparePrecedence(String x, String y)
{
int val1 = 0;
int val2 = 0;
if(x.equals("-"))
val1 = 0;
if(y.equals("-"))
val2 = 0;
if(x.equals("+"))
val1 = 1;
if(y.equals("+"))
val2 = 1;
if(x.equals("/"))
val1 = 2;
if(y.equals("/"))
val2 = 2;
if(x.equals("*"))
val1 = 3;
if(y.equals("*"))
val2 = 3;
if(x.equals("^"))
val1 = 4;
if(y.equals("^"))
val2 = 4;
if(val1 > val2)
return 1;
else if(val2 > val1)
return -1;
else
return 0;
}
}
Everything above the dotted line was given via the professor, and is not the problem for the code.
StdIn is simply a method that reads inputs.

Categories