I want to calculate the distance between two co-ordinates, which are stored in a CVS file. There are two column mentioned in CVS files for X and Y Co-ordinates respectively.
I want to apply Euclidean Distance Formula between those stored points and printing the result on the console. For the same I have retrieved the CVS file's point as an array, printing that array on the console, and applying the Distance Formula, and after that I want to sort them according to ascending order and selecting the one having minimum distance for further problem.
But my problem is that the distance is not being displayed on the console. The code is mentioned below:
import java.util.*;
import java.io.*;
public class distance {
public void euclidianDistanceFromFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine(); // for ignoring the header of file
int row = 0;
int col = 0;
double dist;
String[][] numbers = new String[8][2];
double Cordx[] = new double[8];
double Cordy[] = new double[2];
while ((line = br.readLine()) != null && row < 8) {
StringTokenizer st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
// get next token and store it in the array
numbers[row][col] = st.nextToken();
col++;
}
col = 0;
row++;
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 2; col++) {
System.out.print(" " + numbers[row][col]);
}
System.out.println(" ");
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 2; col++) {
Cordx[row] = Double.parseDouble(numbers[row][col]);
Cordy[col] = Double.parseDouble(numbers[row][col]);
}
}
for (int i = 0; i < Cordx.length; i++) {
dist = 0;
for (int j = 0; j < Cordy.length; j++) {
double diffx = Cordx[i + 1] - Cordx[i];
double diffy = Cordy[j + 1] - Cordy[j];
dist = dist + Math.sqrt(Math.pow(diffx, 2) + Math.pow(diffy, 2));
}
System.out.println("distance is" + "" + dist);
}
}
public static void main(String[] argv) throws IOException {
try {
distance dist = new distance();
dist.euclidianDistanceFromFile("src\\ploting\\ravm.csv");
// ravm is the cvs file from which i retrieve the points and calculate the distance.
} catch (Exception e) {
e.getMessage();
}
}
}
First of all, change e.getMessage() to e.printStackTrace() and you'll be able to see that an ArrayIndexOutOfBoundsException is happening (you're trying to access an inexistent position in some array).
The error is in this loop:
for (int i = 0; i < Cordx.length; i++) {
dist = 0;
for (int j = 0; j < Cordy.length; j++) {
double diffx = Cordx[i + 1] - Cordx[i];
double diffy = Cordy[j + 1] - Cordy[j];
Note that when i is equals to Cordx.length - 1 (aka "the last position"), you try to access Cordx[i + 1] (one position after the last one), causing the error. Try to do the loops this way:
for (int i = 0; i < Cordx.length - 1; i++) {
dist = 0;
for (int j = 0; j < Cordy.length - 1; j++) {
Related
This is one first post here, Pardon me if my question doesn't meet required standards here.
I have written a piece of code which takes input for two matrix from two separate files and performs multiplication and output the data to a new file.
It gives perfect output for 2x3 or 3x3 matrix. If i give input of 4x4 matrix i get array index out of bound runtime exception. I don't understand the reason as i dynamically create index
I get an array index out of bound exception at line 40.
I get an error.
![Snipet][2]
List item
public class MM {
private BufferedReader br;
private int sum = 0;
private final static String matrixA="matrixA.txt";
private final static String matrixB="matrixB.txt";
public static void main(String[] args) {
new MM().MathMultiplicationValues(matrixA, matrixB);
}
private void MathMultiplicationValues(String mat1, String mat2) {
try {
br = new BufferedReader(new FileReader(mat1));
String line;
int mat1rows = 0, mat1cols = 0, mat2rows = 0, mat2cols = 0;
while ((line = br.readLine()) != null) {
mat1cols = line.split(" ").length + 1;
mat1rows++;
}
br.close(); // To close file
br = new BufferedReader(new FileReader(mat2)); // to read input from file.
while ((line = br.readLine()) != null) {
mat2cols = line.split(" ").length + 1;
mat2rows++;
}
int[][] mat1vals = new int[mat1rows ][mat1cols ];
int[][] mat2vals = new int[mat2rows ][mat2cols ];
br.close();
br = new BufferedReader(new FileReader(mat1));
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
br = new BufferedReader(new FileReader(mat2));
for (int i = 1; i < mat2rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat2cols; j++) {
mat2vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
if ((mat1cols-1) == mat2rows) {
int[][] resltmat = new int[mat1rows + 1][mat2cols + 1];
for (int i = 1; i < mat1rows + 1; i++) { //Loop does matrix multiplication.
for (int j = 1; j < mat1cols; j++) {
for (int k = 0; k < mat2rows + 1; k++)
sum = sum + mat1vals[i][k] * mat2vals[k][j];
resltmat[i][j] = sum;
sum = 0;
}
}
final PrintWriter pw = new PrintWriter("Answer.txt"); //Creates a new file called Matrix Answer.
for (int i = 1; i < mat1rows + 1; i++)
{
for (int j = 1; j < mat2cols; j++) {
pw.print(resltmat[i][j] + " "); // Writes the output to file the file called MatrixAnswer
}
pw.println();
}
pw.close();
} else // If no of columns not equal to rows control passes to else block.
System.out.println("Multiplication of Matrix is not possible because columns are not equal to rows");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Might be because of this
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
i = mat1rows on the last iteration which is OOB. Change for (int i = 1; i < mat1rows + 1; i++) to for (int i = 1; i < mat1rows; i++)
As you used in the allocation, the dimension of the resulting matrix are mat1rows x mat2cols. Thus in the computation of resltmat[i][j] the index i has bound mat1rows (check) and the index j has the upper bound mat2cols (fail). Thus change the range of j from mat1cols to mat2cols.
I have three run arguments that are min width, max width and the text file name. The text files are filled with one long string of random characters. I want to put each character into a grid spot. But all I get back is the string itself from the file. How do I make the grid?
class GridCipher{
static int minGridWidth;
static int maxGridWidth;
static File inputFile;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args))
processInput();
}
static final String usage = "Usage: GridWriter min_width max_width input_file_name";
static boolean handleArguments(String[] args) {
// Check for correct number of arguments
if (args.length != 3) {
System.out.println("Wrong number of command line arguments.");
System.out.println(usage);
return false;
}
try {
minGridWidth = Integer.parseInt(args[0]);
maxGridWidth = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.out.println("min_width and max_width must be integers.");
System.out.println(usage);
return false;
}
inputFile = new File(args[2]);
if (!inputFile.canRead()) {
System.out.println("The file " + args[2] + " cannot be opened for input.");
return false;
}
return true;
}
static void processInput() throws FileNotFoundException {
Scanner input = new Scanner(inputFile);
String line = input.nextLine();
int length = line.length(); // number of characters.
// Try each width in the appropriate range
for (int width = minGridWidth; width <= maxGridWidth; width++) {
// Determine heigth of grid
int height = line.length() / width;
// Add one to height if there's a partial last row
if (line.length() % width != 0)
height += 1;
loadUnloadGrid(line, width, height);
}
}
static void loadUnloadGrid(String line, int width, int height) {
char grid[][] = new char[height][width];
// Determine number long columns
int longColumn = line.length() % width;
if (longColumn == 0)
longColumn = width;
//Load the input data into the grid by column
int charCount = 0;
for (int c = 0; c < width; c++) {
for (int r = 0; r < height; r++) {
if (r < height - 1 || c < longColumn) {
grid[r][c] = line.charAt(charCount);
charCount += 1;
}
}
}
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
// Special handling for last row
for (int c = 0; c < longColumn; c++) {
System.out.print(grid[height - 1][c]);
}
System.out.println("\"");
}
}
If the text file has ABCDE, I just get back ABCDE. I would like the characters in a grid determined by my min and max width.
If I understand you correctly you want ABCDEFG into
A B C
D E F
G
but in the fragment writing it on screen you miss new line character
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
should be
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
System.out.println();
}
Printing grid is not correct in your program.
Change below to
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
this code
for(char[] arr : grid) {
System.out.println(Arrays.toString(arr));
}
Need little help with my programming.
I'd like to create a grid with n columns and n rows. A also would like to show or print adjacency matrix.For start I did create some code, but the results are not correct, and I don't know hot to fix it. I need this grid to calculate shortest path, mutation of this grid, ...
The first for loop create a nice grid size n*n, but I don't know how to create links between naighbour nodes. The second code (which is in comment, create a adjacency matrix, but is not correnct -> node 3-4,7-8, 11-12 shouldn't be connected (if we have 4x4 grid), and in this code is missing last 4 nodes (if n=4).
Can someone tell me where did I fail in my coding :)?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Network_1 {
public static void main(String[] args) throws Exception {
BufferedReader input1 = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter the number of columns/rows");
int cols = Integer.parseInt(input1.readLine());
input1.close();
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
if (i > 1
&& ((cols == 0 && N % i == 0) || (cols > 0 && i % cols == 0))) {
if (cols == 0) {
cols = i;
}
System.out.print("\n");
}
System.out.format("%3d", i);
}
System.out.println("\nAdjacency matrix:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
/*
// If I try to create my "grid" with this code, I do not get true results
// The Matrix is incorrect
for(int i=0; i<N-cols; i++){
for(int j=0; j<N-cols; j++){
if((cols > 0) && (i % cols == 0)){
A[i][i+1] = 0;
A[i + 1][i] = 0;
}else{
A[i][i+1] = 1;
A[i + 1][i] = 1;
A[i][i+cols] = 1;
A[i + cols][i] = 1;
}
}
}
System.out.println("Adjacency matrix2:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println("");
}
*/
}
}
Helo. I did some other approach and this work quite well for me right now. I know tis isn't the best solution, but it wokrs for now. Now I will etst if realy works...
public static int[][] make_grid(int cols) {
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
A[i][i] = 0;
int left= i - 1;
int right= i + 1;
int upper= i - cols;
int bottom= i + cols;
if (left> 0)
A[i][left] = 1;
if (rigft% cols != 0) {
if (right< N)
A[i][right] = 1;
}
if (upper> 0)
A[i][upper] = 1;
if (bottom< N)
A[i][bottom] = 1;
}
return A;
}
I have written a code in lucene, which firsts indexes xml documents, and finds the number of unique terms in the index.
Say there are n number (no.) of unique terms.
I want to generate a matrix of dimensions nXn, where
m[i][j] = (co_occurrence value of terms (i, j))/ (occurrence value of term i)
co_occurence of terms (i, j) = no. of documents in which ith term and jth terms, both are occurring
occurence of term j is the no. of documents in which the term j is occurring.
My code is working fine. But its not efficient. for large no. of files, where no. of terms are more than 2000, its taking more than 10 minutes.
here is my code for finding co_occurence -
int cooccurrence(IndexReader reader, String term_one, String term_two) throws IOException {
int common_doc_no = 0, finaldocno_one = 0, finaldocno_two = 0;
int termdocid_one[] = new int[6000];
int termdocid_two[] = new int[6000];
int first_docids[] = new int[6000];
int second_docids[] = new int[6000];
int k = 0;
for (java.util.Iterator<String> it = reader.getFieldNames(
FieldOption.ALL).iterator(); it.hasNext();) {
String fieldname = (String) it.next();
TermDocs t = reader.termDocs(new Term(fieldname, term_one));
while (t.next()) {
int x = t.doc();
if (termdocid_one[x] != 1) {
finaldocno_one++;
first_docids[k] = x;
k++;
}
termdocid_one[x] = 1;
}
}
/*
* System.out.println("value of finaldoc_one - " + finaldocno_one); for
* (int i = 0; i < finaldocno_one; i++) { System.out.println("" +
* first_docids[i]); }
*/
k = 0;
for (java.util.Iterator<String> it = reader.getFieldNames(
FieldOption.ALL).iterator(); it.hasNext();) {
String fieldname = (String) it.next();
TermDocs t = reader.termDocs(new Term(fieldname, term_two));
while (t.next()) {
int x = t.doc();
if (termdocid_two[x] != 1) {
finaldocno_two++;
second_docids[k] = x;
k++;
}
termdocid_two[x] = 1;
}
}
/*
* System.out.println("value of finaldoc_two - " + finaldocno_two);
*
* for (int i = 0; i < finaldocno_two; i++) { System.out.println("" +
* second_docids[i]); }
*/
int max;
int search = 0;
if (finaldocno_one > finaldocno_two) {
max = finaldocno_one;
search = 1;
} else {
max = finaldocno_two;
search = 2;
}
if (search == 1) {
for (int i = 0; i < max; i++) {
if (termdocid_two[first_docids[i]] == 1)
common_doc_no++;
}
} else if (search == 2) {
for (int i = 0; i < max; i++) {
if (termdocid_one[second_docids[i]] == 1)
common_doc_no++;
}
}
return common_doc_no;
}
code for calculation of knowledge matrix: -
void knowledge_matrix(double matrix[][], IndexReader reader, double avg_matrix[][]) throws IOException {
ArrayList<String> unique_terms_array = new ArrayList<>();
int totallength = unique_term_count(reader, unique_terms_array);
int co_occur_matrix[][] = new int[totallength + 3][totallength + 3];
double rowsum = 0;
for (int i = 1; i <= totallength; i++) {
rowsum = 0;
for (int j = 1; j <= totallength; j++) {
int co_occurence;
int occurence = docno_single_term(reader,
unique_terms_array.get(j - 1));
if (i > j) {
co_occurence = co_occur_matrix[i][j];
} else {
co_occurence = cooccurrence(reader,
unique_terms_array.get(i - 1),
unique_terms_array.get(j - 1));
co_occur_matrix[i][j] = co_occurence;
co_occur_matrix[j][i] = co_occurence;
}
matrix[i][j] = (float) co_occurence / (float) occurence;
rowsum += matrix[i][j];
if (i > 1)
{
avg_matrix[i - 1][j] = matrix[i - 1][j] - matrix[i - 1][0];
}
}
matrix[i][0] = rowsum / totallength;
}
for (int j = 1; j <= totallength; j++) {
avg_matrix[totallength][j] = matrix[totallength][j]
- matrix[totallength][0];
}
}
Please anyone suggest me any efficient method to implement it.
I think you can put the find process of term_one and term_two in one for loop. And you can use two hashsets to save the docid that you have found. And then use termOneSet.retainAll(termTwoSet) to get the doc which have both term_one and term_two.
I am trying to write a nested for loop that will print out the values of the following code in a specific order:
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
System.out.println(array2d[y][x]);
}
}
}
}
The current array prints the way I want it, but each printout on a separate line.
I want the output (on a single line) to be this:
1 6 11 2 7 12 3 8 13 4 9 14 5 10 15
Thanks for the help.
You can use System.out.print instead:
System.out.print(array2d[y][x] + " ");
Replace println with print and it should work
String s = "";
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[i].length; j++) {
s += array2d[i][j] + " ";
}
}
System.out.println(s);
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
StringBuilder builder = new StringBuilder();
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
builder.append(array2d[y][x]);
if(!(x == 4 && y == 2)){
builder.append(" ");
}
}
}
System.out.println(builder.toString());
}
You basically had it right, except for changing the println to be print and formatting the string how you want. I changed it a little to show how the StringBuilder works. Whenever possible I use a StringBuilder because it is more convenient.