Algorithm – Gram-Schmidt process in Java for calculating independent bases in linear spaces

In the face of a series of $$k$$ $$n$$vectors $$x_1, dots, x_k$$The Gram-Schmidt method calculates a basis $$y_1, dots, y_m$$ ($$m leq k$$) whose vectors encompass the same space as $$x_1, dots, x_k$$ but are orthogonal to each other: $$(y_i, y_j) = 0$$ for all $$i neq j$$, where the parentheses designate the inner product
$$(x, y) = sum_ {i = 1} ^ n x_i y_i.$$

Below is my code:

`net.coderodde.math.Additive`

``````package net.coderodde.math;

/ **
* This interface defines the API for adding the two elements.
*
* @param  the type of the left operand.
* @param  the type of the correct operand.
* @param   the sum type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /

/ **
* This method adds {@code a} and {@code b} and returns the sum.
*
* @param a the first element.
* @param b the second element.
* @ Return the sum of the two numbers indicated.
* /
}
``````

`net.coderodde.math.Demo`

``````package net.coderodde.math;

import net.coderodde.math.impl.ComplexVectorProductByScalar;
import net.coderodde.math.impl.ComplexNumber;
import net.coderodde.math.impl.ComplexVectorDivisible;
import net.coderodde.math.impl.ComplexVectorInnerProduct;
import net.coderodde.math.impl.ComplexVectorNegative;
import net.coderodde.math.impl.RealVectorDivisible;
import net.coderodde.math.impl.RealVectorInnerProduct;
import net.coderodde.math.impl.RealVectorNegative;
import net.coderodde.math.impl.RealVectorProductByScalar;

/ **
* This class will do a simple demo for the Gram-Schmidt process.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /

public static void main (String[] Arguments) {
vector x1 = new vector <> (1st, -1st, 1st, -1th);
vector x2 = new vector <> (5th, 1st, 1st, 1st);
vector x3 = new vector <> (- 3rd, -3th, 1st, -3th);

vector[]    orthogonalBase1 =
new GramSchmidtProcess <> (new RealVectorInnerProduct (),
new RealVectorDivisible (),
new RealVectorProductByScalar (),
new RealVectorNegative ())
Process (x1, x2, x3);

for (Vector Vector: OrthogonalBase1) {
System.out.println (vector);
}

System.out.println ("Orthogonal:" +
is Orthogonal (orthogonalBase1[0].
orthogonalBasis1[1].
0.00001));

System.out.println ("------");

// [(1, -2), (3, 4)] = [1 - 2i, 3 + 4i]
vector c1 = new vector <> (new ComplexNumber (1, -2),
new ComplexNumber (3, 4));

// [(0, -3), (1, 1)] = [-3i, 1 + i]
vector c2 = new vector <> (new ComplexNumber (0, -3),
new ComplexNumber (1, 1));

vector[]    orthogonalBase2 =
new GramSchmidtProcess <> (new ComplexVectorInnerProduct (),
new ComplexVectorDivisible (),
new ComplexVectorProductByScalar (),
new ComplexVectorNegative ())
Process (c1, c2);

for (Vector c: orthogonalBase2) {
System.out.println (c);
}

System.out.println ("Orthogonal:" +
isOrthogonalComplex (orthogonalBase2[0].
orthogonalBasis2[1].
0.00001));
}

public static  boolean baseIsOrthogonal (Vector[]    Base,
double epsilon) {
for (int i = 1; i <base.length; i ++) {
vector Goal = base[i];

for (int j = 0; j <i; j ++) {
vector Electricity = base[j];

if (! isOrthogonal (target, current, epsilon)) {
return it incorrectly;
}
}
}

return true;
}

public static boolean baseIsOrthogonalComplex (
vector[]    Base, double epsilon) {
for (int i = 1; i <base.length; i ++) {
vector Goal = base[i];

for (int j = 0; j <i; j ++) {
vector Electricity = base[j];

if (! isOrthogonalComplex (target, current, epsilon)) {
return it incorrectly;
}
}
}

return true;
}

private static boolean isOrthogonal (Vector a, vector b, double epsilon) {
Double sum = 0.0;

for (int i = 0; i <a.getNumberOfDimensions (); i ++) {
Sum + = a.get (i) * b.get (i);
}

Return sum <epsilon;
}

private static boolean isOrthogonalComplex (Vector on,
vector b
double epsilon) {
ComplexNumber sum = new ComplexNumber (0, 0);

for (int i = 0; i <a.getNumberOfDimensions (); i ++) {
ComplexNumber product = a.get (i) .multiply (b.get (i));
}

return Math.abs (sum.getRealPart ()) <epsilon &&
Math.abs (sum.getImaginaryPart ()) <epsilon;
}
}
``````

`net.coderodde.math.Divisible`

``````package net.coderodde.math;

/ **
* This interface defines the API for the division operator.
*
* @param  the type of dividend.
* @param  the type of divisor.
* @param   the type of faction.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface divisible {

/ **
* Divides {@code a} by {@code b} and returns the result.
*
* @param divident the object to be split.
* @param divisor the divisor.
* @Return the result of dividing {@code divident} by {@code divisor}.
* /
public F pitch (D1 divisor, D2 divisor);
}
``````

`net.coderodde.math.GramSchmidtProcess`

``````package net.coderodde.math;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/ **
* This class implements the method to execute
* https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
* over a given independent basis of a linear space.
*
* @param  the vertex component type.
* @param  the inner product type.
* @param   the division result type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public class GramSchmidtProcess {

/ **
* This object is responsible for the calculation of the inner product of two
* Vectors.
* /
Private Inner Product Inner product;

/ **
* This object is responsible for the division of the law.
* /
privately divisible divisible;

/ **
* This object is responsible for the calculation of products (multiplication).
* /
Private Product <FT, vector, Vector> Product;

/ **
* This object is responsible for the calculation of the addition.
* /

/ **
* This object is responsible for the calculation of negative elements.
* /
Private Negative <Vector, Vector> negative;

/ **
* Constructs the object using the method to execute the Gram-Schmidt process
* over specified basis.
*
* @param innerProduct the object for calculating inner products.
* @param divisible the object to carry out the division.
* @param product the object for multiplication.
* @param negative the object for calculating inverse.
* /
public GramSchmidtProcess (InnerProduct Inner product,
Divisible divisible,
Product <FT, vector, Vector> Product,
vector.
Negative <Vector, Vector> negative) {
this.innerProduct =
Objects.requireNonNull (
Inner product,
"The input InnerProduct is null.");

this.negative = Objects.requireNonNull (negative,
"The negative input is zero.");

this.product = Objects.requireNonNull (product,
"The entered product is null.");

this.divisible = Objects.requireNonNull (divisible,
"The Divisible input is null.");

}

/ **
* Executes the Gram-Schmidt process on {@ code basis}.
*
* @param base to process the base.
* @Return the orthogonal basis.
* /
public vector[]    process (Vector... Base) {
// validate the input base:
checkBase (basis);

// Treat the very first basic element:
vector[]    OrthogonalBase = new vector[basis.length];
orthogonal basis[0] = (Vector) new vector (base[0]);

// The actual process:
for (int i = 1; i <base.length; i ++) {
// copy-construct & x39; x & # 39; from & # 39; base[i]& # ;: 39
vector x = new vector <> (base[i]);

// Perform for each base element & # 39; x & # 39; The following:
for (int j = 0; j <i; j ++) {
// Take the inner product of the dividend:
IPT innerProductDivident =
this.innerProduct.innerProductOf (x, orthogonalBase[j]);

// take the inner product of the divisor:
IPT innerProductDivisor =
this.innerProduct.innerProductOf (orthogonalBase[j].
orthogonal basis[j]);

// Divide the divider by the divider:
FT break = divisible.divide (innerProductDivident,
innerProductDivisor);

// Multiply the above with the current base:
vector term = product.multiply (fraction, basis[j]);

// Negate the above:
term = negative.negate (term);

// Add the above to & # 39; x & # 39; added. Effectively, it subtracts "term" from
// & # 39; x & # 39; since we & # 39; term & # 39; have negated:
}

orthogonal basis[i] = x;
}

// remove the duplicates and return everything that is left:
return removeDuplicates (orthogonalBasis);
}

/ **
* This method validates the input data sent to the Gram-Schmidt process
* Implementation above.
*
* @param             the element component type.
* @param basis Apply for the base candidate.
* @throws IllegalArgumentException if the candidate is not valid.
* /
private static  void checkBase (Vector[]    baseCandidate) {
// check not null:
Objects.requireNonNull (basisCandidate, "The input base is null.");

// Check is not empty:
if (basisCandidate.length == 0) {
throw new IllegalArgumentException ("No vectors specified.");
}

int expectedDimensions = basisCandidate[0].getNumberOfDimensions ();

// Every element in the base candidate must have the same
// dimensionality:
if (expectedDimensions == 0) {
throw new IllegalArgumentException (
"The element at index 0 has no components.");
}

for (int i = 1; i <basisCandidate.length; i ++) {
if (basisCandidate[i].getNumberOfDimensions () == 0) {
// Oops. An empty element:
throw new IllegalArgumentException (
"The element at index" + i + "has no components.");
}

if (expectedDimensions
! = baseCandidate[i].getNumberOfDimensions ()) {
// Oops. Not all basic elements are the same
// dimensionality:
throw new IllegalArgumentException (
"Mismatched element dimensions: expected" +
expectedDimensions + "but was" +
basisCandidate[i].getNumberOfDimensions () +
"at index" + i + ".");
}
}
}

private static  vector[]    removeDuplicates (Vector[]    Base) {
Set <Vector> set = new HashSet <> (Arrays.asList (base));
vector[]    Vectors = new vector[set.size()];
return set.toArray (vectors);
}
}
``````

`net.coderodde.math.InnerProduct`

``````package net.coderodde.math;

/ **
* This interface defines the API for the inner product over a specific vector component
* Art.
*
* @param  the left vector type.
* @param  the right vector type.
* @param   the inner product value type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface InnerProduct {

/ **
* Calculates the inner product of the two specified vectors.
*
* @param a the first vector.
* @param b the second vector.
* @ Send back indoor product
* /
public IPT innerProductOf (Vector a, vector b);
}
``````

`net.coderodde.math.Negative`

``````                package net.coderodde.math;

/ **
* This interface defines the API for calculating negative values.
*
* @param  the input type.
* @param  the output type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface negative {

/ **
* Returns the negative of {@code element}. The negative of {@code a} is
* {@code -a} such that {@code a + (-a) = O}, where {@code O} is zero
* Element.
*
* @param element the element to be negated.
* @ back the negative of {@code element}.
* /
public O negate (I element);
}
``````

`net.coderodde.math.Product`

``````package net.coderodde.math;

/ **
* This interface defines the API for multiplication (product).
*
* @param  The type of left element to multiply.
* @param  the type of the right element to be multiplied.
* @param   the product result type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface product {

/ **
* Returns the product of {@code a} and {@code b}.
*
* @param a the first element.
* @param b the second element.
* @return the product of the two input elements.
* /
multiply public O (E1 a, E2 b);
}
``````

`net.coderodde.math.Vector`

``````package net.coderodde.math;

import java.util.Arrays;
import java.util.Objects;

/ **
* This class implements a vector / element in a {@code n} -dimensional space.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /

/ **
* The actual vector content.
* /
private final E[] components;

/ **
* Constructs the vector from the specified data.
*
* @param compiles the vector data.
* /
public Vector (E ... components) {
Objects.requireNonNull (components, "The input vector is null.");
this.components = Arrays.copyOf (components, components.length);
}

/ **
* Copy this vector.
*
* @param vector The vector to be copied.
* /
public vector (vector Vector) {
this.components = Arrays.copyOf (vector.components,
vector.components.length);
}

/ **
* Returns the {@code index} -th component of this vector.
*
* @param index of the component index.
* return the value of the {@code index} -th component.
* /
public E get (int index) {
Return components[index];
}

/ **
* Sets the value of the {@code index} -th vector component to the specified value
* Value.
*
* @param index The index of the target vector component.
* @param value The value to set.
* /
public void set (int index, E value) {
components[index] = Value;
}

/ **
* Returns the number of components in this vector.
*
* @Return the number of components in this vector.
* /
public int getNumberOfDimensions () {
return components.length;
}

@Override
public String toString () {
StringBuilder stringBuilder = new StringBuilder ("<");
String separator = "";

for (E component : components) {
stringBuilder.append(separator);
separator = ", ";
stringBuilder.append(component);
}
return stringBuilder.append(">"). toString ();
}

@Override
public int hashCode () {
return Arrays.hashCode (components);
}

@Override
public boolean equals (object o) {
if (o == null) {
return it incorrectly;
}

if (o == this) {
return true;
}

if (! o.getClass (). equals (this.getClass ())) {
return it incorrectly;
}

vector other = (Vectoro;
return arrays.equals (components, other.components);
}
}
``````

`net.coderodde.math.impl.ComplexNumber`

``````package net.coderodde.math.impl;

/ **
* This class implements a complex number. The complex number consists of a real one
* Part and an imaginary part. The imaginary part is a real number equipped with
* The imaginary unit {@code i}, for which {@code i ^ 2 = -1} applies. This class is
* immutable.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public senior class ComplexNumber {

/ **
* The real number.
* /
private final double realPart;

/ **
* The imaginary number.
* /
private final double imaginaryPart;

/ **
* Construct a new complex number.
*
* @param realPart the real part of the newly built complex
*                      Number.
* @param imaginaryPart the imaginary part of the newly built complex
*                      Number.
* /
public ComplexNumber (final double realPart, final double imaginaryPart) {
checkNotNan (realPart);
checkNotNan (imaginaryPart);
checkNotInfinite (realPart);
checkNotInfinite (imaginaryPart);
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}

/ **
* Returns the real part of this complex number.
*
* @ Return the real part of this complex number.
* /
public double getRealPart () {
return realPart;
}

/ **
* Returns the imaginary part of this complex number.
*
* @ return the imaginary part of this complex number.
* /
public double getImaginaryPart () {
return imaginaryPart;
}

/ **
* Returns the complex number corresponding to the sum of this complex
* number and the {@code other} complex number.
*
* @param others the complex number that should be added.
* Return the sum of this and {@code other} complex number.
* /
public ComplexNumber add (ComplexNumber other) {
Return new ComplexNumber (realPart + other.realPart,
imaginaryPart + other.imaginaryPart);
}

/ **
* Returns the negative of this complex number.
*
* @ back the negative of this complex number.
* /
public ComplexNumber negate () {
return new ComplexNumber (-realPart, -imaginaryPart);
}

/ **
* Returns the complex number representing the product of the two inputs
* complex numbers.
*
* @param a the first complex number.
* @param b is the second complex number.
* Return the product from {@code a} and {@code b}.
* /
multiply public ComplexNumber (ComplexNumber complexNumber) {
double a = realPart;
double b = imaginaryPart;
double c = complexNumber.realPart;
double d = complexNumber.imaginaryPart;
double resultRealPart = a * c - b * d;
double resultImaginaryPart = a * d + b * c;
return new ComplexNumber (resultRealPart, resultImaginaryPart);
}

/ **
* Returns a simple text representation of this complex number.
*
* @return the text representation of this complex number.
* /
@Override
public String toString () {
if (realPart == 0.0 && imaginaryPart == 0.0) {
return "0.0";
}

if (realPart == 0.0) {
return imaginaryPart + "i";
}

if (imaginaryPart == 0.0) {
return Double.toString (realPart);
}

if (imaginaryPart <0.0) {
return realPart + "-" + Math.abs (imaginaryPart) + "i";
}

return realPart + "+" + imaginaryPart + "i";
}

/ **
* Checks if the entered {@code double} value is not {@code NaN}.
*
* @param d is the value to be checked.
* @throws IllegalArgumentException in case {@code d} {@code NaN} is.
* /
private void checkNotNan (double d) {
if (Double.isNaN (d)) {
throw new IllegalArgumentException ("NaN");
}
}

/ **
* Checks if the entered {@code double} value is finite.
*
* @param d is the value to be checked.
* @throws IllegalArgumentException in case {@code d} is not finite.
* /
private void checkNotInfinite (double d) {
if (Double.isInfinite (d)) {
throw new IllegalArgumentException ("Infinite");
}
}
}
``````

`net.coderodde.math.impl.ComplexVectorAdditive`

``````package net.coderodde.math.impl;

import net.coderodde.math.Vector;

/ **
* This class implements the addition operation over complex vectors.
*
* @author Rodion "rodde" Efremov
* @version 1.6: P (May 18, 2019)
* /
vector.
vector> {

/ **
* Adds the complex vectors {@code a} and {@code b} and returns it
* Component copy of the object. Both input complex vectors are preserved
* intact.
*
* @param a the left summation operand.
* @param b the correct summation operand.
* @ Return of the sum vector.
* /
@Override
vector b) {
Complex number[] complexNumbers =
new ComplexNumber[a.getNumberOfDimensions()];

for (int i = 0; i <a.getNumberOfDimensions (); i ++) {
complex numbers[i] = a.get (i) .add (b.get (i));
}

return new vector <> (complexNumbers);
}
}
``````

`net.coderodde.math.impl.ComplexVectorDivisible`

``````package net.coderodde.math.impl;

import net.coderodde.math.Divisible;

/ **
* This class implements the division operator over complex numbers.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public final class ComplexVectorDivisible implements Divisible {

/ **
* Divides the complex {@code Divident} by the complex {@code Divisor} and
* returns the break Both complex input numbers are retained.
*
* @param divident the complex divident.
* @param divisor The complex divisor.
* @ return the break after dividing the divider by the divider.
* /
@Override
public ComplexNumber divide (Complex Number divent, ComplexNumber divisor) {
// TODO: Could do a Karatsuba multiplication here, I think.
double a = divident.getRealPart ();
double b = divent.getImaginaryPart ();
double c = divisor.getRealPart ();
double d = divisor.getImaginaryPart ();

double resultRealPart = (a * c + b * d) / (c * c + d * d);
double resultImaginaryPart = (b * c - a * d) / (c * c + d * d);

return new ComplexNumber (resultRealPart, resultImaginaryPart);
}
}
``````

`net.coderodde.math.impl.ComplexVectorInnerProduct`

``````package net.coderodde.math.impl;

import net.coderodde.math.InnerProduct;
import net.coderodde.math.Vector;

/ **
* This class implements the calculation of the inner product over complex vectors.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public senior year ComplexVectorInnerProduct
implements InnerProduct {

/ **
* Calculates the inner product of {@code a} and {@code b} and returns it to
* the caller.
*
* @param a the first operand.
* @param b the second operand.
* @ Send back indoor product.
* /
@Override
public ComplexNumber innerProductOf (Vector a, // 1 -2i
vector b) {// 1 -2i
ComplexNumber innerProduct = new ComplexNumber (0.0, 0.0);

for (int i = 0; i <a.getNumberOfDimensions (); i ++) {
ComplexNumber complexNumber1 = a.get (i);
ComplexNumber complexNumber2 = b.get (i);
ComplexNumber product = complexNumber1.multiply (complexNumber2);
}

return inner product;
}
}
``````

`net.coderodde.math.impl.ComplexVectorNegative`

``````package net.coderodde.math.impl;

import net.coderodde.math.Negative;
import net.coderodde.math.Vector;

/ **
* This class implements the negation operation on complex numbers.
*
* @author Rodino "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public senior year ComplexVectorNegative
implements Negative <Vector.
vector> {

/ **
* Negates each component in {@code element} and returns the result
* vector. The input vector is retained.
*
* @param element the element to be negated.
* @Return the item with all the negated components compared to
* Input vector.
* /
@Override
public vector negate (Vector Element) {
vector Result = new vector <> (element);

for (int i = 0; i <element.getNumberOfDimensions (); i ++) {
result.set (i, result.get (i) .negate ());
}

Return result;
}
}
``````

`net.coderodde.math.impl.ComplexVectorProductByScalar`

``````package net.coderodde.math.impl;

import net.coderodde.math.Product;
import net.coderodde.math.Vector;

/ **
* This class implements the multiplication of complex vectors with a complex scalar.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public senior class ComplexVectorProductByScalar
implements Product <ComplexNumber,
vector.
vector> {

/ **
* Multiplies the complex vector by the given complex scalar and returns it
* Result. All input objects are retained.
*
* @param scalar the scalar to be multiplied.
* @param vector The complex vector to be multiplied.
* Return the {@ code vector multiplied by {@ code scalar}.
* /
@Override
public vector multiply (ComplexNumber scalar,
vector Vector) {
vector ret = new vector <> (vector);

for (int i = 0; i <vector.getNumberOfDimensions (); i ++) {
ret.set (i, ret.get (i) .multiply (scalar));
}

return ret;
}
}
``````

`net.coderodde.math.impl.RealVectorAdditive`

``````package net.coderodde.math.impl;

import net.coderodde.math.Vector;

/ **
* This class implements an addition via {@code double} -valued vectors of one
* Euclidean space.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
vector.
vector> {

/ **
* Adds content in {@code a} and {@code b} component by component and returns
* the sum. Both input vectors are retained.
*
* @param a the first operand.
* @param b the second operand.
* @ Return of the sum of the two input operands.
* /
@Override
public vector add (Vector a, vector b) {
vector Result = new vector <> (a);

for (int i = 0; i <a.getNumberOfDimensions (); i ++) {
result.set (i, result.get (i) + b.get (i));
}

Return result;
}
}
``````

`net.coderodde.math.impl.RealVectorDivisible`

``````package net.coderodde.math.impl;

import net.coderodde.math.Divisible;

/ **
* This class implements the distribution of {@code double} values.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
implements divisibility {

/ **
* Returns the fraction of {@code divident} and {@code divisor}.
*
* @param divident the dividend value {@code double}.
* @param divisor the value of the divisor {@code double}.
* @ Return of the faction.
* /
@Override
public Double divide {double divisor, double divisor) {
Return dividend / divisor;
}
}
``````

`net.coderodde.math.impl.RealVectorInnerProduct`

``````package net.coderodde.math.impl;

import net.coderodde.math.InnerProduct;
import net.coderodde.math.Vector;

/ **
* This class is responsible for the calculation of inner products over the actual value
* Vectors.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
implements InnerProduct {

/ **
* Computes and returns the inner product of the vectors {@code a} and back
* {@code b}.
*
* @param a the left operand vector.
* @param b is the correct operand vector.
* Return the inner product of the vectors {@code a} and {@code b}.
* /
@Override
public Double innerProductOf (Vector a, vector b) {
double innerProduct = 0.0;

for (int i = 0; i <a.getNumberOfDimensions (); i ++) {
innerProduct + = a.get (i) * b.get (i);
}

return inner product;
}
}
``````

`net.coderodde.math.impl.RealVectorNegative`

``````package net.coderodde.math.impl;

import net.coderodde.math.Negative;
import net.coderodde.math.Vector;

/ **
* This class implements a negation operation on real vectors.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public final class RealVectorNegative implements Negative <Vector.
vector> {

/ **
* Negates the input vector {@code double}. The input vector is retained.
*
* @param a is the {@code double} vector to negate.
* @ back the negative of {@code a}.
* /
@Override
public vector negate (Vector on) {
vector Result = new vector <> (a);

for (int i = 0; i <result.getNumberOfDimensions (); i ++) {
result.set (i, -result.get (i));
}

Return result;
}

}
``````

`net.coderodde.math.impl.RealVectorProductByScalar`

``````package net.coderodde.math.impl;

import net.coderodde.math.Product;
import net.coderodde.math.Vector;

/ **
* This class implements the multiplication of a vector with a scalar.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public senior class RealVectorProductByScalar
implements product <Double, Vector, Vector> {

/ **
* This method multiplies the input vector {@codevektor} component by component
* the scalar {@code double} and returns the result. The input vector
* remains intact.
*
* @param scalar the scalar.
* @param vector The vector to be multiplied by the scalar.
* @ Return the input vector multiplied by the input scalar.
* /
@Override
public vector multiply (double scalar, vector Vector) {
vector x = new vector <> (vector);

for (int i = 0; i <vector.getNumberOfDimensions (); i ++) {
x.set (i, x.get (i) * scalar);
}

return x;
}
}
``````

`net.coderodde.math.GramSchmidtProcessTest`

``````package net.coderodde.math;

import net.coderodde.math.impl.RealVectorDivisible;
import net.coderodde.math.impl.RealVectorInnerProduct;
import net.coderodde.math.impl.RealVectorNegative;
import net.coderodde.math.impl.RealVectorProductByScalar;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.test;
import static org.junit.Assert. *;

public class GramSchmidtProcessTest {

private final GramSchmidtProcess process =
new GramSchmidtProcess <> (new RealVectorInnerProduct (),
new RealVectorDivisible (),
new RealVectorProductByScalar (),
new RealVectorNegative ());

@Test (expected = NullPointerException.class)
public void testThrowsNullPointerExceptionOnNullBasis () {
process.process (null);
}

@Test (expected = IllegalArgumentException.class)
public void testThrowsIllegalArgumentExceptionOnNoVectors () {
process.process ();
}

@Exam
public void testReturnsSingleVectorWhenBasisContainsOnlyOneVector () {
vector vec = new vector <> (1.0, 2.2, 3.0);
vector[]    Result = process.process (vec);
assertEquals (1, result.length);
assertEquals (vec, result[0]);
}

@Test (expected = IllegalArgumentException.class)
public emptiness
testThrowsIllegalArgumentExceptionWhenFirstVectorHasDimensionZero () {
vector v1 = new vector <> ();
vector v2 = new vector <> (1.0);
process.process (v1, v2);
}

@Test (expected = IllegalArgumentException.class)
public emptiness
testThrowsIllegalArgumentExceptionWhenAnotherVectorHasDimensionZero () {
vector v1 = new vector <> (1.0);
vector v2 = new vector <> ();
process.process (v1, v2);
}

@Test (expected = IllegalArgumentException.class)
public void testThrowsIllegalArgumentExceptionWhenDimensionalityMismatch () {
vector v1 = new vector <> (1.0);
vector v2 = new vector <> (2,0, 3,0);
process.process (v1, v2);
}

@Exam
public void testValidInput1 () {
vector v1 = new vector <> (1st, 1st, 1st);
vector v2 = new vector <> (1st, 0th, 1st);
vector v3 = new vector <> (3rd, 2nd, 3rd);
vector[]    orthogonalBase = process.process (v1, v2, v3);
assertTrue (Demo.basisIsOrthogonal (orthogonalBase, 0.001));
}
}
``````

(The whole project is here.)

Critical request

Conversion of an SQL command into Lambda or Java 8 Stream

I'm starting with Java 8 and want to turn the following SQL command into a lambda function:

``````SELECT * FROM CorrespondenceCandidate c, (SELECT entityEngine, MAX (m1)
similarityMaxima FROM CorrespondenceCandidata WHERE m1 <> 0 GROUP BY
entityOrig) r WHERE c.entityRequest = r.Request AND AND c.m1 =
r.ÄhnlichkeitMaxima
``````

I created the class `Correspondence` With `getter` and `setter`,

public correspondence

``````int code;
String name;
String entity;
String EntityDestino;
double m1;
double m2;
twice m3;
double medMax;
double that;

public int getCode () {
Return code;
}
public void setCode (int code) {
this.codigo = code;
}
public String getNome () {
return name;
}
public void setNome (String name) {
this.name = name;
}
public String getEntityOrigem () {
return entityEngine;
}
public void setEntityOrigem (String entityOrigem) {
this.sourceOrigem = SourceType;
}
public String getDataInfo () {
}
public void setEntityDestination (String entityDestination) {
EntityDestino = EntityDestino;
}
public double getM1 () {
return m1;
}
public void setM1 (double m1) {
this.m1 = m1;
}
public double getM2 () {
return m2;
}
public void setM2 (double m2) {
this.m2 = m2;
}
public double getM3 () {
return m3;
}
public void setM3 (double m3) {
this.m3 = m3;
}
public double getMedMax () {
return medMax;
}
public void setMedMax (double medMax) {
this.medMax = medMax;
}
public double getDem () {
return that;
}
public void setDem (double dem) {
this.dem = that;
}
``````

Java – Small CCG Project Review

Hello, I am creating a small CCG application similar to this Yugioh project linked below. I've written my own rules for the game in a text that I can link to when needed.

Video:

Wonderful project, right? One small difference I want to design is that the spell effects, if possible, are all one class

I feel that my project needs a code review, because after a short break I am back in programming and working on my own.

Here is a picture of my project in Eclipse Explorer:

The project is progressing well, but I would like to have a bit of input in two parts:

Language is Java.

1: Is that okay or should I only initialize content when I need to create it?

``````import javax.swing.JFrame;

public game extends JFrame {

private static final long serialVersionUID = 1L;
public static TitlePanel tp;
public static DuelSettingsAIPanel dsaip;
public static DuelAIPanel daip;
public static EditDeckPanel edp;

public game () {

// initialize content
tp = new TitlePanel (this);
dsaip = new DuelSettingsAIPanel (this);
edp = new EditDeckPanel (this);
daip = new DuelAIPanel (this);

setBounds (0,0,1024,768);
setResizable (false);
setLocationRelativeTo (null);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setContentPane (tp);
setVisible (true);
}

public static void main (String[] arguments)
{
new game();
}
}
``````

2: Why does requestFocus () cause cardToAdd not to be displayed if not called? The only other way to see it is to hover over the component while the application is running.

``````private void dealHands ()
{
HandCard cardToAdd = new HandCard (new card (0));
cardToAdd.requestFocus (); /// why is that necessary?
}
``````

Feel free to talk to me on Discord.
As a side note, I also use the Window Builder Plug-in for Eclipse.
Many Thanks!

Java – How do I convert the ASCII list to binary and vice versa? Or how could these lists be handled more efficiently?

Every contribution is very well received, thank you.

I'm trying to make a small text program that will convert to binaries and then do the same, but vice versa.

I just found this place and asked that question in search of a reply or post.

My problem is that I managed to get a little bit out of the way, so I was converted from text to binary, but I can not find a way to start the second part, which is to convert from binary to text.

In addition, I reiterate that I can probably have a lot of rookie mistakes, and I'd like to know how to use the already created lists if they have something to mention in the code or ideas to improve the code.

This is the code and I mention once again that every post is very well received. Many Thanks

``````public static void main (String[] args) throws IOException {
String path = "\ user \ Manuel \ Desktop \ Jobs \ 2 years \ object oriented programming \ file path \ try topassprogramming";
File File = new file (path);
BufferedWriter bw;

listASCII;
listBinary2;

ascii = new ArrayList <> ();
binary2 = new ArrayList <> ();

int binaries = 0;
int number, exp, digit;

tries {
if (file.exists ()) {
bw = new BufferedWriter (new FileWriter (file));
String = "Ana Graciela Montelongo Arzate", n = zero;
int x = 0;
for (int i = 0; i <letters.length (); i ++) {
x = letters.charAt (i);
n = integer.toBinaryString (x);
}
bw.write (letters + ascii + binary2);
}
otherwise {
bw = new BufferedWriter (new FileWriter (file));
String = "Ana Graciela Montelongo Arzate", n = zero;
int x = 0;
for (int i = 0; i <letters.length (); i ++) {
x = letters.charAt (i);
n = integer.toBinaryString (x);
}
bw.write (letters + ascii + binary2);
}
bw.close ();
}
catch (IOException errorDeFichero) {
System.out.println ("Problems encountered:" + errorFile.getMessage ());
}
}
``````

}

java – Appsealing: How to decompile APK with appsealing?

I have an APK file. I've tried decompiling it with jadx, but there are appsealing.dex that can not be decompiled with jadx.

How do I decompile an application that uses appealing protection?

java – Why iterative code times out the time limit for calculating the number of trailing zeros in a faculty

Both codes calculate the following number of zeros in A!.

Here is the iterative code: For large inputs, a timeout occurs

``````public int trailingZeroes (int A) {

int count = 0;

for (int i = 5; A / i> = 1; i = i * 5)
{
count + = A / i;
}
return count;
}
``````

And here's the recursive code that will be completed on time.

``````public int trailingZeroes (int A) {

return A == 0? 0: (A / 5 + TrailingZeroes (A / 5));
}
``````

Are recursive codes faster than iterative codes in all cases? e.g. Tree crossing etc.

Java – How Arraylist Create Getters and Setters?

Good morning, I create a question and answer game with the attributes: question, correct answer and the option arraylist (private ArrayList option = new ArrayList ();). I need the getter of options to print the questions and answers in my main class on the screen, but I'm not sure how to create the options getter as an arraylist. I've tried it in some ways and when I go into the main class, I can not access the getter. If anyone can give me an idea of ​​how I do it, I appreciate it.

public class questions {

``````private string query;

private ArrayList option = new ArrayList();

private string responseCorrect;

// builder method
public questions (string p, string res, string opc1, string opc2, string opc3) {
this.question = p;
this.respostaCorreta = res;
}

// GET AND SET THE QUESTION
public String getQuestion () {
Consultation;
}

public void setQuestion (String p) {
this.question = p;
}

// GET AND SET OPTIONS

// GET AND SET THE RIGHT ANSWER
public String getResponseCorrect () {
}

public void setResponseCorrect (String res) {
this.respostaCorreta = res;
}

}
``````

Java – Sudoku generator with seeds Sudoku

I created a Sudoku generator in Java. Here I am using a simple solved sudoku as seed and by transposing and mixing the rows and columns I get a new solved sudoku.
Below is the code:

``````                    // import java.util.Arrays;

import java.util.Random;

public class SudokuGenerator {
private char[][]    board = new char[9][9];
private int[] randomizeSudoku = new int[9];
private char[][]    transposedSeed = new character[][]{{& 8,, # 2 #, # 7 #, # 1 #, & 5 #, & # 39; ; 4, 39, 39, 39, 39, 39)
{# 9 #, # 6,, # 5 #, # 3 #, & 2 #, & # 39; 7,, # 1 #, # 4 #, # 8 #,}
{# 3 #, 4 4 #, # 1 #, # 6 #, # 8 #, & # 39; 9,, # 7,, # 5 #, # 2 #,}
{# 5 #, # 9,, # 3 #, & 4 #, # 6 #, & # 39; 8,, # 2 #, # 7,, # 1 #,}
{# 4 #, # 7,, # 2 #, # 5 #, & 1 #, & # 39; 3 #, # 6,, # 8 #, # 9 #,}
{# 6 #, 1 1 #, # 8 #, # 9 #, & 7 #, & # 39; 2 & # 39 ;, 4 & # 39 ;, & # 39; 4 & # 39 ;, 3 & # 39 ;, & # 39; 4 & # 39;
{# 7,, # 8 #, # 6,, # 2 #, & 3 #, & # 39; 5,, # 9,, # 1 #, & 4 #,}
{1, 5, 4, 7, 9, 6, 8, 2, 3
{# 2 #, & 3 #, # 9,, # 8 #, & 4 #, & # 39; 1,, # 5 #, # 6 #, # 7},};
private char[][]    seed = new char[9][9];
private random random = new random ();

public static void main (String[] Arguments) {
Sudoku generator s = new sudoku generator ();
int n = 2;
to transpose ();
to shuffle ();
s.seedChanger ();
while (n> 0) {
System.out.println (" n  n ------ New Board --------  n");
to transpose ();
to shuffle ();
to display ();
s.seedChanger ();
n--;
}
}

transpose private void () {
for (int i = 0; i <9; i ++) {
for (int j = 0; j <9; j ++) {
seed[j][i]    = transposed seed[i][j];
}
}
}

private void seedChanger () {
for (int i = 0; i <9; i ++) {
System.arraycopy (card[i], 0, transposed[i]0, board length);
}
}

private void randomSudokuGenerator () {
for (int i = 0; i <randomizeSudoku.length; i ++) {
randomizeSudoku[i] = 9;
}
int i = 0;
for (i <randomizeSudoku.length; ++ i) {
int r = random.nextInt (2);
for (int i1 = 0; i1 <i; ++ i1) {
int x = randomize Sudoku[i1];
if (x == r) {
if (i <3) {
r = random.nextInt (3);
} else if (i <6) {
r = random.nextInt (3) + 3;
} else if (i <9) {
r = random.nextInt (3) + 6;
}
i1 = -1;
}
}
randomizeSudoku[i] = r;
}
}

private void shuffle () {
random Sudoku generator ();
// System.out.println (Arrays.toString (randomizeSudoku));
for (int x = 0; x <9; x ++) {
blackboard[0][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[0]][x];
blackboard[1][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[1]][x];
blackboard[2][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[2]][x];
blackboard[3][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[3]][x];
blackboard[4][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[4]][x];
blackboard[5][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[5]][x];
blackboard[6][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[6]][x];
blackboard[7][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[7]][x];
blackboard[8][x]    = Seeds[randomizeSudoku[randomizeSudoku[randomizeSudoku[randomizeSudoku[8]][x];
}
for (int x = 0; x <9; x ++) {

if (randomizeSudoku[0] == 0) Swap (board, x, 1, 0);
if (randomizeSudoku[0] == 1) swap (board, x, 2, 0);
if (randomizeSudoku[0] == 0) Swap (board, x, 5, 4);
if (randomizeSudoku[0] == 1) swap (board, x, 5, 3);
if (randomizeSudoku[0] == 2) swap (board, x, 8, 6);
}
}

private exchange (char[][]    a, int commonIndex, int first, int second) {
char swap = a[commonIndex][first];
on[commonIndex][first]    = a[commonIndex][second];
blackboard[commonIndex][second]    = Swap;
}

private void display () {
int i, j;
for (i = 0; i <= 8; ++ i) {
if (i == 0) {
System.out.print (" t  t  t _______________________________________  n  t line" + (i + 1) + " t");
} else {
System.out.print (" t  t  t | --- | --- | --- || --- | --- | --- || --- | --- | - - |  n  t line "+ (i + 1) +"  t ");
}
for (j = 0; j <= 8; ++ j) {
if (j == 3) {
System.out.print ("|");
}
if (j == 6) {
System.out.print ("|");
}
if (j == 8) {
System.out.println ("|" + board[i][j]    + "|");
} else {
System.out.print ("|" + board[i][j]    + "");
}
}
if (i == 2) {
System.out.println (" t  t  t | --- | --- | --- || --- | --- | --- || --- | --- | - - | ");
}
if (i == 5) {
System.out.println (" t  t  t | --- | --- | --- || --- | --- | --- || --- | --- | - - | ");
}
if (i == 8) {
System.out.println (" t  t  t ------------------------------------- - ");
System.out.println (" tC columns 1 2 3 4 5 6 7 8 9  n  n  n");
}
}
}
}
``````

Java – Create users with different roles for each group

I have a class called Reunion (Meet), this meeting (Meet) has users, but each user can have different roles in each meeting.

``````@Entity
@Table (name = "Meet")
public class Meet implements Serializable {

@id
@GeneratedValue (Strategy = GenerationType.AUTO)
private long id;

@Column (unique = true, name = "name")
private string name;

@Enumerated (EnumType.STRING)
@Column (name = "state")
private state;

@JoinColumn (name = "id_bet", referencedColumnName = "id")
private bet bet;

@OneToMany (fetch = FetchType.EAGER) //, mappedBy = "meet"
Private set users = new HashSet <> ();
``````

Below, I show the user class:

``````public class user implements Serializable {

@id
@GeneratedValue (Strategy = GenerationType.AUTO)
private long id;

@Column (name = "name")
private string name;

@Column (unique = true, name = "email")
private string e-mail;

@Enumerated (EnumType.STRING)
@Column (name = "role")
Role role;

@Enumerated (EnumType.STRING)
@Column (name = "life")
Live life;
``````

In each meeting (meeting) there are two roles for the users, the first is attendee and the second is owner, but I get all users with role: Attendee, how do I do that so that a user can have multiple roles in the different groups ?

``````[
{
"id": 1,
"name": "string",
"email": "string",
"rol": "PARTICIPANT",
"life": "suspend"
},
{
"id": 2,
"name": "string",
"email": "string2",
"rol": "PARTICIPANT",
"life": "suspend"
}
]
``````

Java – Why does this for loop for array use array.length-1?

Hello, I am a beginner in Java, now I have arrived at Arrays. Here's a for loop to sort the number from highest to lowest. My question is why the instructor used newARRAY.length-1.

``````public static int [] whole numbers;

public static int [] sortArray (int[] Array) {
Boolean PeaceArray = true;
int temp;
int [] newARRAY = Arrays.copyOf (array, array.length);
while (PeaceArray) {
PeaceArray = false;
for (int i = 0; i <newARRAY.length-1; i ++) {
if (newARRAY[i]<newArray[i+1]) {
temp = newARRAY[i];
newArray[i] = newARRAY[i+1];
newArray[i+1] = temp;
PeaceArray = true;

}

}

}

return newARRAY;
}
``````