In: Computer Science
Java - In this lab, you will be writing your own method using
the brute force algorithm, to solve a second degree
polynomial.
This method will take in four parameters, three coefficients, and
one constant, and it will have the following signature:
public static String bruteForceEquationSolver(int one, int two, int three, int constant){}
The equation you are trying to solve is of the following format, given the parameters stated above:
(constant) = (one) * x + (two) * y + (three) * z
X, Y, and Z are variables that you are finding solutions for.
For example, if you were to call the method with parameters (2, 3, 4, 42), you would be finding the solution for the equation 2x + 3y + 4z = 42.
Some specifications for the method:
Your method should return if a solution is found, and return a string with the solutions in the following format:
x: xSolution y: ySolution z: zSolution
There should be a space between the solution and the next variable, and each variable letter should be followed by a colon and a space.
Call the testBFES() method from main after completing this method to ensure it is working as expected.
Here's what I have so far:
public static String bruteForceEquationSolver(int one, int two, int three, int constant) { // student code here for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { for (int k = 1; k <= 10; k++) { } } } return String.format("x:%d y:%d z:%d", one, two, three); }
public static void testBFES() { System.out.println("Testing Brute Force Equation Solver"); String expected = "x: 2 y: 3 z: 4"; System.out.println("Expecting: " + expected); String actual = bruteForceEquationSolver(3, 4, 6, 42); System.out.println("Actual: " + actual); boolean correct = expected.equals(actual); System.out.println("Outputs equal? " + correct); } public static void testMT() { System.out.println("Testing Multiplication Table"); String expected = "1\t2\t3\t4\t\n2\t4\t6\t8\t\n3\t6\t9\t12\t\n"; System.out.print("Expecting:\n" + expected); String actual = multiplicationTable(3, 4); System.out.print("Actual:\n" + actual); boolean correct = expected.equals(actual); System.out.println("Outputs equal? " + correct); }
CODE/OUTPUT image
CODE:
Kindly upvote if
this helped you. Comment for more help.
public class EquationSolver {
public static void main(String[] args) {
String answer = bruteForceEquationSolver(2,3,4,42);
System.out.println(answer);
}
public static String bruteForceEquationSolver(int one, int two, int three, int constant) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
for (int k = 1; k <= 10; k++) {
if( ((i*one) + (j*two) + (k*three)) == constant) {
return String.format("x:%d y:%d z:%d", i, j, k);
}
}
}
}
return "Solution not found";
}
}