I working through a few exercises from an academic programing book. The task is to implement 2 vectors and calculate the Euclidean distance between thereof. No this is not Home Work, rather self studying.
I'm seeking some feedback on the correctness of my distance implementation.
public class EuclideanDist
{
public static void main(String[] args)
{
EuclideanDist euc = new EuclideanDist();
Random rnd = new Random();
int N = Integer.parseInt(args[0]);
double[] a = new double[N];
double[] b = new double[N];
double[] x = new double[N];
euc.print(euc.init(a, rnd));
euc.print(euc.init(b, rnd));
print(euc.distance(a, b, x));
}
private double[] init(double[] src, Random rnd)
{
for(int i = 0; i < src.length; i++)
{
src[i] = rnd.nextDouble();
}
return src;
}
private double[] distance(double[] a, double[] b, double[] x)
{
double diff;
int N = a.length;
for(int i = 0; i < N; i++)
{
diff = a[i] - b[i];
x[i] = Math.sqrt(diff * diff);
}
return x;
}
private static void print(double[] x)
{
int N = x.length;
for(int j = 0; j < N; j++)
System.out.print(" " + x[j] + " ");
System.out.println();
}
}
Based on the suggestions of #AlanStokes, the following codes seems to be one solution (I have tested it):
import java.util.Random;
public class EuclideanDist {
public static void main(String[] args) {
EuclideanDist euc = new EuclideanDist();
Random rnd = new Random();
int N = Integer.parseInt(args[0]);
double[] a = new double[N];
double[] b = new double[N];
euc.print(euc.init(a, rnd));
euc.print(euc.init(b, rnd));
System.out.println(euc.distance(a, b));
}
private double[] init(double[] src, Random rnd) {
for (int i = 0; i < src.length; i++) {
src[i] = rnd.nextDouble();
}
return src;
}
private double distance(double[] a, double[] b) {
double diff_square_sum = 0.0;
for (int i = 0; i < a.length; i++) {
diff_square_sum += (a[i] - b[i]) * (a[i] - b[i]);
}
return Math.sqrt(diff_square_sum);
}
private void print(double[] x) {
for (int j = 0; j < x.length; j++) {
System.out.print(" " + x[j] + " ");
}
System.out.println();
}
}
Related
My code is returning Runtime error, but I don't Know how to fix this. This code is about the problem 104. I tried to change somethings but nothing... I read about this error and basically is associated with the Scanner.
Please Help me!
import java.util.Scanner;
public class Main {
static int MAX = 20;
static double LUCRO_MIN = 1.01;
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n, i, j;
double v;
while(sc.hasNext()) {
double[][] W = new double [MAX][MAX];
n = sc.nextInt();
sc.nextLine();
for(i = 0; i < n; i++) {
int pos = 0;
String linha = sc.nextLine();
String vertice[] = linha.split(" ");
for(j = 0; j < n; j++) {
if(i == j) {
W[i][i] = 0;
continue;
}
v = Double.parseDouble(vertice[pos]);
W[i][j] = v;
pos++;
}
}
Converte(n, W);
}
}
static public void Imprime (int i, int j, int l, int P[][][]) {
if(l == 0)
System.out.printf ("%d\n", i + 1);
else {
System.out.printf ("%d ", i + 1);
Imprime (P[l][i][j], j, l - 1, P);
}
}
static void IniZero (int n, double m[][][], int l) {
int i, j;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
m[l][i][j] = 0;
}
static void Converte(int n, double W[][]) {
double[][][] B = new double [MAX][MAX][MAX];
int [][][]P = new int [MAX][MAX][MAX];
int l, i, j, k;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++) {
B[1][i][j] = W[i][j];
if(W[i][j] > 0)
P[1][i][j] = j;
}
for(l = 2; l <= n; l++) {
IniZero(n, B, l);
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
for(k = 0; k < n; k++) {
if(B[l][i][j] < W[i][k] * B[l - 1][k][j]) {
B[l][i][j] = W[i][k] * B[l - 1][k][j];
P[l][i][j] = k;
if(B[l][i][i] >= LUCRO_MIN) {
Imprime(i, i, l, P);
return;
}
}
}
}
System.out.printf("no arbitrage sequence exists\n");
}
}
Change scanner like this
Scanner input = new Scanner(System.in);
TO
Scanner input = new Scanner(new FileInputStream(args[0]));
and i recommad you to use input.hasNext() instead of input.nextInt();this can cause nullpointerexception
I am working on a project that requires a pattern recognition program. I will receive a data file with 50000+ data points, and have to recognize if a certain pattern is present. If the sum of the square regression is above a certain value, I have the pattern, otherwise, I keep cycling to the end of the of the file. However, at around datapoint 1000 ~ 3500, the sum settles and does not change. I cannot figure out why it won't change.
public class Recognition {
private static final double[] pattern = {102.0909091,
...
-102};
private static double[] temp = new double[161];
private static int[] sums;
private static final int threshold = 2107270;
private static Scanner reader;
private static PrintWriter writer;
public static int[] rec(int[] array) {
sums = new int[array.length];
int[] solution = array;
int sum = 0;
for (int x = 0; x < 161; x++) {
temp[x] = Math.pow((array[x] - pattern[x]), 2);
solution[x] = 0;
sums[x] = sumArray();
}
loop:
for (int x = 161; x < array.length; x++) {
sum = sumArray();
if (sum > threshold) {
solution[x] = 1;
cycleArray();
sums[x] = sum;
continue loop;
}
sums[x] = sum;
solution[x] = 0;
cycleArray();
temp[0] = Math.pow((array[x] - pattern[0]), 2);
}
return solution;
}
private static int sumArray() {
int sum = 0;
for (int x = 0; x < temp.length; x++) {
sum += temp[x];
}
return sum;
}
private static void cycleArray() {
for (int x = (temp.length - 1); x > 0; x--) {
temp[x] = temp[x - 1];
}
}
public static void main(String[] args0) throws FileNotFoundException {
reader = new Scanner(new File("data1.txt");
writer = new PrintWriter(new File("pattern.txt"));
int[] data = new int[50000];
int x = 0;
while (reader.hasNext()) {
data[x] = reader.nextInt();
x++;
}
int[] solutions = rec(data);
for (int y = 0; y < solutions.length; y++) {
writer.printf("%d: %d, Running Sum: %d\n", y + 1, solutions[y], sums[y]);
System.out.println(solutions[y]);
}
}
}
For clarification, the pattern length is 161 integers. If the pattern is recognized, then a 1 is outputted, otherwise a 0 is outputted.
Any and all help is appreciated.
Here's my whole idea of it, and I dont get stuck except when i hit the max value
public class PatternRecognition {
private double[] pattern = new double[161];
private double[] temp = new double[161];
private int[] sums;
private static final int threshold = 2107270;
public int[] rec(int[] array) {
sums = new int[array.length];
int[] solution = array;
int sum = 0;
for (int x = 0; x < 161; x++) {
temp[x] = Math.pow((array[x] - pattern[x]), 2);
solution[x] = 0;
sums[x] = sumArray(temp);
}
for (int x = 0; x < array.length-temp.length; x++) {
for (int x2 =0; x2<temp.length ; x2++)
temp[x2] = Math.pow((array[x+x2] - pattern[x2]), 2);
sum = sumArray(temp);
if (sum > threshold)
solution[x] = 1;
else solution[x] = 0;
sums[x] = sum;
}
return solution;
}
private int sumArray(double[] temp) {
int sum = 0;
for (int x = 0; x < temp.length; x++) {
sum += temp[x];
}
return sum;
}
private void cycleArray() {
for (int x = (temp.length - 1); x > 0; x--) {
temp[x] = temp[x - 1];
}
}
public static void main(String[] args0) {
int[] data = new int[50000];
int x = 0;
while (x<data.length) {
data[x] = x/2;
x++;
}
PatternRecognition p=new PatternRecognition();
x=0;
while (x<p.pattern.length) {
p.pattern[x] = x+1;
x++;
}
int[] solutions = p.rec(data);
for (int y = 0; y < solutions.length; y++) {
System.out.printf("%d: %d, Running Sum: %d %d\n", y + 1, solutions[y], p.sums[y], Integer.MAX_VALUE);
System.out.println(solutions[y]);
}
}
}
import java.util.*;
public class Algorithm {
public class Matrix{
private Double[][] x;
}
public static Scanner scan = new Scanner(System.in);
private static String str;
public static void read_data(Double[] degrees, Double[] l) {
l[0] = 0.0;
int i;
for (i = 0; i < 9; i++) {
str = scan.next(); //passem la primera columna
str = scan.next(); //agafem el valor del desplaçament
str = str.substring(0, str.length()-1); //traiem la coma
l[i+1] = Double.parseDouble(str);
str = scan.next(); //passem la primera columna
str = scan.next(); //agafem el valor del desplaçament
str = str.substring(0, str.length()-1); //traiem la coma
degrees[i] = Double.parseDouble(str);
}
degrees[i] = 0.0;
}
public static void init_Matrix(Double[][] M, int i, Double[] degrees, Double[] l) {
M[0][3] = l[i];
M[0][0] = Math.cos(degrees[i]);
M[0][1] = -Math.sin(degrees[i]);
M[1][0] = Math.sin(degrees[i]);
M[1][1] = Math.cos(degrees[i]);
for (int k = 0; i < 4; k++) {
for (int j = 0; j < 4; j++) {
if (k == j && (M[k][j] == null)) M[k][j] = 1.0;
else if(M[k][j] == null) M[k][j] = 0.0;
}
}
}
public static void init_Ultima_Matrix(Double[][] M, int i, Double[] l) {
M[0][3] = l[i];
for (int k = 0; k < 4; k++) {
for (int j = 0; j < 4; j++) {
if (k == j) M[k][j] = 1.0;
else if(M[k][j] == null) M[k][j] = 0.0;
}
}
}
public static void init_Derivada(Double[][] M, int i, Double[] degrees) {
M[0][0] = -Math.sin(degrees[i]);
M[0][1] = -Math.cos(degrees[i]);
M[1][0] = Math.cos(degrees[i]);
M[1][1] = -Math.sin(degrees[i]);
for (int k = 0; k < 4; k++) {
for (int j = 0; j < 4; j++) {
if(M[k][j] == null) M[k][j] = 0.0;
}
}
}
public static void init_Ultima_Derivada(Double[][] M, int i) {
for (int k = 0; k < 4; k++) {
for (int j = 0; j < 4; j++) {
M[k][j] = 0.0;
}
}
}
public static void fulfill_Ts(Matrix[] Ts, Double[] degrees, Double[] l) {
int i;
for (i = 0; i < 9; i++) {
Ts[i].x = new Double[4][4];
init_Matrix(Ts[i].x, i, degrees, l);
}
init_Ultima_Matrix(Ts[i].x, i, l);
}
public static void fulfill_Ds(Matrix[] Ds, Double[] degrees) {
int i;
for (i = 0; i < 9; i++) {
Ds[i].x = new Double[4][4];
init_Derivada(Ds[i].x, i, degrees);
}
init_Ultima_Derivada(Ds[i].x, i);
}
private static Double[][] product(Double[][] A, Double[][] B){
Double suma = 0.0;
Double result[][] = new Double[4][4];
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
suma = 0.0;
for(int k = 0; k < 4; k++){
suma += A[i][k] * B[k][j];
}
result[i][j] = suma;
}
}
return result;
}
private static void calc_Jacobian(Matrix[] Ts, Matrix[] Ds, int i, Double[][] jacobian) {
Double[][] tmp;
if (i == 0) tmp = Ds[0].x;
else tmp = Ts[0].x;
for (int j = 1; j < 10; j++) {
if (j == i) tmp = product(tmp, Ds[j].x);
else tmp = product(tmp, Ts[j].x);
}
jacobian[0][i] = tmp[0][3];
jacobian[1][i] = tmp[1][3];
jacobian[2][i] = tmp[0][0];
}
public static void main(String[] args) {
Matrix[] Ts = new Matrix[10];
Matrix[] Ds = new Matrix[10];
for (int i = 0; i < 10; i++) {
Ts[i].x = new Double[4][4];
Ds[i].x = new Double[4][4];
}
Double[] degrees = new Double[10];
Double[] l = new Double[10];
read_data(degrees, l);
fulfill_Ts(Ts, degrees, l);
fulfill_Ds(Ds, degrees);
Matrix jacobian = new Matrix();
jacobian.x = new Double[3][9];
for (int j=0; j<9; j++)
calc_Jacobian(Ts, Ds, j, jacobian.x);
//La matriu Jacobiana hauria d'estar acabada
}
}
Well, this is my code. The error is in the first line where says "Matrix jacobian = new Matrix();". Have I declared it wrong? The definition of Matrix is at the beginning of the code.
It says: No enclosing instance of type Algorithm is accessible. Must qualify the allocation with an enclosing instance of type Algorithm (e.g. x.new A() where x is an instance of Algorithm).
Moreover, I get an Exception with this: "Matrix[] Ts = new Matrix[10];". Can't I declare an array of elements Matrix?
Thank you very much.
Yes, try this: Matrix M = new Matrix();
This one Matrix[] Ts = new Matrix[10]; is valid but you should also loop through the array elements and initialize them by calling the constructor. Otherwise, they will remain having null values.
Change
public class Matrix
to
public static class Matrix
Creating a nested class without the static modifier creates a closure, which allows you to reference non-static members of the enclosing instance. If you don't declare it static, you need an enclosing instance (ie, a this) to create it, which you don't have in static void main().
Explaining a closure is beyond the scope of this answer, but it would be a private member Algorithm _closure in Matrix, which is implicitly referenced (the same way this is), when you mention a non-static member of Algorithm.
I'm having trouble with this polynomial class, specifically the checkZero and differentiate methods. The checkZero class is supposed to see if there are any leading coefficients in the polynomial, and if so, it should resize the coefficient array. The differentiate method should find the derivative of a polynomial, but I keep getting ArrayIndexOutOfBounds errors.
public class Polynomial {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Polynomial test = new Polynomial(fa);
}
public Polynomial() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Polynomial(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Polynomial(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Polynomial add(Polynomial p) {
int n = getDegree();
int m = p.getDegree();
Polynomial result = new Polynomial(Polynomial.max(n, m));
int i;
for (i = 0; i <= Polynomial.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPolynomial () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Polynomial multiplyCon (double c){
int n = getDegree();
Polynomial results = new Polynomial(n);
for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient
results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient
}
return results;
}
public Polynomial multiplyPoly (Polynomial p){
int n = getDegree();
int m = p.getDegree();
Polynomial result = null;
for (int i = 0; i <= n; i++){
Polynomial tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method
if (result == null){
result = tmpResult;
} else {
result = result.add(tmpResult);
}
}
return result;
}
public void checkZero(){
int newDegree = getDegree();
int length = coefficients.length;
float testArray[] = coefficients;
for (int i = coefficients.length-1; i>0; i--){
if (coefficients[i] != 0){
testArray[i] = coefficients[i];
}
}
for (int j = 0; j < testArray.length; j++){
coefficients[j] = testArray[j];
}
}
public Polynomial differentiate(){
int n = getDegree();
int newPolyDegree = n - 1;
Polynomial newResult = new Polynomial();
if (n == 0){
newResult.setCoefficient(0, 0);
}
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
return newResult;
}
}
There might be more problems, but one is a problem with your differentiate method:
int n = getDegree();
...
Polynomial newResult = new Polynomial();
...
for (int i = 0; i <= n; i++)
{
newResult.setCoefficient(i, coefficients[i + 1] * (i + 1)); //This line
}
Your paramaterless constructor initializes an array with length 1, so "newResult" will only have 1 index, and you try to put something into place i, which goes above 1 if the Polynomial you are in have an array of greater length than 1.
First, a few code notes:
New arrays are automatically initialized to 0 in Java. This is not needed.
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
I also see many lines which might become more readable and compact if you use the trinary operator, for example:
int i;
for (i = 0; i <= Polynomial.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
Could become something like
for (int i = 0; i <= result.getDegree(); i++)
result.setCoefficient(i,
i>n?0:coefficients[i] +
i>m?0:p.getCoefficient(i));
The one bug I did spot was here:
int n = getDegree();
....
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
This will always call coefficients[coefficients.length] on the last iteration, which will always fail.
The stack trace of the exception when you ran this program should tell you exactly where the error is, by the way.
I'm trying to create a matrix of random double numbers. The matrix must be of size n x n and all numbers must be between 1 and 100. I've been trying to sort it out for ages now and I know it must be something so simple (as it usually is).
Here is my code:
public static void main(String[] args) {
PrintRandomGraph(RandomArray(4));
}
private static double[] RandomArray(int n) {
double[] randomArray = new double[n];
double[][] randomMatrix = new double [n][n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
Integer r = rand.nextInt()% 100;
randomArray[i] = Math.abs(r);
for (int j = 0; j < n; j++) {
Arrays.fill(randomMatrix, i, i+1, randomArray);
}
}
return randomArray;
}
private static void PrintRandomGraph(double[] inputArray) {
int n = inputArray.length;
double[] showArray = new double[n];
double[][] showMatrix = new double [n][n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
double r = inputArray[i];
showArray[i] = r;
Arrays.fill(showMatrix, i, i+1, showArray);
}
}
System.out.println(Arrays.deepToString(showMatrix));
}
When I run the code I get a random array repeated n times like :
[[63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0]]
I think I need to go back to the top of the for loop and add the new array...? Please help =(
Any help is much appreciated. Thank you.
Did you try something like this:
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
to Print the graph:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(array[i][j]);
}
}
}
To Print Graph with Square brackets:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" [ ");
for (int j = 0; j < n; j++) {
System.out.print(array[i][j]);
}
//Put println instead of print here to have each row in a new line
System.out.print(" ]");
}
}
Also, this seems a lot like homework, if it is, please tag it like so :)
Hi all this provides the answer I was looking for
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];
double[] randomArray = new double [n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args){
//PrintRandomGraph(RandomArray(5));
System.out.println(Arrays.deepToString(RandomArray(5)));
}