Related
I was looking into the Knight's Tour Problem, where the solution is obtained when a chess knight piece moves to every square on a grid exactly once. However, upon looking at different solutions for the problem, I keep seeing a specific array of numbers:
int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
Where exactly these integers are coming from? Is there a way that you can solve the problem without these specific integers, or are they essential to the problem? For reference, here is the full code I was looking at. (credit GeeksforGeeks)
// Java program for Knight Tour problem
class KnightTour {
static int N = 8;
/* A utility function to check if i,j are
valid indexes for N*N chessboard */
static boolean isSafe(int x, int y, int sol[][])
{
return (x >= 0 && x < N && y >= 0 && y < N
&& sol[x][y] == -1);
}
/* A utility function to print solution
matrix sol[N][N] */
static void printSolution(int sol[][])
{
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++)
System.out.print(sol[x][y] + " ");
System.out.println();
}
}
/* This function solves the Knight Tour problem
using Backtracking. This function mainly
uses solveKTUtil() to solve the problem. It
returns false if no complete tour is possible,
otherwise return true and prints the tour.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions. */
static boolean solveKT()
{
int sol[][] = new int[8][8];
/* Initialization of solution matrix */
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;
/* xMove[] and yMove[] define next move of Knight.
xMove[] is for next value of x coordinate
yMove[] is for next value of y coordinate */
int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Since the Knight is initially at the first block
sol[0][0] = 0;
/* Start from 0,0 and explore all tours using
solveKTUtil() */
if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) {
System.out.println("Solution does not exist");
return false;
}
else
printSolution(sol);
return true;
}
/* A recursive utility function to solve Knight
Tour problem */
static boolean solveKTUtil(int x, int y, int movei,
int sol[][], int xMove[],
int yMove[])
{
int k, next_x, next_y;
if (movei == N * N)
return true;
/* Try all next moves from the current coordinate
x, y */
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x][next_y]
= -1; // backtracking
}
}
return false;
}
/* Driver Code */
public static void main(String args[])
{
// Function Call
solveKT();
}
}
// This code is contributed by Abhishek Shankhadhar
It's simply an exhaustive list of all the moves a knight can make, relative to its current position. That list is determined by the rules of chess (and the rectangular grid of a chessboard).
For example, the 0'th entries in both arrays mean "2 squares right and 1 square forward" - assuming x-coordinates increase left-to-right and y coordinates increase front-to-back.
You can determine the list for yourself by enumerating every possible combination of "two squares in one direction, and then one square at right-angles to it".
I am trying to find the k nearest neighbors with the Knn classifier in OpenCV.
I found this C++ Code:
class atsKNN{
public :
void knn(cv::Mat& trainingData, cv::Mat& trainingClasses, cv::Mat& testData, cv::Mat& testClasses, int K)
{
cv::KNearest knn(trainingData, trainingClasses, cv::Mat(), false, K);
cv::Mat predicted(testClasses.rows, 1, CV_32F);
for(int i = 0; i < testData.rows; i++) {
const cv::Mat sample = testData.row(i);
predicted.at<float>(i,0) = knn.find_nearest(sample, K);
}
float percentage = evaluate(predicted, testClasses) * 100;
cout << "K Nearest Neighbor Evaluated Accuracy = " << percentage << "%" << endl;
prediction = predicted;
}
void showplot(cv::Mat testData)
{
plot_binary(testData, prediction, "Predictions Backpropagation");
}
private:
cv::Mat prediction;
};
The comments mention it works really good but i am having problems Converting it to Java. There is no Documentation for Java. I tried using a C++ to Java Converter but the resulting Code does not work.
here is the code it produced:
public class atsKNN
{
public final void knn(cv.Mat trainingData, cv.Mat trainingClasses, cv.Mat testData, cv.Mat testClasses, int K)
{
cv.KNearest knn = new cv.KNearest(trainingData, trainingClasses, cv.Mat(), false, K);
cv.Mat predicted = new cv.Mat(testClasses.rows, 1, CV_32F);
for (int i = 0; i < testData.rows; i++)
{
final cv.Mat sample = testData.row(i);
predicted.<Float>at(i,0) = knn.find_nearest(sample, K);
}
float percentage = evaluate(predicted, testClasses) * 100;
System.out.print("K Nearest Neighbor Evaluated Accuracy = ");
System.out.print(percentage);
System.out.print("%");
System.out.print("\n");
prediction = predicted;
}
public final void showplot(cv.Mat testData)
{
plot_binary(testData, prediction, "Predictions Backpropagation");
}
private cv.Mat prediction = new cv.Mat();
}
edit:
The line predicted.at(i,0) = knn.find_nearest(sample, K); has most definitely to be wrong.
There is now function at in object Mat.
Also there is no "evaluate function".
Another thing is where does the prediction Mat belong to?In java you can not just put it in the end of the class.
Thanks=)
The following code is for finding the digits
here's some code to try:
import org.opencv.core.*;
import org.opencv.imgproc.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.ml.*;
import org.opencv.utils.*;
import java.util.*;
class SimpleSample {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String[] args) {
// samples/data/digits.png, have a look at it.
Mat digits = Imgcodecs.imread("digits.png", 0);
// setup train/test data:
Mat trainData = new Mat(),
testData = new Mat();
List<Integer> trainLabs = new ArrayList<Integer>(),
testLabs = new ArrayList<Integer>();
// 10 digits a 5 rows:
for (int r=0; r<50; r++) {
// 100 digits per row:
for (int c=0; c<100; c++) {
// crop out 1 digit:
Mat num = digits.submat(new Rect(c*20,r*20,20,20));
// we need float data for knn:
num.convertTo(num, CvType.CV_32F);
// 50/50 train/test split:
if (c % 2 == 0) {
// for opencv ml, each feature has to be a single row:
trainData.push_back(num.reshape(1,1));
// add a label for that feature (the digit number):
trainLabs.add(r/5);
} else {
testData.push_back(num.reshape(1,1));
testLabs.add(r/5);
}
}
}
// make a Mat of the train labels, and train knn:
KNearest knn = KNearest.create();
knn.train(trainData, Ml.ROW_SAMPLE, Converters.vector_int_to_Mat(trainLabs));
// now test predictions:
for (int i=0; i<testData.rows(); i++)
{
Mat one_feature = testData.row(i);
int testLabel = testLabs.get(i);
Mat res = new Mat();
float p = knn.findNearest(one_feature, 1, res);
System.out.println(testLabel + " " + p + " " + res.dump());
}
//// hmm, the 'real world' test case probably looks more like this:
//// make sure, you follow the very same preprocessing steps used in the train phase:
// Mat one_feature = Imgcodecs.imread("one_digit.png", 0);
// Mat feature; one_feature.convertTo(feature, CvTypes.CV_32F);
// Imgproc.resize(feature, feature, Size(20,20));
// int predicted = knn.findNearest(feature.reshape(1,1), 1);
}
}
I am working on solving a linear programming problem using joptimizer.
My problem is:
Maximize (x1*f1 + x2*f2 + x3*f3)
such that (x1*v1 + x2*v2 + x3*v3) <= h
I need to find x1, x2 and x3.
I do not know how to create a joptimizer input from the above equation.
Java doc is available here
http://www.joptimizer.com/apidocs/index.html
simple example
minimize 3x+4y such that 2x+3y >= 8, 5x+2y >= 12, x >= 0, y >= 0
My sample code for solving simple linear programming question is below:
package test_joptimizer;
import com.joptimizer.functions.ConvexMultivariateRealFunction;
import com.joptimizer.functions.LinearMultivariateRealFunction;
import com.joptimizer.optimizers.JOptimizer;
import com.joptimizer.optimizers.OptimizationRequest;
import org.apache.log4j.BasicConfigurator;
/**
* #author K.P.L.Kanchana
*/
public class Main {
public static void main(String[] args) throws Exception {
// Objective function (plane)
LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] {3.0, 4.0}, 0); //minimize 3x+4y
//inequalities (polyhedral feasible set G.X<H )
ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4];
// x >= 0
inequalities[0] = new LinearMultivariateRealFunction(new double[]{-1.0, 0.00}, 0.0); // focus: -x+0 <= 0
// y >= 0
inequalities[1] = new LinearMultivariateRealFunction(new double[]{0.0, -1.00}, 0.0); // focus: -y+0 <= 0
// 2x+3y >= 8
inequalities[2] = new LinearMultivariateRealFunction(new double[]{-2.0, -3.00}, 8.0); // focus: -2x-3y+8 <= 0
// 5x+2y >= 12
inequalities[3] = new LinearMultivariateRealFunction(new double[]{-5.0, -2.00}, 12.0);// focus: -5x-2y+12 <= 0
//optimization problem
OptimizationRequest or = new OptimizationRequest();
or.setF0(objectiveFunction);
or.setFi(inequalities);
//or.setInitialPoint(new double[] {0.0, 0.0});//initial feasible point, not mandatory
or.setToleranceFeas(1.E-9);
or.setTolerance(1.E-9);
//optimization
JOptimizer opt = new JOptimizer();
opt.setOptimizationRequest(or);
int returnCode = opt.optimize();
double[] sol = opt.getOptimizationResponse().getSolution();
System.out.println("Length: " + sol.length);
for (int i=0; i<sol.length/2; i++){
System.out.println( "X" + (i+1) + ": " + Math.round(sol[i]) + "\ty" + (i+1) + ": " + Math.round(sol[i+1]) );
}
}
}
Maybe you would like to have a look at the following sample code too.
Don't forget to import the dependecies from http://www.joptimizer.com/downloadWithAdd.html.
You should download and import external three jar files ( /joptimizer-4.0.0.jar, /joptimizer-4.0.0-dependencies.zip, /joptimizer-4.0.0-sources.jar) into your project manually. The .zip file demands unzipping too.
import java.util.Arrays;
import com.joptimizer.optimizers.*;
public class LCLP {
// min (x) for J = C'*X;
// s.t.
// A*X = b;
// X <= 0;
// X = [x1;x2;x3;...xN]
public static void main(String[] args) throws Exception {
// Example from http://www.joptimizer.com/linearProgramming.html
//Objective function
double[] c = new double[] { -1., -1. };
//Inequalities constraints
double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}};
double[] h = new double[] {2., 1./2., 2., 1./2.};
//Bounds on variables
double[] lb = new double[] {0 , 0};
double[] ub = new double[] {10, 10};
//optimization problem
LPOptimizationRequest or = new LPOptimizationRequest();
or.setC(c);
or.setG(G);
or.setH(h);
or.setLb(lb);
or.setUb(ub);
or.setDumpProblem(true);
//optimization
LPPrimalDualMethod opt = new LPPrimalDualMethod();
opt.setLPOptimizationRequest(or);
opt.optimize();
double[] sol = opt.getOptimizationResponse().getSolution();
System.out.println("Solution = " + Arrays.toString(sol));
}
}
So as per usual I've got a pretty bad logic error in my code that my compiler isn't catching and thus my output is not returning the values i need and i was wondering if someone could give me a nudge in the right direction as to how to solve this pesky error. But before you guys get to that it might help if i explain whats going on a bit . so in the main I am trying to assign value 'x' aa array of numbers that gets carried over to getAllEvens in another file but somewhere along the way to the output screen the value changes get negated or didn't happen at all and all i get are zeros.
i would really appreciate any help or suggestions on this but please try to keep onsets along the lines of my code or at least not use too many advanced methods as I'm trying to keep this in line with a lab I'm doing for school. so now on to the code
code in the main
`int[] x = {2,4,6,8,10,12,14};
int[] x = {2,4,6,8,10,12,14};
int[] y = {1,2,3,4,5,6,7,8,9};
int[] z = {2,10,20,21,23,24,40,55,60,61};
System.out.println("Odds - " + Arrays.toString(OddsAndEvens.getAllOdds(x)));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(x)));
code in the other file
private static int[] cf = new int[20];
public static int countEm(int[] array, boolean odd)
{
cf=array;
return 0;
}
public static int[] getAllEvens(int[] array)
{
int[]vegeta = new int[20];
int VegetaScouterCount = 0;
int[] XboxThreeYearOld = new int[20];
for(int f : cf)
{
if(array[f]%2==0)
{
vegeta[VegetaScouterCount]=cf[f];
VegetaScouterCount++;
XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
}
XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
}
return XboxThreeYearOld;
}
(please ignore the "hip" Slang)
output i get
Odds - []
Evens - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ouput i want
Odds - []
Evens - [2, 4, 6, 8, 10, 12, 14]
any way id appreciate any help in pointing me in the right direction.
You haven't initialized your cf array, so Java will automatically assign default values to it, meaning each element will have the value zero.
Also, you're using cf (which is entirely composed of zeros) to check whether a number is even, so it is 0 % 2.
Also, you're assigning the elements of cf to vegeta, which is turn is copied into XboxThreeYearOld, which is the returned value. So, in consequence, your returned array will be populated with zeroes.
To get around your issue, use the following:
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
vegeta[VegetaScouterCount] = array[i];
VegetaScouterCount++;
XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
}
XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
}
This,
for(int f : cf)
{
if(array[f]%2==0)
{
Accesses the value at f of array. I think you wanted to check if f is even.
for(int f : array)
{
if(f%2==0)
To really fix your code, I would start by writing a method to count the even values. Like,
static int countEvens(int[] arr) {
int count = 0;
for (int i : arr) {
if (i % 2 == 0) {
count++;
}
}
return count;
}
Then you can use that to get your odds and evens like
static int[] getAllEvens(int[] array) {
int[] out = new int[countEvens(array)];
int pos = 0;
for (int f : array) {
if (f % 2 == 0) {
out[pos++] = f;
}
}
return out;
}
and then
static int[] getAllOdds(int[] array) {
int[] out = new int[array.length - countEvens(array)];
int pos = 0;
for (int f : array) {
if (f % 2 != 0) {
out[pos++] = f;
}
}
return out;
}
If there is not real requirement for an array it might be easier using a growing collection like Sets or Lists. But using the given structure you are using the for each loop incorrectly.
The variable f is not an index but the value of cf for every position. And because cf is initialized with length 20 and zero filled it will always return 0.
try with a traditional for loop i.e. for (int i=0; i<cf.length;i++){ // do work here } and check output.
There might be other logical errors the compiler won't catch because it's not a syntax or type issue.
before you print the odds and evens you must call countem() method
instead just change vegeta[VegetaScouterCount]=cf[f]; to vegeta[VegetaScouterCount]=array[f];
the problem is that your array cf was just instanciated with size of 20 BUT all of the indexes are 0 by default until you tell it otherwise
I have three equations like the following ones:
x + y + z = 100;
x + y - z = 50;
x - y - z = 10;
How can I find the values of x, y, and z with Java?
String equation1="x+y+z=100;";
String equation2="x+y-z=50;";
String equation3="x-y-z=10;";
int[] SolveEquations(equation1,equation2,equation3) {
// to do
// how to do?
}
Do you have any possible solutions or other common frameworks?
You can use determinant to calculate values of x y and z.
Logic can be found out here http://www.intmath.com/Matrices-determinants/1_Determinants.php
And then you need to implement it in java using 3 dimensional arrays.
Since you're writing Java, you can use the JAMA package to solve this. I'd recommend a good LU decomposition method.
It's a simple linear algebra problem. You should be able to solve it by hand or using something like Excel pretty easily. Once you have that you can use the solution to test your program.
There's no guarantee, of course, that there is a solution. If your matrix is singular, that means there is no intersection of those three lines in 3D space.
you can use the java matrix package JAMA. See the full page of this example below here
/*
*Solving three variable linear equation system
* 3x + 2y - z = 1 ---> Eqn(1)
* 2x - 2y + 4z = -2 ---> Eqn(2)
* -x + y/2- z = 0 ---> Eqn(3)
*/
import Jama.Matrix;
import java.lang.Math.*;
public class Main {
public Main() {
//Creating Arrays Representing Equations
double[][] lhsArray = {{3, 2, -1}, {2, -2, 4}, {-1, 0.5, -1}};
double[] rhsArray = {1, -2, 0};
//Creating Matrix Objects with arrays
Matrix lhs = new Matrix(lhsArray);
Matrix rhs = new Matrix(rhsArray, 3);
//Calculate Solved Matrix
Matrix ans = lhs.solve(rhs);
//Printing Answers
System.out.println("x = " + Math.round(ans.get(0, 0)));
System.out.println("y = " + Math.round(ans.get(1, 0)));
System.out.println("z = " + Math.round(ans.get(2, 0)));
}
public static void main(String[] args) {
new Main();
}
}
You can also use Commons Math. They have a section of this in their userguide (see 3.4)
Create a parser using ANTLR. Then evaluate the AST using Gaussian elimination.
Use Gaussian_elimination it's incredibly easy, but there are some values you may have hard life calculating.
Code example
try this, please:
import org.apache.commons.math3.linear.*;
import org.junit.Assert;
import org.junit.Test;
/**
* Author: Andrea Ciccotta
*/
public class LinearSystemTest extends Assert {
/**
* Ax = B
* 2x + 3y - 2z = 1
* -x + 7y + 6x = -2
* 4x - 3y - 5z = 1
* <p>
* it will use the LUDecomposition:
* LU decomposition:
* 1. find A = LU where LUx = B
* 2. solve Ly = B
* 4. solve Ux = y
*/
#Test
public void linearSystem3x3Test() {
final RealMatrix coefficients = new Array2DRowRealMatrix(new double[][]{{2, 3, -2}, {-1, 7, 6}, {4, -3, -5}});
final DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
final RealVector constants = new ArrayRealVector(new double[]{1, -2, 1}, false);
final RealVector solution = solver.solve(constants);
final double[] arraySolution = solution.toArray();
assertEquals(arraySolution[0], -0.36986301369863006, 0);
assertEquals(arraySolution[1], 0.1780821917808219, 0);
assertEquals(arraySolution[2], -0.6027397260273972, 0);
}
}
There are many ways to solve linear system equations. There is a simplest way to perform this. In the example the java code solve for two variables USING Matrix method but you can modify to perform 3 variables calculations.
import java.util.Scanner; //OBJETO SCANNER
public class SYS2 {
public static void main (String args[]) {
//VARIABLE DECLARATION SPACE
int i=0,j = 0;
float x,y;
Scanner S = new Scanner (System.in);
int EC3[][]= new int [2][3]; //ARRAY TO STORE EQUATION 2X3
float DET1=0;
float DET2 =0;
float DETA=0;
float DETB=0;
//END VARIABLE DECLARATIONS
System.out.println("Enter Equation System : ");
for (i=0; i< 2; i++) {
for (j=0; j< 3; j++)
EC3[i][j] = S.nextInt();
}
System.out.println("SISTEMA DE ECUACION LINEAL: "); //THIS SENTENCE ONLY PRINT THE CATCHED VALUES OF EQUATION
for (i=0; i< 2; i++) {
for (j=0; j< 3; j++)
System.out.print(EC3[i][j] + " ");
System.out.println();
}
// System.out.print("Determinante A de la Matriz: ");
// System.out.print((EC3[0][2] * EC3[1][1]) - (EC3[0][1]*EC3[1][2]) );
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DET1= ((EC3[0][2] * EC3[1][1]) -( EC3[0][1]*EC3[1][2]));
}
// System.out.print(DET1 );
// System.out.println();
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DET2= ((EC3[0][0] * EC3[1][1]) - (EC3[0][1]*EC3[1][0]));
}
// System.out.print("Determinante B de la Matriz: ");
// System.out.println(DET2 );
x = (DET1 / DET2);
System.out.println();
System.out.println("X = " + x);
System.out.print("=======================");
//FIN PARA VALOR DE X
//COMIENZO DE VALOR DE Y
// System.out.print("Determinante A de la Matriz Y: ");
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DETA= EC3[0][0] * EC3[1][2] - EC3[0][2]*EC3[1][0];
// System.out.print(DETA );
// System.out.println();
}
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DETB= EC3[0][0] * EC3[1][1] - EC3[0][1]*EC3[1][0];
}
// System.out.print("Determinante B de la Matriz Y: ");
// System.out.println(DETB );
y = DETA / DETB;
System.out.print("=======================");
System.out.println();
System.out.println("Y = " + y);
System.out.print("=======================");
}
}