Untitled

unknown
plain_text
a month ago
2.8 kB
1
Indexable
Never
```package divideAndConquer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Test {

public static double calculateGravitationalForce(double x, double m1, double m2, double d) {
double G = 6.67e-11;
return G * m1 * m2 / Math.pow((d - x), 2);
}

public static double sumForcesFromLeft(double x, double[] xArray, double[] mArray) {
int n = xArray.length;
double fSum = 0;
for (int i = 0; i < n; i++) {
if (xArray[i] < x) {
fSum += calculateGravitationalForce(x, mArray[i], 1, xArray[i]);
}
}
return fSum;
}

public static double sumForcesFromRight(double x, double[] xArray, double[] mArray) {
int n = xArray.length;
double fSum = 0;
for (int i = 0; i < n; i++) {
if (xArray[i] > x) {
fSum += calculateGravitationalForce(x, mArray[i], 1, xArray[i]);
}
}
return fSum;
}

public static double[] findBalance(double[] xArray, double[] mArray) {
int n = xArray.length;
double[] balancePoints = new double[n - 1];
for (int i = 0; i < n - 1; i++) {
double a = xArray[i];
double b = xArray[i + 1];
double tol = 1e-9;
int maxIter = 100;
int iter = 0;
while (Math.abs(a - b) > tol && iter < maxIter) {
double c = (a + b) / 2;
if (sumForcesFromLeft(c, xArray, mArray) == sumForcesFromRight(c, xArray, mArray)) {
break;
} else if (sumForcesFromLeft(c, xArray, mArray) > sumForcesFromRight(c, xArray, mArray)) {
a = c;
} else {
b = c;
}
iter++;
}
balancePoints[i] = (a + b) / 2;
}
return balancePoints;
}

public static void main(String[] args) throws FileNotFoundException {
System.setIn(new FileInputStream("Text"));
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
// Read the number of magnetic materials
int n = sc.nextInt();
double[] x = new double[n];
double[] m = new double[n];

for (int j = 0; j < n; j++) {
x[j] = sc.nextDouble();
}
for (int j = 0; j < n; j++) {
m[j] = sc.nextDouble();
}
double[] balancePoints = findBalance(x, m);

System.out.print("#1 ");

for (double point : balancePoints) {
System.out.printf("%.10f ", point);
}

System.out.println();
}
sc.close();
}
}
```