I am using binary search to find a balance point between the planets. The method binaryBalance takes in Arraylist of planets which is an object with displacement and mass property. It also takes in the displacement of two planets between which I am trying to find a balance point of. Double x is the inital starting point of the search and I am setting the average displacement of p1 and p2 here. The code runs smoothly but it is off the answer for a minute amount. I try to increase the precision by setting the error interval to more than 1e-10, but I keep getting Stack Overflow error. How do I solve this problem with higher precision?
import java.util.*;
import java.lang.*;
public class Solution {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
int numCase = sc.nextInt();
for (int k = 1; k <= numCase; k++) {
//Initializing Space...
int numPlanets = sc.nextInt();
ArrayList<Planet> space = new ArrayList<>();
int[] weights = new int[numPlanets];
int[] displacements = new int[numPlanets];
for (int i = 0; i < numPlanets; i++) {
displacements[i] = sc.nextInt();
}
for (int i = 0; i < numPlanets;i++) {
weights[i] = sc.nextInt();
}
for (int i = 0; i < numPlanets;i++) {
Planet p = new Planet(displacements[i],weights[i]);
space.add(p);
}
System.out.print("#" + k + " ");
for (int i = 0; i < numPlanets-1; i++) {
double init = (double) (space.get(i).getDisplacement() + space.get(i+1).getDisplacement()) /2;
binaryBalance(space,space.get(i).getDisplacement(),space.get(i+1).getDisplacement(),init);
}
System.out.println();
}
}
public static class Planet {
private int d;
private int m;
public Planet(int d,int m) {
this.d = d;
this.m = m;
}
public void setDisplacement(int d) {
this.d = d;
}
public void setMass(int m) {
this.m = m;
}
public double getG(double dPlanet) {
double betweenDistance = this.d - dPlanet;
return this.m/(betweenDistance*betweenDistance);
}
public int getDisplacement() {
return d;
}
public int getMass() {
return m;
}
}
public static void binaryBalance(ArrayList<Planet> space, double p1, double p2, double x) {
double leftg = 0;
double rightg = 0;
for (int i = 0; i < space.size(); i++) {
if (space.get(i).getDisplacement() < x) {
leftg = leftg + space.get(i).getG(x);
} else {
rightg = rightg + space.get(i).getG(x);
}
}
if (Math.abs(leftg - rightg) < 1e-10) {
System.out.print(String.format("%.10f",x) + " ");
return;
}
if (leftg < rightg) {
binaryBalance(space, p1, x, (p1 + x) / 2);
} else {
binaryBalance(space, x, p2, (p2 + x) / 2);
}
}
Test Cases are:
10
2
1 2 1 1
2
1 2 1 1000
2
457 468 333 321
3
1 2 3 1 2 1
4
2 3 5 7 3 2 7 5
5
3 11 12 19 29 542 661 450 521 366
6
42 75 88 94 113 144 669 551 355 344 294 155
7
62 86 279 323 363 516 579 810 749 736 297 136 107 52
8
10 34 64 73 93 97 101 122 466 463 441 373 315 292 225 83
10
9 14 38 39 48 73 179 190 207 302 560 497 640 722 437 259 449 470 709 520
And the expected answer is:
#1 1.5000000000
#2 1.0306534300
#3 462.5504629633
#4 1.4060952085 2.5939047915
#5 2.5328594461 3.7271944335 6.0999536409
#6 6.3428568767 11.5477377494 15.9641592998 24.9267991615
#7 57.8805685415 81.8651598883 91.0573691382 105.0835650491 133.2934094881
#8 74.2211477711 190.6837563313 305.8269181686 348.3304429927 470.2694219293 555.4943093854
#9 21.5171374463 47.9890597763 68.6536668433 82.9131954023 95.0052272762 99.1999097770 116.4978330953
#10 11.5573600056 24.0238341337 38.4847676134 44.6137453708 64.7500445424 126.9908128982 184.3221650927 197.9760596291 266.0574653677
With the leftg-rightg tolerance of 1e-10, the greatest number of iterations is 47, on the second case where the masses are so different. That won't overflow any stacks, but of course you asked about increasing the accuracy. Unfortunately, it's impossible to even reach 1e-11 on case 6, because of the scale of the numbers involved (as I mentioned in a comment). So you get infinite recursion if you change the tolerance exponent at all.
But maybe a fixed balance tolerance isn't what you're expected to do for this exercise! I get exactly the expected answers (to their given precision) if I instead refine until the interval has "zero" width. (p1 and p2 need not be equal, but there are no floating-point numbers between them. You detect this by noticing that x==p1 || x==p2; x will be whichever ends in a 0 in binary.) This takes at most 53 bisections for these cases: a number which should be familiar to any numerical analyst since it is the effective number of bits in the significand of a double. I didn't check whether a larger p2-p1 tolerance might give the correct answers.
Since it's useless to get (much) above 53 levels deep, the choice of recursion here is harmless (although tail recursion with a void function looks very odd), and changing to iteration won't help at all. Either way, you do have to make sure that it terminates!
Try to use iteration instead of recursion. I also added line with logging of data on each iteration.
public static void binaryBalance(ArrayList<Planet> space, double p1, double p2, double x) {
while(true) {
//You can use this line to log evolution of your data
System.out.println(String.format("p1=%s p2=%s x=%s", p1, p2, x));
double leftg = 0;
double rightg = 0;
for (int i = 0; i < space.size(); i++) {
if (space.get(i).getDisplacement() < x) {
leftg = leftg + space.get(i).getG(x);
} else {
rightg = rightg + space.get(i).getG(x);
}
}
if (Math.abs(leftg - rightg) < 1e-10) {
System.out.print(String.format("%.10f",x) + " ");
return;
}
double p1Tmp = p1;
double p2Tmp = p2;
double xTmp = x;
if (leftg < rightg) {
p1 = p1Tmp;
p2 = xTmp;
x = (p1Tmp + xTmp) / 2;
} else {
p1 = xTmp;
p2 = p2Tmp;
x = (p2Tmp + xTmp) / 2;
}
}
}
Related
public class Program {
public static void main(String[] args) {
int x = 1;
for (int i = 1; i < 31; i++) {
x = x + 2 * x;
}
System.out.println(x);
}
}
It prints -1010140999 and I don't know why it is negative number.
Final output is a very long number which will exceed the max integer capaxity. Hence we need to use long data type. Please check the correct code below with x value at each iteration
public class Program {
public static void main(String[] args) {
long x = 1;
for (int i = 1; i < 31; i++) {
x = x + 2l * x;
System.out.println(i+ " " +x);
}
}
}
Output
1 3
2 9
3 27
4 81
5 243
6 729
7 2187
8 6561
9 19683
10 59049
11 177147
12 531441
13 1594323
14 4782969
15 14348907
16 43046721
17 129140163
18 387420489
19 1162261467
20 3486784401
21 10460353203
22 31381059609
23 94143178827
24 282429536481
25 847288609443
26 2541865828329
27 7625597484987
28 22876792454961
29 68630377364883
30 205891132094649
An integer in Java is stored with 32 bits, of which one is used to indicate whether the value is positive or negative. This means an int's value is between -2^31 and 2ˆ31 - 1.
Once you add or subtract past those limits, you wrap around in the corresponding direction since an overflow/underflow occurs.
public class OverflowExample {
public static void main(String args[]) {
int largest_int = Integer.MAX_VALUE;
int smallest_int = Integer.MIN_VALUE;
System.out.println(largest_int); // 2ˆ31 - 1 = 2147483647
System.out.println(largest_int + 1); // -2147483648
System.out.println(smallest_int); // -2^31, same as above
}
}
So I need to get rid of this final multiplication sign in each line. I've tried a few different ways but they just messed up my code or didn't work, and I can't seem to wrap my head around how to go about this.
Here's an example of the output:
Starting value (at least 2):
59
Ending value (at least 2):
64
59 = 59 x
60 = 2 x 2 x 3 x 5 x
61 = 61 x
62 = 2 x 31 x
63 = 3 x 3 x 7 x
64 = 2 x 2 x 2 x 2 x 2 x 2 x
Here's how I want it to look:
Starting value (at least 2):
59
Ending value (at least 2):
64
59 = 59
60 = 2 x 2 x 3 x 5
61 = 61
62 = 2 x 31
63 = 3 x 3 x 7
64 = 2 x 2 x 2 x 2 x 2 x 2
And here's the code:
import java.util.Scanner;
public class PrimeFact {
public static void main(String[] args) {
int start, stop;
int number = 0;
Scanner input = new Scanner(System.in);
System.out.println("Starting value (at least 2): ");
start = input.nextInt();
System.out.println("Ending value (at least 2): ");
stop = input.nextInt();
// stops the program if the user entered n input that cannot be factored
if (start < 2 || stop < 2) {
System.out.println("Amount must be at least 2 rather than " + start + " and " + stop + ". Quitting.");
System.exit(0);
} // end if
// loop
// calls factors
for (int i = start; i <= stop; i++) {
number = i;
printFactors(i);
System.out.println();
} // ends loop
}// ends main
// prints prime factors
public static void printFactors(int number) {
int out = number;
int count = 0;
System.out.print(out + " = ");
for (int factor = 2; factor <= number; factor++) {
int exponent = 0;
while (number % factor == 0) {
number /= factor;
exponent++;
count++;
}
if (exponent > 0) {
printExponents(exponent, factor, count);
}
}
}
//prints the factors the required number of times
public static void printExponents(int exponent, int factor, int count) {
for (int q = 1; q <= exponent; q++) {
System.out.print(factor + " x ");
// if (q /= count) {
// System.out.print(factor);
// }
}
}
}// ends class
into printFactors near the declarations of the ints add in
boolean hadFactor = false;
also amend your call there to:
if (exponent > 0) {
printExponents(exponent, factor, count, hadFactor);
hadFactor=true;
}
and in printExponents do
public static void printExponents(int exponent, int factor, int count, boolean hadFactor) {
for (int q = 1; q <= exponent; q++) {
if (hadFactor){System.out.print(" x ")}
System.out.print(factor);
hadFactor=true;
// if (q /= count) {
// System.out.print(factor);
// }
}
This program pulls two columns from the input.txt file where the first column indicates the value of the object, and the second column represents the weight. The values are imported and placed into two arrays: the value array and the weight array. The knapsack calculations are then made. There are 23 objects in total represented by the rows of the arrays. My code correctly calculates the total value that is being held in the knapsack, and will print out the correct IDs if the weight capacity entered is 5, but for any other weight the IDs being held in the id array are not correct, but the total value printed out is. Here is my code for both files, and if anyone is able to figure out how to correctly save and print the IDs being held in the knapsack please let me know . . .
input.txt file:
17 5
12 8
15 22
17 11
33 21
43 15
15 4
44 35
23 19
10 23
55 39
8 6
21 9
20 28
20 13
45 29
18 16
21 19
68 55
10 16
33 54
3 1
5 9
knapsack.java file:
//We did borrow concepts from:
//http://www.sanfoundry.com/java-program-solve-knapsack-problem-using-dp/
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.*;
public class knapsack
{
static int max(int a, int b)
{
if(a > b)
{
//System.out.println(a);
return a;
}
else
//System.out.println(b);
return b;
}
static int knapSack(int maxCapacity, int weight[], int value[], int n)
{
int track = 0;
int i, w;
int foo1 = 0;
int foo2 = 0;
K = new int[n+1][maxCapacity+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= maxCapacity; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (weight[i-1] <= w)
{
//K[i][w] = max(value[i-1] + K[i-1][w-weight[i-1]], K[i-1][w]);
if(value[i-1] + K[i-1][w-weight[i-1]] > K[i-1][w])
{
K[i][w] = value[i-1] + K[i-1][w-weight[i-1]];
//System.out.println("A: "+i);
}
else
{
K[i][w] = K[i-1][w];
id[track++] = i;
//System.out.println("B: "+i);
}
}
else
{
K[i][w] = K[i-1][w];
}
}
//System.out.println(K[foo1][foo2]);
}
return K[n][maxCapacity];
}
public static void main(String args[])throws java.io.FileNotFoundException
{
Scanner sc = new Scanner(System.in);
int n = 23;
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
id = new Integer [n];
//knapval = new int[n];
//knapweight = new int [n];
int []value = new int[n];
int []weight = new int[n];
for(int i=0; i<n; i++)
{
value[i] = scanner.nextInt();
weight[i] = scanner.nextInt();
}
System.out.println("Enter the maximum capacity: ");
int maxCapacity = sc.nextInt();
System.out.println("The maximum value that can be put in a knapsack with a weight capacity of "+maxCapacity+" is: " + knapSack(maxCapacity, weight, value, n));
System.out.println();
System.out.println("IDs Of Objects Held In Knapsack: ");
//System.out.println();
for(int z = 0; z < n && id[z] != null; z++)
{
System.out.println(id[z]);
}
if(id[0] == null)
System.out.println("All objects are too heavy, knapsack is empty.");
sc.close();
scanner.close();
}
protected static Integer [] id;
protected static int [][]K;
}
Your way of recording your solution in the id array is flawed. At the time you do id[track++] = i;, you don’t yet know whether i will be in your final solution. Because of the nested loops you may even add i more than once. This in turn may lead to overflowing the array with a java.lang.ArrayIndexOutOfBoundsException: 23 (this happens for max capacity 12 and above).
I suggest instead of using id, after your solution is complete you track your way backward through the K array (by Java naming conventions, it should be a small k). It holds all the information you need to find out which objects were included in the maximum value.
private static void printKnapsack(int maxCapacity, int weight[], int value[], int n) {
if (K[n][maxCapacity] == 0) {
System.out.println("No objects in knapsack");
} else {
int w = maxCapacity;
for (int i = n; i > 0; i--) {
if (K[i][w] > K[i - 1][w]) { // increased value from object i - 1
System.out.format("ID %2d value %2d weight %2d%n", i, value[i - 1], weight[i - 1]);
// check that value in K agrees with value[i - 1]
assert K[i - 1][w - weight[i - 1]] + value[i - 1] == K[i][w];
w -= weight[i - 1];
}
}
}
}
The above prints the objects backward. Example run:
Enter the maximum capacity:
13
The maximum value that can be put in a knapsack with a weight capacity of 13 is: 36
ID 13 value 21 weight 9
ID 7 value 15 weight 4
If you want the objects in forward order, inside the for loop put them into a list (you may for instance use id from your old attempt), and then print the items from the list in opposite order.
This code is meant to find 100 factorial and the sum the digits in the number. However, it returns 0.
Why does this happen?
public class Problem20 {
public static void main(String[] args){
int num = 100;
for(int i = 1; i< 100; i++){
num = num * i;
}
String numstring = Integer.toString(num);
int sum = 0;
for(int j = 0; j < numstring.length(); j++){
sum += numstring.charAt(j) - '0';
}
System.out.print(sum);
}
}
Every time you multiply by 2, you add a 0 to the low bits of binary representation of the number.
According to the JLS §15.17.1:
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.
Here's some code to demonstrate this point. As you can see, the number of 0 at the end of the number slowly increases; soon as we get to 32, the low order bits become all 0. See: Why does this multiplication integer overflow result in zero?
public class Problem20 {
public static void main(String[] args) {
int num = 100;
for (int i = 1; i < 33; i++) {
num = num * i;
System.out.println(i + "\t" + Integer.toBinaryString(num));
}
}
}
Output:
1 1100100
2 11001000
3 1001011000
4 100101100000
5 10111011100000
6 10001100101000000
7 1111011000011000000
8 1111011000011000000000
9 10001010011011011000000000
10 10101101000010001110000000000
11 11101101111011000011010000000000
12 100111000100100111000000000000
13 11111011111011111011000000000000
14 11000111000110111010000000000000
15 10101010100111100110000000000000
16 10101001111001100000000000000000
17 1001000010001100000000000000000
18 10100111011000000000000000000
19 10001101100001000000000000000000
20 1110010100000000000000000000
21 101100100100000000000000000000
22 11010100011000000000000000000000
23 10100101000000000000000000000
24 11101111000000000000000000000000
25 1010111000000000000000000000000
26 11010110000000000000000000000000
27 10010010000000000000000000000000
28 11111000000000000000000000000000
29 11000000000000000000000000000
30 11010000000000000000000000000000
31 110000000000000000000000000000
32 0
You can solve this problem by using BigInteger instead of int, e.g.
import java.math.BigInteger;
public class Problem20 {
public static void main(String[] args) {
BigInteger num = BigInteger.valueOf(100);
for (int i = 1; i < 100; i++) {
num = num.multiply(BigInteger.valueOf(i));
System.out.println(num);
}
}
}
Alright.
1! = 1
2! = 2
3! = 6
4! = 24
.
.
.
10! = 3628800
.
.
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Do you think this fits in any of those data-types?
What happens once a number crosses the limit? It overflows. And hence you get a wrong answer.
So what do I do?
Use BigInteger.
I tried to find all possible longest increasing subsequence using recursion. When I tried an input array {10,22,9,33,21,50,41,40,60,55}, it worked and the output was:
10 22 33 40 55 /
10 22 33 41 55 /
10 22 33 50 55 /
10 22 33 40 60 /
10 22 33 41 60 /
10 22 33 50 60 /
But when I tried an input array {2,-3,4,90,-2,-1,-10,-9,-8}, I got an output:
-3 4 90 /
-3 -2 -1 /
-10 -9 -8 /
In this case I didn't get 2 4 90. What should I change in my code to make it word for this case?
public class Main {
public static void main(String[] args) {
int arr[]={10,22,9,33,21,50,41,40,60,55};
int lis[]=new int[arr.length];
for(int i=0;i<arr.length;i++){
lis[i]=1;
}
for(int i=1;i<arr.length;i++){
for(int j=0;j<i;j++){
if(arr[i]>arr[j]&&lis[i]<lis[j]+1){
lis[i]=lis[j]+1;
}
}
}
int max=0;
for(int i=0;i<arr.length;i++){
if(max<lis[i])
max=lis[i];
}
//**************Recursive Print LIS****************
int rIndex=-1;
for(int i=arr.length-1;i>=0;i--){
if(lis[i]==max){
rIndex=i;
break;
}
}
int res[]=new int[max];
printLISRecursive(arr,rIndex,lis,res,max,max);
}
private static void printLISRecursive(int[] arr, int maxIndex, int[] lis, int[] res, int i, int max) {
if(maxIndex<0)return;
if(max==1&&lis[maxIndex]==1&&i==1){
res[i-1]=arr[maxIndex];
// System.out.println("Using Print Recursion:");
for(int j=0;j<res.length;j++){
System.out.print(res[j]+" ");
}
System.out.println();
return;
}
if(lis[maxIndex]==max){
res[i-1]=arr[maxIndex];
printLISRecursive(arr, maxIndex-1, lis, res, i-1, max-1);
}
printLISRecursive(arr, maxIndex-1, lis, res, i, max);
}
}
public static String lcs(String a, String b){
int aLen = a.length();
int bLen = b.length();
if(aLen == 0 || bLen == 0){
return "";
}else if(a.charAt(aLen-1) == b.charAt(bLen-1)){
return lcs(a.substring(0,aLen-1),b.substring(0,bLen-1))
+ a.charAt(aLen-1);
}else{
String x = lcs(a, b.substring(0,bLen-1));
String y = lcs(a.substring(0,aLen-1), b);
return (x.length() > y.length()) ? x : y;
}
}
public static int lcsrec(String x, String y) {
// If one of the strings has one character, search for that character
// in the other string and return the appropriate answer.
if (x.length() == 1)
return find(x.charAt(0), y);
if (y.length() == 1)
return find(y.charAt(0), x);
// Solve the problem recursively.
// Corresponding beginning characters match.
if (x.charAt(0) == y.charAt(0))
return 1+lcsrec(x.substring(1), y.substring(1));
// Corresponding characters do not match.
else
return max(lcsrec(x,y.substring(1)), lcsrec(x.substring(1),y));
}