Related
I'm doing a program , it is about an "object" (element) that move in 8way direction based on input.
My questions are : How can I make this element to visit cells of the board (2D Array) only once? How do I make it stay it current position if it can not move according to rules?
Start is position (0,0)
As input it get n-> number of dimension Matrix n x n , direction and t-> seconds. The other thing I don't get how to implement is input seconds, I get input seconds and directions because based on those I have to move the element into this 2D array list.
I've completed mostly of the program. I can give you my code here if you want to check it and give me advice. I'm stuck in it and I need help.
I want to print number of cells that are not visited. My idea is to give a number 0 to all cells that are not visited and the rest that are visited give number 1 as value. Like cell[x][x]=1; And in the end I count all cells that have number 0 as value and print count.
For a valid move in a particular direction, the object must move to a previously unoccupied cell, or else wait until the next direction.
You have defined cell[row][col] to represent the visited state; 0=unvisited, 1=visited. At the end, the number of unvisited cells will be the number of cell elements equal to zero.
To determine if the object should be moved, two checks must be done:
Make sure the next position is a valid matrix position (you are doing this correctly)
Make sure the next position has not yet been visited (will show below)
// Iterate through all k movements
for (i = 0; i < arrTime.length - 1; i++) {
// Move by 1 second until reach next instruction
for (j = arrTime[i]; j < arrTime[i + 1]; j++) {
// South East
if (arrDirection[i].equals("SE")) {
// Check #1 above (a valid matrix position)
if (nCurrRow < n - 1 && nCurrCol < n - 1) {
// Check #2 above (only move into unvisited position)
if (cell[nCurrRow+1][nCurrCol+1] == 0) {
// Move, and record that cell has been visited
nCurrRow++;
nCurrCol++;
cell[nCurrRow][nCurrCol] = 1;
}
}
}
// Other directions following the template for South East
Now to count unvisited cells:
int unVisited=0;
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
if (cell[i][j] == 0) unVisited++;
EDIT: To describe the two issues with the code.
1) The first issue relates to the j loop. The current j loop is
for(j = arrTime[i]; j <= arrTime[i + 1]; j++)
But must be:
for(j = arrTime[i]; j < arrTime[i + 1]; j++)
The way it was moves the object one more time than it should
2) The final movement was not being performed. The original code was:
arrTime[k] = arrTime[k - 1];
But must be:
arrTime[k] = arrTime[k - 1] + n;
Once you make these two changes, both test cases will work.
EDIT #2: A way to reduce the j loop
Previously, the j loop would run each iteration to the next i value. Here, we short circuit and leave the j loop as soon the object is unable to move. In the second test case, this reduced the number of j iterations from 50 to 28.
for (i = 0; i < arrTime.length - 1; i++) {
boolean canMove = true;
for (j = arrTime[i]; j < arrTime[i + 1] && canMove; j++) {
if (arrDirection[i].equals("SE")) {
if (nCurrRow < n - 1 && nCurrCol < n - 1 && cell[nCurrRow + 1][nCurrCol + 1] == 0) {
nCurrRow++;
nCurrCol++;
cell[nCurrRow][nCurrCol] = 1;
} else
canMove = false;
} else if (arrDirection[i].equals("NE")) {
if (nCurrRow > 0 && nCurrCol < n - 1 && cell[nCurrRow - 1][nCurrCol + 1] == 0) {
nCurrRow--;
nCurrCol++;
cell[nCurrRow][nCurrCol] = 1;
} else
canMove = false;
} ...
EDIT: Looking for test cases that will fail
Looking at your new comments, it is legal that the wind changes when t=1000000 (the maximum allowed value for t).
Consider this very simple test case:
3 2 (3x3 matrix, two wind changes)
0 E (wind blows east right away; robot moves to 0,2)
1000000 S (wind blows south at 1000000s, robot should move to 2,2)
Result should be: 4, but your current code will give 6 because it doesn't accept t=1000000.
If you change the line:
if(seconds >=0 && seconds<1000000 && k >=2 && k<1000000) {
to
if(seconds >=0 && seconds<=1000000 && k >=2 && k<=1000000) {
Then you get the expected answer of 4. It is very likely that at least one test case will push all the input boundaries, including when t=1000000.
EDIT: Faster algorithm #2
The current algorithm can be improved by reducing the number of if statements. There are two important improvements:
1) The former code had to use if to check both a) Valid matrix location b) If the location had been previously visited. You can use one 1 if for this, if you create a border around the matrix, and pre-populate with the value 1. Because of the border, the starting position is 1,1 and not 0,0.
2) Inside the j loop, the code unnecessarily looked up the direction. Now the direction is determined prior to the j loop, making the code inside the j loop much faster.
Also the number of unvisited cells is dynamic; no need to count them after the i loop completes. I changed the type to long because when n gets large, then the number of unvisited cells can be up to n*n which requires a type long. This might solve some of the incorrect answers.
If you study the new code, compare it to the older one, you will see many less if statements. This should scale better under larger test cases. Lets see if some of the test cases that were timing out improve.
public class Robot {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int j = 0;
int i = 0;
int n = in.nextInt();
int k = in.nextInt();
int[] arrTime = new int[k + 1];
String[] arrDirection = new String[k];
for (j = 0; j < k; j++) {
int seconds = in.nextInt();
if (seconds >= 0 && seconds <= 1000000) {
arrTime[j] = seconds;
}
String direction = in.next();
arrDirection[j] = direction;
}
arrTime[k] = arrTime[k - 1] + n;
// Add a border around the matrix with values of 1
int N = n + 2;
int[][] cell = new int[N][N];
for (j = 0; j < cell.length; j++) {
cell[0][j] = 1; // Top border
cell[j][0] = 1; // Left border
cell[j][N - 1] = 1; // Right border
cell[N - 1][j] = 1; // Bottom border
}
int nCurrRow = 1;
int nCurrCol = 1;
cell[nCurrRow][nCurrCol] = 1;
long R = n * n - 1; // Number of remaining unvisited cells
for (i = 0; i < arrTime.length - 1; i++) {
boolean canMove = true;
int xDir = 0;
int yDir = 0;
if (arrDirection[i].equals("SE")) {
xDir = 1;
yDir = 1;
} else if (arrDirection[i].equals("NE")) {
xDir = 1;
yDir = -1;
} else if (arrDirection[i].equals("E")) {
xDir = 1;
} else if (arrDirection[i].equals("N")) {
yDir = -1;
} else if (arrDirection[i].equals("NW")) {
xDir = -1;
yDir = -1;
} else if (arrDirection[i].equals("W")) {
xDir = -1;
} else if (arrDirection[i].equals("SW")) {
xDir = -1;
yDir = 1;
} else if (arrDirection[i].equals("S")) {
yDir = 1;
}
for (j = arrTime[i]; j < arrTime[i + 1] && canMove; j++) {
if (cell[nCurrRow + yDir][nCurrCol + xDir] == 0) {
nCurrRow += yDir;
nCurrCol += xDir;
cell[nCurrRow][nCurrCol] = 1;
R--;
} else
canMove = false;
}
}
//printArray(cell);
System.out.println(R);
in.close();
}
static void printArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr.length; col++)
System.out.print(arr[row][col]);
System.out.println();
}
}
}
EDIT #3: More efficient memory usage; using BitSet
I suspect that the higher test cases are failing because the value of n is large in those cases. It is simple to test that when n=100000 that the cell array is too large, causing java memory error. So this code make the cell array very compact by using bitset. Lets see how this code does:
public class Robot {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int j = 0;
int i = 0;
int n = in.nextInt();
int k = in.nextInt();
int[] arrTime = new int[k + 1];
String[] arrDirection = new String[k];
for (j = 0; j < k; j++) {
int seconds = in.nextInt();
if (seconds >= 0 && seconds <= 1000000) {
arrTime[j] = seconds;
}
String direction = in.next();
arrDirection[j] = direction;
}
if (k >= 2 && k < 1000000) {
arrTime[k] = arrTime[k - 1] + n;
}
int N = n + 2;
BitSet[] cell = new BitSet[N];
for (j = 0; j < cell.length; j++)
cell[j] = new BitSet(N);
for (j = 0; j < cell.length; j++) {
set(cell, 0, j);
set(cell, j, 0);
set(cell, j, N-1);
set(cell, N-1, j);
}
int nCurrRow = 1;
int nCurrCol = 1;
set(cell,nCurrRow,nCurrCol);
long R = n * n - 1;
for (i = 0; i < arrTime.length - 1; i++) {
boolean canMove = true;
int xDir = 0;
int yDir = 0;
if (arrDirection[i].equals("SE")) {
xDir = 1;
yDir = 1;
} else if (arrDirection[i].equals("NE")) {
xDir = 1;
yDir = -1;
} else if (arrDirection[i].equals("E")) {
xDir = 1;
} else if (arrDirection[i].equals("N")) {
yDir = -1;
} else if (arrDirection[i].equals("NW")) {
xDir = -1;
yDir = -1;
} else if (arrDirection[i].equals("W")) {
xDir = -1;
} else if (arrDirection[i].equals("SW")) {
xDir = -1;
yDir = 1;
} else if (arrDirection[i].equals("S")) {
yDir = 1;
}
for (j = arrTime[i]; j < arrTime[i + 1] && canMove; j++) {
if (!isSet(cell,nCurrRow + yDir, nCurrCol + xDir)) {
nCurrRow += yDir;
nCurrCol += xDir;
set(cell,nCurrRow,nCurrCol);
R--;
} else
canMove = false;
}
}
//System.out.println();
//printArray(cell);
System.out.println(R);
in.close();
}
static boolean isSet(BitSet[] cell, int x, int y) {
BitSet b = cell[x];
return b.get(y);
}
static void set(BitSet[] cell, int x, int y) {
BitSet b = cell[x];
b.set(y);
}
static void printArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr.length; col++)
System.out.print(arr[row][col]);
System.out.println();
}
}
}
EDIT: Attempt to read and process at the same time
This technique sometimes helps with large input. Rather than read all the input, then process in a second phase, process it as you read. In this case there is no need to store the data in two arrays (one for arrivalTime and one for direction). Lets see if this helps at all.
public class Robot2 {
static int nCurrRow = 1;
static int nCurrCol = 1;
static long R = 0;
static int[][] cell;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i = 0;
int n = in.nextInt();
int k = in.nextInt();
// Add a border around the matrix with values of 1
int N = n + 2;
cell = new int[N][N];
for (i = 0; i < cell.length; i++) {
cell[0][i] = 1; // Top border
cell[i][0] = 1; // Left border
cell[i][N - 1] = 1; // Right border
cell[N - 1][i] = 1; // Bottom border
}
cell[nCurrRow][nCurrCol] = 1;
R = (long)n * n - 1; // Number of remaining unvisited cells
int sec1 = in.nextInt();
int sec2 = 0;
String dir1 = in.next();
String dir2;
for (i = 0; i < k - 1; i++) {
sec2 = in.nextInt();
dir2 = in.next();
move(sec2-sec1, dir1);
dir1 = dir2;
sec1 = sec2;
}
move(n, dir1);
System.out.println(R);
in.close();
}
static void move(int t, String dir1) {
boolean canMove = true;
int xDir = 0;
int yDir = 0;
if (dir1.equals("SE")) {
xDir = 1;
yDir = 1;
} else if (dir1.equals("NE")) {
xDir = 1;
yDir = -1;
} else if (dir1.equals("E")) {
xDir = 1;
} else if (dir1.equals("N")) {
yDir = -1;
} else if (dir1.equals("NW")) {
xDir = -1;
yDir = -1;
} else if (dir1.equals("W")) {
xDir = -1;
} else if (dir1.equals("SW")) {
xDir = -1;
yDir = 1;
} else if (dir1.equals("S")) {
yDir = 1;
}
for (int j = 0; j < t && canMove; j++) {
if (cell[nCurrRow + yDir][nCurrCol + xDir] == 0) {
nCurrRow += yDir;
nCurrCol += xDir;
cell[nCurrRow][nCurrCol] = 1;
R--;
} else
canMove = false;
}
}
}
EDIT: Combination of BitSet and one phase processing
public class Robot3 {
static int nCurrRow = 1;
static int nCurrCol = 1;
static long R = 0;
static BitSet[] cell;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i = 0;
int n = in.nextInt();
int k = in.nextInt();
// Add a border around the matrix with values of 1
int N = n + 2;
cell = new BitSet[N];
for (i = 0; i < cell.length; i++)
cell[i] = new BitSet(N);
for (i = 0; i < cell.length; i++) {
set(cell, 0, i);
set(cell, i, 0);
set(cell, i, N-1);
set(cell, N-1, i);
}
set(cell, nCurrRow, nCurrCol);
R = (long)n * n - 1; // Number of remaining unvisited cells
int sec1 = in.nextInt();
int sec2 = 0;
String dir1 = in.next();
String dir2;
for (i = 0; i < k - 1; i++) {
sec2 = in.nextInt();
dir2 = in.next();
move(sec2-sec1, dir1);
dir1 = dir2;
sec1 = sec2;
}
move(n, dir1);
System.out.println(R);
in.close();
}
static void move(int t, String dir1) {
boolean canMove = true;
int xDir = 0;
int yDir = 0;
if (dir1.equals("SE")) {
xDir = 1;
yDir = 1;
} else if (dir1.equals("NE")) {
xDir = 1;
yDir = -1;
} else if (dir1.equals("E")) {
xDir = 1;
} else if (dir1.equals("N")) {
yDir = -1;
} else if (dir1.equals("NW")) {
xDir = -1;
yDir = -1;
} else if (dir1.equals("W")) {
xDir = -1;
} else if (dir1.equals("SW")) {
xDir = -1;
yDir = 1;
} else if (dir1.equals("S")) {
yDir = 1;
}
for (int j = 0; j < t && canMove; j++) {
if (!isSet(cell,nCurrRow + yDir, nCurrCol + xDir)) {
nCurrRow += yDir;
nCurrCol += xDir;
set(cell, nCurrRow, nCurrCol);
R--;
} else
canMove = false;
}
}
static boolean isSet(BitSet[] cell, int x, int y) {
return cell[x].get(y);
}
static void set(BitSet[] cell, int x, int y) {
cell[x].set(y);
}
}
EDIT: Replacing Scanner with BufferedReader
There is a chance that Scanner is too slow:
https://www.cpe.ku.ac.th/~jim/java-io.html
This may be worth a try:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.BitSet;
import java.util.StringTokenizer;
public class Robot3 {
static int nCurrRow = 1;
static int nCurrCol = 1;
static long R = 0;
static BitSet[] cell;
public static void main(String[] args) throws IOException {
Reader.init(System.in);
//Scanner in = new Scanner(System.in);
int i = 0;
int n = Reader.nextInt();
int k = Reader.nextInt();
// Add a border around the matrix with values of 1
int N = n + 2;
cell = new BitSet[N];
for (i = 0; i < cell.length; i++)
cell[i] = new BitSet(N);
for (i = 0; i < cell.length; i++) {
set(cell, 0, i);
set(cell, i, 0);
set(cell, i, N-1);
set(cell, N-1, i);
}
set(cell, nCurrRow, nCurrCol);
R = (long)n * n - 1; // Number of remaining unvisited cells
int sec1 = Reader.nextInt();
int sec2 = 0;
String dir1 = Reader.next();
String dir2 = "";
for (i = 0; i < k - 1; i++) {
sec2 = Reader.nextInt();
dir2 = Reader.next();
move(sec2-sec1, dir1);
dir1 = dir2;
sec1 = sec2;
}
move(n, dir1);
System.out.println(R);
}
static void move(int t, String dir1) {
boolean canMove = true;
int xDir = 0;
int yDir = 0;
if (dir1.equals("SE")) {
xDir = 1;
yDir = 1;
} else if (dir1.equals("NE")) {
xDir = 1;
yDir = -1;
} else if (dir1.equals("E")) {
xDir = 1;
} else if (dir1.equals("N")) {
yDir = -1;
} else if (dir1.equals("NW")) {
xDir = -1;
yDir = -1;
} else if (dir1.equals("W")) {
xDir = -1;
} else if (dir1.equals("SW")) {
xDir = -1;
yDir = 1;
} else if (dir1.equals("S")) {
yDir = 1;
}
for (int j = 0; j < t && canMove; j++) {
if (!isSet(cell,nCurrRow + yDir, nCurrCol + xDir)) {
nCurrRow += yDir;
nCurrCol += xDir;
set(cell, nCurrRow, nCurrCol);
R--;
} else
canMove = false;
}
}
static boolean isSet(BitSet[] cell, int x, int y) {
return cell[x].get(y);
}
static void set(BitSet[] cell, int x, int y) {
cell[x].set(y);
}
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
}
EDIT: Using a Set to store visited cells
It turns out that when n is large, creating BitSets is an expensive process. About 1.4s was taken just to create the array of BitSets. So arrays don't work, and BitSet creation is slow. After some thought, I realized that a regular HashSet<Long> should work to store visited cells, and it doesn't have the same cost to create it.
public class Robot4 {
static int nCurrRow = 1;
static int nCurrCol = 1;
static long R = 0;
static Set<Long> cell;
static long N;
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int i = 0;
int n = Reader.nextInt();
int k = Reader.nextInt();
// Add a border around the matrix with values of 1
N = n + 2L;
cell = new HashSet<Long>(1000000);
for (i = 0; i < N; i++) {
set(0, i);
set(i, 0);
set(i, n+1);
set(n+1, i);
}
set(nCurrRow, nCurrCol);
R = (long)n * n - 1; // Number of remaining unvisited cells
int sec1 = Reader.nextInt();
int sec2 = 0;
String dir1 = Reader.next();
String dir2 = "";
for (i = 0; i < k - 1; i++) {
sec2 = Reader.nextInt();
dir2 = Reader.next();
move(sec2-sec1, dir1);
dir1 = dir2;
sec1 = sec2;
}
move(n, dir1);
System.out.println(R);
}
static void move(int t, String dir1) {
boolean canMove = true;
int xDir = 0;
int yDir = 0;
if (dir1.equals("SE")) {
xDir = 1;
yDir = 1;
} else if (dir1.equals("NE")) {
xDir = 1;
yDir = -1;
} else if (dir1.equals("E")) {
xDir = 1;
} else if (dir1.equals("N")) {
yDir = -1;
} else if (dir1.equals("NW")) {
xDir = -1;
yDir = -1;
} else if (dir1.equals("W")) {
xDir = -1;
} else if (dir1.equals("SW")) {
xDir = -1;
yDir = 1;
} else if (dir1.equals("S")) {
yDir = 1;
}
for (int j = 0; j < t && canMove; j++) {
if (!isSet(nCurrRow + yDir, nCurrCol + xDir)) {
nCurrRow += yDir;
nCurrCol += xDir;
set(nCurrRow, nCurrCol);
R--;
} else
canMove = false;
}
}
static boolean isSet(int x, int y) {
return cell.contains(indexId(x,y));
}
static void set(int x, int y) {
cell.add(indexId(x,y));
}
static long indexId(int x, int y) {
return x*N+y;
}
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
}
I'm new to java and I'm trying to see if the method public String toString() is representing correctly the polynomial function. I don't know how to give the coefficients from main so that the class Func receives them.
package ro.utcluj.poo.lab04;
import java.util.Scanner;
class Func {
public double[] coef; //the coefficients
public int nrCoef; //coefficients number
public Func(double[] input)
{
nrCoef = input.length;
this.coef = new double[nrCoef];
for (int counter = 0; counter < input.length; counter++)
coef[counter] = input[counter];
}
public double getFuncValue(double x)
{
double exponent = nrCoef;
double y = 0;
double sum = 0;
for(int i = nrCoef; i >= 0; i--)
{
y = coef[i]*Math.pow(x, exponent-1); //n grade polynomial function
exponent--;
sum += y; //the sume for each member
}
return sum;
}
public double getDerivValue(double x)
{
double deriv = 0;
double rezDeriv = 0;
for(int i = 0; i < nrCoef - 1; i++)
{
deriv = coef[i]*(nrCoef - i)*Math.pow(x, nrCoef - i -1);
rezDeriv += deriv;
}
return rezDeriv;
}
public String toString()
{
String s = new String(" ");
int exp = nrCoef-1;
for(int i = 0; i < nrCoef; i++)
{
if(exp == 0 && coef[i] > 0)
s +="+" + coef[i];
else if(exp == 0 && coef[i] < 0)
s +=coef[i];
else if(exp == 1 && coef[i] > 0 && i == 0)
s +="+" + coef[i] + "x";
else if(exp == 1 && coef[i] >0)
s +="+" + coef[i];
else if(exp == 1 && coef[i] < 0)
s+=coef[i];
else if(coef[i] == 0)
s += "";
else if(coef[i] > 0 && i!=0)
s +="+" + coef[i]+"x^" + exp;
else
s +=coef[i] + "x^" + exp;
exp--;
System.out.println(s);
}
return s;
}
}
.
public class Main04 {
public static void main(String[] args) {
double[] v = new double[]{3,5,4};
Func f = new Func(v);
}
}
If you want to see what toString() does on your object f in main, all you need to do is
System.out.println(f);
f already has the coefficients that you passed into its constructor. println will call the object's toString() method and output the resulting string for you to see.
Also, as Steven pointed out in the comments, you don't need to put:
System.out.println(s);
in your toString() method itself. toString is supposed to produce and return the string. Your main method can deal with printing it out.
It's pretty simple to see what toString() does on object f in main...
You only have to yo use :
System.out.println(f);
This method will print the result of toString() to the command line.
That's all ;)
That worked but if I give the values {-3, -5, -4} I receive this:
-3.0x^2-5.0-4.0
It's missing the x from the second term(-5.0x). That is happining only if the second value is a negative one. For positive values it's working fine.
Try this way.
class Func {
public double[] coef; // the coefficients
public int nrCoef; // coefficients number
private StringBuilder sbl = new StringBuilder();
private StringBuilder tsbl = new StringBuilder();
public Func(double[] input) {
nrCoef = input.length;
this.coef = new double[nrCoef];
sbl.append("\nF(x) = ");
int exp = 0;
for (int counter = 0; counter < nrCoef; counter++) {
coef[counter] = input[counter];
if (coef[counter] != 0) {
if (counter != 0) {
sbl.append(coef[counter] < 0 ? " - " : " + ");
} else if (coef[counter] < 0) {
sbl.append(" - ");
}
exp = nrCoef - counter - 1;
sbl.append(Math.abs(coef[counter])+(exp == 0 ? "" : exp == 1 ? "*x" : "*x^"+exp));
}
}
}
public String toString() {
return tsbl.toString().isEmpty() ? sbl.toString() : tsbl.toString();
}
public double getFuncValue(double x) {
double sum = 0;
for (int index = 0; index < nrCoef; index++) {
sum += coef[index] * Math.pow(x, nrCoef - index - 1); // n grade polynomial
}
tsbl = new StringBuilder();
tsbl.append(sbl.toString());
tsbl.append("\nF(");
tsbl.append(x);
tsbl.append(") = "+sum);
return sum;
}
...
I appreciate the help. I was able to finish modifying everything in this class into BigInteger format except for the compose method. Can anyone help me with this last part as to why it is not working correctly? I really appreciate it, thanks.
import java.math.BigInteger;
public class Polynomial {
private BigInteger[] coef; // coefficients
private int deg; // degree of polynomial (0 for the zero polynomial)
/** Creates the constant polynomial P(x) = 1.
*/
public Polynomial(){
coef = new BigInteger[1];
coef[0] = new BigInteger("1");
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(int a){
coef = new BigInteger[2];
coef[1] = new BigInteger("1");
coef[0] = new BigInteger(Integer.toString(a));
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
for(int i = 0; i < b; i++){
if(coef[i] == null)
coef[i] = new BigInteger("0");
}
coef[b] = new BigInteger(Integer.toString(a));
deg = degree();
}
/** Return the degree of this polynomial (0 for the constant polynomial).
*/
public int degree() {
int d = 0;
for (int i = 0; i < coef.length; i++)
if (coef[i] != null) d = i; // check to make sure this works
return d;
}
/** Return the composite of this polynomial and b, i.e., return this(b(x)) - compute using Horner's method.
*/
public Polynomial compose(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, 0);
for (int i = a.deg; i >= 0; i--) {
Polynomial term = new Polynomial(a.coef[i].intValue(), 0);
c = term.plus(b.times(c));
}
return c;
}
public Polynomial times(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, a.deg + b.deg);
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] = c.coef[i+j].add((a.coef[i].multiply(b.coef[j])));
c.deg = c.degree();
return c;
}
/** Return a textual representation of this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return coef[1] + "x + " + coef[0];
String s = coef[deg] + "x^" + deg;
for (int i = deg-1; i >= 0; i--) {
if (coef[i] == null) continue;
else if (coef[i].intValue() > 0) s = s + " + " + ( coef[i]);
else if (coef[i].intValue() < 0) s = s + " - " + (coef[i].negate());
if(coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial p = new Polynomial(1,2);
Polynomial q = new Polynomial(2,3);
Polynomial t = p.compose(q); // incorrect
System.out.println("p(q(x)) = " + t); // incorrect
}
}
What I think is the problem is with your toString() itself as it does not align to your defaulting mechanism. Meaning, you assign default value of '0's but do not check for 0 values in the following lines:
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
It gets piled up even for 0 coefficient values. Add a condition of checking non-zero coefficient only:
if (coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
This should work, I haven't tested it but you can try testing and post the results.
EDIT:
Well, i just tried your code and seems to give the correct information with the above condition in place:
6x^7 + 2x^3
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I already have this whole entire class done in Int and now I had to convert it to BigInteger. Main objective is so I can store the coefficients as the BigIntegers for large coefficients. I am getting a null pointer error with the code but I knew that BigInteger was immutable and needed that format. Just maybe another eye or maybe I'm just not doing this correctly.
public class Polynomial {
private BigInteger[] coef; // coefficients
private int deg; // degree of polynomial (0 for the zero polynomial)
/** Creates the constant polynomial P(x) = 1.
*/
public Polynomial(){
coef = new BigInteger[1];
coef[0] = BigInteger.valueOf(1);
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(int a){
coef = new BigInteger[2];
coef[1] = BigInteger.valueOf(1);
coef[0] = BigInteger.valueOf(a);
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
coef[b] = BigInteger.valueOf(a);
deg = degree();
}
public Polynomial(BigInteger a, int b) {
coef = new BigInteger[b+1];
coef[b] = a;
deg = degree();
}
/** Return the degree of this polynomial (0 for the constant polynomial).
*/
public int degree() {
int d = 0;
for (int i = 0; i < coef.length; i++)
if (coef[i] != BigInteger.valueOf(0)) d = i;
return d;
}
/** Return the sum of this polynomial and b, i.e., return c = this + b.
*/
public Polynomial plus(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].add(b.coef[i]);
c.deg = c.degree();
return c;
}
/** Return the difference of this polynomial and b, i.e., return (this - b).
*/
public Polynomial minus(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].subtract(b.coef[i]);
c.deg = c.degree();
return c;
}
/** Return the product of this polynomial and b, i.e., return (this * b).
*/
public Polynomial times(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, a.deg + b.deg);
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] = c.coef[i+j].add(a.coef[i].multiply(b.coef[j]));
c.deg = c.degree();
return c;
}
/** Return the composite of this polynomial and b, i.e., return this(b(x)) - compute using Horner's method.
*/
public Polynomial compose(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, 0);
for (int i = a.deg; i >= 0; i--) {
Polynomial term = new Polynomial(a.coef[i], 0);
c = term.plus(b.times(c));
}
return c;
}
/** Return true whenever this polynomial and b are identical to one another.
*/
public boolean equals(Polynomial b) {
Polynomial a = this;
if (a.deg != b.deg) return false;
for (int i = a.deg; i >= 0; i--)
if (a.coef[i] != b.coef[i]) return false;
return true;
}
/** Evaluate this polynomial at x, i.e., return this(x).
*/
public int evaluate(int x) {
int p = 0;
for (int i = deg; i >= 0; i--){
coef[i] = coef[i].add(BigInteger.valueOf(x * p));
p = coef[i].intValue();
}
return p;
}
/** Return the derivative of this polynomial.
*/
public Polynomial differentiate() {
if (deg == 0) return new Polynomial(0, 0);
Polynomial deriv = new Polynomial(0, deg - 1);
deriv.deg = deg - 1;
for (int i = 0; i < deg; i++)
deriv.coef[i] = coef[i + 1].multiply(BigInteger.valueOf(i+1));
return deriv;
}
/** Return a textual representationof this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return String.valueOf(coef[1]) + "x + " + String.valueOf(coef[0]);
String s = String.valueOf(coef[deg]) + "x^" + deg;
for (int i = deg-1; i > 0; i--) {
if (coef[i].intValue() == 0) continue;
else if (coef[i].intValue() > 0) s = s + " + " + ( coef[i].intValue());
else if (coef[i].intValue() < 0) s = s + " - " + (-coef[i].intValue());
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial zero = new Polynomial(1, 0);
Polynomial p1 = new Polynomial(4, 3);
Polynomial p2 = new Polynomial(3, 2);
Polynomial p3 = new Polynomial(-1, 0);
Polynomial p4 = new Polynomial(-2, 1);
Polynomial p = p1.plus(p2).plus(p3).plus(p4); // 4x^3 + 3x^2 - 2x - 1
Polynomial q1 = new Polynomial(3, 2);
Polynomial q2 = new Polynomial(5, 0);
Polynomial q = q1.minus(q2); // 3x^2 - 5
Polynomial r = p.plus(q);
Polynomial s = p.times(q);
Polynomial t = p.compose(q);
System.out.println("zero(x) = " + zero);
System.out.println("p(x) = " + p);
System.out.println("q(x) = " + q);
System.out.println("p(x) + q(x) = " + r);
System.out.println("p(x) * q(x) = " + s);
System.out.println("p(q(x)) = " + t);
System.out.println("0 - p(x) = " + zero.minus(p));
System.out.println("p(3) = " + p.evaluate(3));
System.out.println("p'(x) = " + p.differentiate());
System.out.println("p''(x) = " + p.differentiate().differentiate());
Polynomial poly = new Polynomial();
for(int k=0; k<=4; k++){
poly = poly.times(new Polynomial(-k));
}
System.out.println(poly);
}
}
So when you initialize your array of BigInteger, the values are null because you have specified an array of objects (if it was int[] then initial values are 0).
As you can see from your constructor:
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
coef[b] = BigInteger.valueOf(a);
deg = degree();
}
You have only assigned coef[b], the other values remain null.
Hence in first iteration of loop in method plus(Polynomial b), c.coef[0] is null hence NullPointerException when your loop tries to call c.coef[0].add(a.coef[0]).
Suggestion: define a method to initialize all the BigInteger values in an array to 0 to be consistent with declaration of int[] and call in your constructors. Example:
private static void initializeBigIntegerArray(BigInteger[] bigIntegers) {
for (int i=0; i<bigIntegers.length; i++) {
// So you don't overwrite anything you assign explicitly
if (bigInteger[i] == null) {
bigIntegers[i] = BigInteger.ZERO;
}
}
}
Recall that in Java an array of objects is actually an array of references to objects. So you need to create a BigInteger object for every array element. The entries you don't assign are not 0, they are null.
So in the plus method, you create this polynomial c whose backing array contains one zero, and several nulls. Then you go ahead and try to operate on all the coefficients in that polynomial, including all those nulls. So you're calling methods on variables for which an object hasn't been created yet, and that's what makes your null pointer problem.
When you create each polynomial, make sure you have a BigInteger created for every entry in the backing array.
I designing a polynomial class for one of my com sci courses , I have a problem of getting the integration method right
can some one help me with that
/** The polynomial class includes the methods: evaluate , add, multiply,
* Differentiate , integrate and square root.
*/
public class polynomial {
private int degree;
private double[] coefficients;
// a constructor that creates a polynomial of degree degMax with all the coefficients are zeroes
public polynomial(int degMax) {
degree= degMax;
coefficients = new double[degree + 1];
}
// a setter method that let the users set the coefficients for the polynomial they constructed
public void setCoefficient(int d , double v ){
if (d > degree)
{
System.out.println("Erorr Message: the degree you specified is larger than the polynomial's degree that you have created ");
}
else {
coefficients[d]=v;
}
}
// a getter method to return the coefficient for the specified degree
public double getCoefficient(int i){
return coefficients[i];
}
// private method that counts the degree of the polynomial by searching for the last element in the coefficient array that
// does not contain zero
private int getDegree() {
int deg = 0;
for (int i = 0; i < coefficients.length; i++)
if (coefficients[i] != 0) deg = i;
return deg;
}
// a method that print out the polynomial as a string
public String print(){
if (degree == 0) return "" + coefficients[0];
if (degree == 1) return coefficients[1] + "x + " + coefficients[0];
String s = coefficients[degree] + "x^" + degree;
for (int i = degree-1; i >= 0; i--) {
if (coefficients[i] == 0) continue;
else if (coefficients[i] > 0) s = s + " + " + ( coefficients[i]);
else if (coefficients[i] < 0) s = s + " - " + (-coefficients[i]);
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
// a method that evaluate the polynomial at specified value x
public double evaluate(double x) {
double result = 0;
for (int i = degree; i >= 0; i--)
result = coefficients[i] + (x * result);
return result;
}
// a method that perform symbolic addition of two polynomial
public polynomial addition(polynomial p2) {
polynomial p1 = this;
polynomial p3 = new polynomial(Math.max(p1.degree, p2.degree));
for (int i = 0; i <= p1.degree; i++) p3.coefficients[i] += p1.coefficients[i];
for (int i = 0; i <= p2.degree; i++) p3.coefficients[i] += p2.coefficients[i];
p3.degree = p3.getDegree();
return p3;
}
// a method that performs a symbolic multiplication
public polynomial multiply(polynomial p2) {
polynomial p1 = this;
polynomial p3 = new polynomial(p1.degree + p2.degree);
for (int i = 0; i <= p1.degree; i++)
for (int j = 0; j <= p2.degree; j++)
p3.coefficients[i+j] += (p1.coefficients[i] * p2.coefficients[j]);
p3.degree = p3.getDegree();
return p3;
}
// a method that apply differentiation to polynomial
public polynomial differentiate() {
if (degree == 0) return new polynomial(0);
polynomial derivative = new polynomial(degree - 1);
derivative.degree = degree - 1;
for (int i = 0; i < degree; i++){
derivative.coefficients[i] = (i + 1) * coefficients[i + 1];
}
return derivative;
}
// a method that find a polynomial integral over the interval a to b
public double integration(double a , double b) {
polynomial integral= new polynomial (degree+1);
integral.degree= degree+1;
for (int i=0 ; i<= degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (coefficients[i-1]/i);
}
}
return (evaluate(b)- evaluate(a));
}
public static void main(String[] args) {
polynomial p1 = new polynomial(3);
p1.setCoefficient(0, 3.0);
p1.setCoefficient(3, 5.0);
String r = p1.print(); //3.0 + 5.0 x^3
polynomial p2 = new polynomial(2);
p2.setCoefficient(1, 4.0);
p2.setCoefficient(2, 2.0);
polynomial n = p1.addition(p2);
String po = n.print();
polynomial t = p1.multiply(p2);
String tr = t.print();
polynomial di = p2.differentiate();
String dir = di.print();
double ev = p2.evaluate(5.0);
double inte = p1.integration(3.0, 7.0);
System.out.println("p1(x) = " + r );
System.out.println("p1(x) + p2(x) = " + po);
System.out.println("p1(x) * p2(x) = " + tr);
System.out.println("p2'(x) = " + dir);
System.out.println("p1(x) integration over [3.0, 7.0] = " + inte);
System.out.println("p2(5.0) = " + ev);
}
}
If I were you, I would split the methods :
public Polynomial integrate()
{
Polynomial integral = new Polynomial(this.degree + 1);
for (int i = 1; i <= this.degree+1; i++)
{
integral.coefficients[i] = (this.coefficients[i - 1] / i);
}
return integral;
}
// a method that find a Polynomial integral over the interval a to b
public double integration(double a, double b)
{
Polynomial integral = integrate();
return (integral.evaluate(b) - integral.evaluate(a));
}
Ok now why it didn't work as you expected :
public double integration(double a , double b) {
polynomial integral= new polynomial (degree+1);
integral.degree= degree+1;
for (int i=0 ; i<= degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (coefficients[i-1]/i);
}
}
return (evaluate(b)- evaluate(a));
}
you messed up your "integral" object with the current instance "this", clean your code first :
public double integration(double a , double b) {
polynomial integral= new polynomial (this.degree+1);
integral.degree= this.degree+1;
for (int i=0 ; i<= this.degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (this.coefficients[i-1]/i);
}
}
return (this.evaluate(b)- this.evaluate(a));
}
Here you can see that you evaluate on your instance object instead of "integral" object. That's why it messed up the result.
You almost got it correct. The only problem is that you should call:
return (integral.evaluate(b) - integral.evaluate(a));
instead of:
return (evaluate(b)- evaluate(a));
Otherwise the code seems ok.
Adding to Boris' answer, you could simplify the integrate method like this:
public double integration(double a, double b) {
polynomial integral = new polynomial(degree + 1);
for (int i = 1; i <= degree + 1; i++) {
integral.coefficients[i] = coefficients[i - 1] / i;
}
return integral.evaluate(b) - integral.evaluate(a);
}