## Appropriate algorithm for a graph theory problem

So recently I came across a graph theory problem and I could not find a matching algorithm for the problem or rephrase it to match some existing algorithm.

The problem is quite simple: given a weighted directed graph, select edges to maximize the sum of all the weights of the selected edges. A maximum edge can point to another vertex and no vertex can be the head for more than one edge.

So far, this seems like a problem that can be solved with a matching algorithm, but there is an additional catch: a vertex can be the head of an edge only if the vertex is not a tail of the edges in the given graph, or if it is a tail for one of the selected edges. In addition to that, the graph of the selected edges must be acyclic.

A good analogy would be to imagine each vertex as a cell. I can mark all the vertices that are initially tails of some edges as cells with some object in them. Choosing a border would mean moving the object from one cell to another. This analogy seems perfect, because:

• `A vertex can be the tail of a chosen maximum edge.` (Also known as the object can be moved to another cell)
• `A vertex can be the head of a chosen maximum edge.` (Also known as a single object can be moved to a cell)
• `A vertex can be the head of an edge only if the vertex was not a tail of the edges, or if it is a tail for one of the edges chosen` (also known as the cell was initially empty or the object can be transported to another cell emptying the cell)

As good as it is, I could not find any algorithm that could be of help. Is the raw brute for edge combinations the best you can? Or can I get the edges in a more optimized way?

## Algorithm: Gram-Schmidt process in Java to calculate independent bases in linear spaces

Given a set of $$k$$ $$n$$-vectors $$x_1, dots, x_k$$, The Gram-Schmidt process calculates a basis $$y_1, dots, y_m$$ ($$m leq k$$) vectors that span the same space as $$x_1, dots, x_k$$ but they are mutually orthogonal: $$(y_i, y_j) = 0$$ for all $$i neq j$$, where the parentheses denote internal product
$$(x, y) = sum_ {i = 1} ^ n x_i y_i.$$

Below is my code:

`net.coderodde.math.Additive`

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

/ **
* This interface defines the API to add the two elements.
*
* @param  The type of the left operand.
* @param  The correct type of operand.
* @param   the type of sum.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface additive {

/ **
* This method adds {@code a} and {@code b} and returns the sum.
*
* @param to the first element.
* @param b the second element.
* @ Returns the sum of the two numbers given.
* /
public O add (I1 a, I2 b);
}
``````

`net.coderodde.math.Demo`

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

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 runs a simple demonstration for the Gram-Schmidt process.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
final class demo {

empty main public static (String[] args) {
Vector x1 = new Vector <> (1., -1., 1., -1.);
Vector x2 = new Vector <> (5., 1., 1., 1.);
Vector x3 = new Vector <> (- 3., -3., 1., -3.);

Vector[]    OrthogonalBasis1 =
new GramSchmidtProcess <> (new RealVectorInnerProduct (),
New RealVectorDivisible (),
New RealVectorProductByScalar (),
new RealVectorNegative ())
.process (x1, x2, x3);

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

System.out.println ("Orthogonal:" +
isOrthogonal (orthogonalBasis1[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[]    orthogonalBasis2 =
new GramSchmidtProcess <> (new ComplexVectorInnerProduct (),
New ComplexVectorDivisible (),
new ComplexVectorProductByScalar (),
new ComplexVectorNegative ())
.process (c1, c2);

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

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

public static  Base BooleanIsOrthogonal (Vector[]    base,
double epsilon) {
for (int i = 1; i <basis.length; i ++) {
Vector goal = base[i];

for (int j = 0; j <i; j ++) {
Vector current = base[j];

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

true returns
}

static boolean base publicIsOrthogonalComplex (
Vector[]    base, double epsilon) {
for (int i = 1; i <basis.length; i ++) {
Vector goal = base[i];

for (int j = 0; j <i; j ++) {
Vector current = base[j];

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

true returns
}

static 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;
}

static static boolean isOrthogonalComplex (Vector a,
Vector second,
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));
sum = sum.add (product);
}

returns Math.abs (sum.getRealPart ()) <Γ©psilon &&
Math.abs (sum.getImaginaryPart ()) <epsilon;
}
}
``````

`net.coderodde.math.Divisible`

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

/ **
* This interface defines the API for the division operator.
*
* @param  The type of the divider.
* @param  The type of divider.
* @param   The type of fraction.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface divisible {

/ **
* Divide {@code a} by {@code b} and return the result.
*
* @param divident the object that is divided.
* @param divider the divider.
* @ returns the result of dividing {@code divident} by {@code divider}.
* /
public division F (D1 divider, D2 divisor);
}
``````

`net.coderodde.math.GramSchmidtProcess`

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

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

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

/ **
* This object is responsible for computing the internal product of two.
* vectors
* /
private internal product Internal product;

/ **
* This object is responsible for the computer division.
* /
divisible private divisible;

/ **
* This object is responsible for computing products (multiplication).
* /
Private product <FT, VectorVector> product;

/ **
* This object is responsible for the computation of the sum.
* /

/ **
* This object is responsible for computing the negative elements.
* /
Private negative <VectorVector> negative;

/ **
* Build the object with the method to execute the Gram-Schmidt process
* on a given basis
*
* @param innerProduct the object to compute internal products.
* @param divisible the object to perform the division.
* @param product the object to perform the multiplication.
* @param additive the object to make the addition.
* @param negative the object to compute inverses.
* /
Public GramSchmidtProcess (InnerProduct Internal product,
Divisible divisible,
Product <FT, VectorVector> product,
Vector,
Negative <VectorVector> negative) {
this.innerProduct =
Objects.requireNonNull (
Internal product,
"The InnerProduct entry is null.");

this.negative = Objects.requireNonNull (negative,
"The Negative entry is null");

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

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

"The input additive is null");
}

/ **
* Perform the Gram-Schmidt process in {@code based}.
*
* @param base the basis to process.
* @ return the orthogonal base.
* /
public vector[]    process (vector... base) {
// Validate the entry base:
checkBasis (base);

// Deal with the first base element:
Vector[]    OrthogonalBasis = new vector[basis.length];
Orthogonal base[0] = (Vector) new vector (base[0]);

// The current process:
for (int i = 1; i <basis.length; i ++) {
// Copy-build & # 39; x & # 39; from & # 39; base[i]& # 39;
Vector x = new vector <> (base[i]);

// For each base element before & # 39; x & # 39 ;, do:
for (int j = 0; j <i; j ++) {
// Take the inner product of the division:
IPT innerProductDivident =
this.innerProduct.innerProductOf (x, orthogonalBasis[j]);

// Take the internal product of the divisor:
IPT innerProductDivisor =
this.innerProduct.innerProductOf (orthogonalBasis[j],
Orthogonal base[j]);

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

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

// Denies the above:
term = negative. denied (term);

// Add the above to & # 39; x & # 39; Effectively, subtract & # 39; term & # 39; of
// & # 39; x & # 39; since we have denied & # 39; term & # 39 ;:
}

Orthogonal base[i] = x;
}

// Remove duplicates and return what is left:
return removeDuplicates (orthogonalBasis);
}

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

// The check is not empty:
if (basisCandidate.length == 0) {
launch a new IllegalArgumentException ("There are no vectors given.");
}

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

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

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

yes (expected dimensions
! = basisCandidate[i].getNumberOfDimensions ()) {
// Oops. Not all the basic elements are the same
// dimensionality:
launch new IllegalArgumentException (
"Element dimension mismatch: expected" +
Expected dimensions + "but it was" +
baseCandidate[i].getNumberOfDimensions () +
"in the index" + i + ".");
}
}
}

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

`net.coderodde.math.InnerProduct`

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

/ **
* This interface defines the API for the internal product on a given vector component
* kind.
*
* @param  the left type vector.
* @param  The correct type of vector.
* @param   the type of internal value of the product.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public interface InnerProduct {

/ **
* Calculate the internal product of the two given vectors.
*
* @param to the first vector.
* @param b the second vector.
* Return the inner product
* /
public IPT innerProductOf (Vector a, vector second);
}
``````

`net.coderodde.math.Negative`

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

/ **
* This interface defines the API to calculate negative values ββof given values.
*
* @param  the type of entry.
* @param  the type of output.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
Negative public interface {

/ **
* 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 deny.
* @ returns the negative of {@code element}.
* /
public OR negate (item I);
}
``````

`net.coderodde.math.Product`

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

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

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

`net.coderodde.math.Vector`

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

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

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

/ **
* The real contents of the vector.
* /
private end e[] components;

/ **
* Build the vector from the given data.
*
* @param components vector data.
* /
Public vector (E ... components) {
Objects.requireNonNull (components, "The input vector is null.");
this.components = Arrays.copyOf (components, components.length);
}

/ **
* Copy-build this vector.
*
* @param vector vector to copy.
* /
public vector (vector vector) {
this.components = Arrays.copyOf (vector.components,
vector.components.length);
}

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

/ **
* Sets the value of the {@code index} th vector component to the given
* value.
*
* @param indexes the index of the target vector component.
* @param value the value to establish.
* /
public vacuum set (int index, E value) {
components[index] = value;
}

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

@Cancel
public string to the string () {
StringBuilder stringBuilder = new StringBuilder ("<");
String separator = "";

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

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

@Cancel
Public booleans are equal (object o) {
yes (or == null) {
false return;
}

yes (or == this) {
true returns
}

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

Vector other = (Vector) or;
return Arrays.equals (components, other.ponents);
}
}
``````

`net.coderodde.math.impl.ComplexNumber`

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

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

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

/ **
* The imaginary number.
* /
Double end private imaginaryPart;

/ **
* Build a new complex number.
*
* @param realPart the real part of the new construction 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.
* /
double public getRealPart () {
returns 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 that is equal to the sum of this complex
* number and the {@code other} complex number.
*
* @param another the complex number to add.
* @ returns the sum of this and {@code another} complex number.
* /
public ComplexNumber add (ComplexNumber other) {
return new ComplexNumber (realPart + other.realPart,
imaginaryPart + other.imaginaryPart);
}

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

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

/ **
* Returns a simple textual representation of this complex number.
*
* @ Return the textual representation of this complex number.
* /
@Cancel
public string to the string () {
if (realPart == 0.0 && imaginaryPart == 0.0) {
returns "0.0";
}

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

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

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

returns realPart + "+" + imaginaryPart + "i";
}

/ **
* Check that the input value {@code double} is not {@code NaN}.
*
* @param d the value to check.
* @throws IllegalArgumentException in case {@code d} is {@code NaN}.
* /
private null checkNotNan (double d) {
yes (Double.isNaN (d)) {
launch new IllegalArgumentException ("NaN");
}
}

/ **
* Check that the input value {@code double} is finite.
*
* @param d the value to check.
* @throws IllegalArgumentException in case {@code d} is not finite.
* /
private null checkNotInfinite (double d) {
yes (Double.isInfinite (d)) {
launch a new IllegalArgumentException ("Infinite");
}
}
}
``````

`net.coderodde.math.impl.ComplexVectorAdditive`

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

import net.coderodde.math.Vector;

/ **
* This class implements the addition operation on complex vectors.
*
* @autor Rodion "rodde" Efremov
* @version 1.6: P (May 18, 2019)
* /
public final class ComplexVectorAdditive
Vector,
Vector> {

/ **
* Add the complex vectors {@code a} and {@code b} and return the
* Copy by component of the object. Both complex input vectors remain
* intact
*
* @param a left summary operand.
* @param b the correct sum operand.
* @ Return the vector sum.
* /
@Cancel
public vector add (Vector a,
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));
}

returns new Vector <> (complexNumbers);
}
}
``````

`net.coderodde.math.impl.ComplexVectorDivisible`

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

import net.coderodde.math.Divisible;

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

/ **
* Divide the complex {@code divident} by the complex {@code divider} and
* returns the fraction. Both the complex entry numbers remain intact.
*
* @param divide the complex divider.
* @param divisor the complex divider.
* @rescribe the fraction after dividing the divider by the divisor.
* /
@Cancel
Public number division of ComplexNumber (ComplexNumber divident, ComplexNumber divisor) {
// ALL: We could do the Karatsuba multiplication here, I suppose.
double a = divident.getRealPart ();
double b = divident.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);

returns the new ComplexNumber (resultRealPart, resultImaginaryPart);
}
}
``````

`net.coderodde.math.impl.ComplexVectorInnerProduct`

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

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

/ **
* This class implements the computation of the internal product on complex vectors.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public final class ComplexVectorInnerProduct
implements InnerProduct {

/ **
* Calculate the internal product of {@code a} and {@code b} and return it to
* caller
*
* @param is the first operand.
* @param b the second operand.
* @ Return the inner product.
* /
@Cancel
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);
innerProduct = innerProduct.add (product);
}

return the internal product;
}
}
``````

`net.coderodde.math.impl.ComplexVectorNegative`

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

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

/ **
* This class implements the denial operation on complex numbers.
*
* @autor Rodino "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public final class ComplexVectorNegative
implements Negative <Vector,
Vector> {

/ **
* Denies all components in {@code element} and returns the result
* vector The input vector remains intact.
*
* @param element the element to deny.
* @ Return the item with all the components denied compared to the
* Entrance vector.
* /
@Cancel
public vector deny (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`

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

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

/ **
* This class implements the multiplication of complex vectors by a complex scalar.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public final class ComplexVectorProductByScalar
implements the product <ComplexNumber,
Vector,
Vector> {

/ **
* Multiply the complex vector by the given complex scalar and return the
* result All the input objects remain intact.
*
* @param scale the scalar to multiply by.
* @param vector the complex vector to multiply.
* @ returns the {@code vector} multiplied by {@code scalar}.
* /
@Cancel
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));
}

back ret
}
}
``````

`net.coderodde.math.impl.RealVectorAdditive`

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

import net.coderodde.math.Vector;

/ **
* This class implements the addition over {@code double} -valued vectors of a
* Euclidean space.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public final class RealVectorAdditive implements Additive <Vector,
Vector,
Vector> {

/ **
* Adds components in terms of content in {@code a} and {@code b} and returns
* the sum. Both input vectors remain intact.
*
* @param is the first operand.
* @param b the second operand.
* @ Returns the sum of the two input operands.
* /
@Cancel
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`

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

import net.coderodde.math.Divisible;

/ **
* This class implements the division of {@code double} values.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public final class RealVectorDivisible
implements divisible {

/ **
* Returns the fraction of {@code divident} and {@code divider}.
*
* @param divides the split value {@code double}.
* @param divisor divider {@code double} value.
* Return the fraction
* /
@Cancel
Double public division (double divided, double divisor) {
divider / divider return;
}
}
``````

`net.coderodde.math.impl.RealVectorInnerProduct`

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

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

/ **
* This class is responsible for computing internal products on real values.
* vectors
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 17, 2019)
* /
public final class RealVectorInnerProduct
implements InnerProduct {

/ **
* Calculates and returns the internal product of vectors {@code a} and
* {@code b}.
*
* @param to the left operand vector.
* @param b the vector operating right.
* @ returns the internal product of vectors {@code a} and {@code b}.
* /
@Cancel
public Double innerProductOf (Vector a, vector b) {
Internal product double = 0.0;

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

return the internal product;
}
}
``````

`net.coderodde.math.impl.RealVectorNegative`

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

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

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

/ **
* Denies the entry {@code double} vector. The input vector remains intact.
*
* @param a vector {@code double} to deny.
* @ returns the negative of {@code a}.
* /
@Cancel
public vector deny (Vector a) {
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`

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

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

/ **
* This class implements the operation of multiplying a vector by a scalar.
*
* @autor Rodion "rodde" Efremov
* @version 1.6 (May 18, 2019)
* /
public final class RealVectorProductByScalar
Implements Product <Double, VectorVector> {

/ **
* This method multiplies the input vector {@code vector} by components
* the {@code double} scale and returns the result. The entry vector
* remains intact.
*
* @param climb the scalar.
* @param vector the vector to multiply by the scalar.
* @rotating the input vector multiplied by the input scalar.
* /
@Cancel
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);
}

returns x;
}
}
``````

`net.coderodde.math.GramSchmidtProcessTest`

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

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 end 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 ();
}

@Test
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);
}

@Test
public void testValidInput1 () {
Vector v1 = new Vector <> (1., 1., 1.);
Vector v2 = new Vector <> (1., 0., 1.);
Vector v3 = new Vector <> (3., 2., 3.);
Vector[]    orthogonalBasis = process.process (v1, v2, v3);
assertTrue (Demo.basisIsOrthogonal (orthogonalBasis, 0.001));
}
}
``````

(The complete project is here.)

Critical request

As always, please, tell me anything you can think of!

## algorithms: if the algorithm solves the NP problem, why can f (n) say that R belongs to TIME (f (n))?

This is my problem:

Suppose that for the problem R belongs to NP, the solution verification algorithm M (x, y) runs at time O (n ^ 3) and uses additional information y, which is long β€5 log n bits. For what f (n) can we affirm that R belongs to TIME (f (n))?

I have no idea how I can know what should be f (n) that R belongs to TIME (f (n)). All suggestions are very welcome!

## c # – Implement parallel processing in recursive algorithm

``````                static main vacuum (chain[] args)
{
List p = new list {1, 2, 3, 4};
Console.WriteLine (F (4, 4, p));
}

public static int F (int k, int n, List P)
{
List maxList = new list();
int ats = 0;

if (n == 0) {return 0; }
yes no (k == 1)
{
ats = 0;

for (int i = 0; i <n; i ++)
{
ats + = p[i];
}
back ats
}
plus
{
for (int i = 0; i <n; i ++)
{
ats = 0;
for (int j = i; j < n; j++)
{
ats += p[j];
}
int funkcija = F(k - 1, n - 1, p);
if (ats > funkcija)
{
}
plus
{
}
}
}
ats = maxList.Min ();
back ats
}
``````

I need to change the previous algorithm to be a parallel processing. However, I can not figure out how, because when I try to change it it does not work anymore. I think it does not work because the recursions that occur in different nuclei do not give each other information.

## Algorithm to change the order of the tree.

I'm looking for an algorithm name to change the order of the levels of a tree. I have done something that works but there is a lot of code and the o (n) is very bad.

Here is an example, let's say there are 3 levels. Each level represents something in a hierarchy (project> budget> fiscal year)

project = {a}
budget = {b, c}
fiscal year = {d, e}

``````            root
|
a
/
BC
/  /
d e d e
``````

I would like to build a tree with the level in a different order.

fiscal year> project> budget

``````            root
/
of
| |
a a a
/  /
b c b c
``````

budget> fiscal year> project

``````            root
/
BC
/  /
d e d e
| | | |
a a a a
``````

The initial tree can be more complicated. Each node can have more than 2 children.

``````                root
/
a b - Projects {a, b}
/  /
c d c e - Budgets {c, d, e}
| | /  |
f g f g g - Exercise with data {f, g}
``````

## pseudocode: is it a good idea to teach algorithm courses using pseudocode?

I am a young teacher who teaches a course in data structures for the first time. I'm teaching at an engineering school that provides an academic degree, but the goal is to prepare future computer programmers, not academics.

Before the beginning of the semester, I decided to present the algorithms as java code, instead of pseudocode. I felt that this would make the presentation more accurate and show the students how to put these algorithms into practice.

My experience has been mixed. It seems that the problem is that now the students think that the different algorithms are The java code. They complain that, for example, I can not expect them to know the counting classification algorithm, because how can they be expected to learn the memory code? So I'm beginning to understand the wisdom of using pseudocode.

My question, addressed to other teachers, is: What has been your experience using pseudocode compared to the use of code?

And, more generally, it would be great if someone told me some good resources to teaching Computer's science. I feel like I'm reinventing the wheel here.

## Algorithm – User leveling system

I've already asked this before, but I just want to code this again with a new leveling format. What I want to do is for the user to gain experience and once he has upgraded, his previous experience will be added to his current experience.

So, to put it in a Scenario is as follows:
User1 is at a level 1 with an exp_needed of 1000 to reach level 2. He got an exp of 1000, so he is now at level 2 with a current_exp of 1000 and a required exp of 1,400. Or if User1 obtained an exp of 1,100, he is at level 2 with a current value of 1,100 and 1,400 exp is needed. And so on, depending on the algorithm. But I get a result of -900 / 1,400 if the user gains 1,100 exp.

Here is the code below:

``````while (\$ user-> curr_exp> = \$ user-> exp_needed) {
\$ user-> curr_exp - = (\$ user-> exp_needed) + \$ user-> prev_exp;
\$ user-> prev_exp = \$ user-> exp_needed;
yes (\$ user-> level <= 19){
\$user->exp_needed = \$ user-> prev_exp * 1.4;
}
elseif (\$ user-> level> = 20 && \$ user-> level <= 39){
\$user->exp_needed = \$ user-> prev_exp * 1.1;
}
elseif (\$ user-> level> = 40 && \$ user-> level <= 59){
\$user->exp_needed = \$ user-> prev_exp * 1.05;
}
elseif (\$ user-> level> = 60 && \$ user-> level <= 79){
\$user->exp_needed = \$ user-> prev_exp * 1.04;
}
elseif (\$ user-> level> = 80 && \$ user-> level <= 99){
\$user->exp_needed = \$ user-> prev_exp * 1.03;
}
elseif (\$ user-> level == 100) {
\$ user-> exp_needed = \$ user-> exp_needed * 0;
}
\$ user-> level + = 1;
\$ user-> save ();
}
``````

Any idea how to deal with this? Thank you.

## Algorithm: preperiodic, periodic or aperiodic binary chain

This is the extension of the rep-string task of the Rosette code. I do not just want to check if the input string is the shortest periodic string (repeat string) or not, but also check if it is preperiodic.

Newspaper means that a part must occur two or more times.

Entry it is a binary string (only 1 and 0 characters). It can be, for example, the binary expansion of the fraction.

Exit is a formatted binary string: preperiod (period)

Examples:

``````10101010 = (10) // newspaper
10010101010 = 100 (10) // preperiodic
11111111110 // aperiodic
``````

Below is my C code. I use a simple / naive string search algorithm, and the code works fine.

``````#include
#include

// string array for tests
char * strs[] = {
// aperiodic
"11111111110", // aperiodic
"011111111110",
"1100010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", // https://en.wikipedia.org/wiki/Liouville_number
"11000100000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000", // https://en.wikipedia.org/wiki/Liouville_number + 0
"101", // aperiodic because only one repetition and a half, possibly periodic if the string is longer
// Newspaper
"0100100", // (010) preperiod = 0 period = 3, truncated
"00100100100100100100100100100100100100100100100100100100100100100100100100100", // (001) preperiod = 0 period = 3 truncated
"1001110011", // = (10011) preperiod = 0 period = 5
"1110111011", // = (1110) preperiod = 0 period = 4
"0010010010", / * 4 x 001 and truncated, the last character can be from 001 * /
"001001001", / * 4 x 001 * /
"1111111111", // (1)
"11", // (1) newspaper
"00", // (0) newspaper
// preperiodic
"0100101101",
"00100100101", / * 4 x 001 but the last 2 characters are NOT of 001 * /
"100100100101", / * * /
"01111111111", // 0 (1) preperiodic
"0010101010101010", // preperiodic = 0 (01) = 1/6
"0100101010101010" // preperiodic = 010 (01) = 7/24
};

//
// strstr: returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
// size_t is an unsigned integer type
// look for the shortest substring !!!!!
// GivePeriod = repstr_shortest
// https://rosettacode.org/wiki/Rep-string#C
int GivePeriod (char * str)
{
if (! str) returns 0; // if the entry is empty

size_t sl = 1;
size_t sl_max = strlen (str) / 2 + 1; // more than one repetition of periodic parts

while (sl <sl_max) {
if (strstr (str, str + sl) == str) // How does it work? Check the entire string str.
back sl
++ sl;
}

returns 0;
}

int FormatString (char * str) {
int p; // offset or preperiod (if the period is found)
int pMax = strlen (str); // length without null character

period of int = 0;
int preperiod = 0;

char * substr;

for (p = 0; p < pMax; ++p ){

substr = str+p;
period = GivePeriod( substr);

if (period > 0) {
preperiod = p;
// printf ("substring =  t% * s  t from position =% d has preperiod =% d  tperiod =% d  n", pMax, substr, p, preperiod, period)); // Pring part of the string from the p position to the end (without the last null character)
printf ("% s =%. * s (%. * s) preperiod =% d  tperiod =% d  n", str, p, str, period, str + p, preperiod, period));
return period
}
// else printf ("substring =  t% * s  t from position =% d  t  n", pMax, substr, p); // Pring part of the string from the p position to the end (without the last null character)
}
printf ("% s is aperiodic  n", str);
returns 0;

}

int main () {
int iMax = sizeof (strs) / sizeof (strs[0]); // number of test values

int i; // test number = index of the matrix

for (i = 0; i <iMax; ++ i) // check all test values
FormatString (strs[i]);

returns 0;

}
``````

Compile :

``````gcc p.c -Wall
``````

run:

``````./a.out
``````

My exit is:

``````11111111110 is aperiodic
011111111110 is aperiodic
1100010000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000001 is aperiodic
110001000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000 is aperiodic
101 is aperiodic
0100100 = (010) preperiod = 0 period = 3
00100100100100100100100100100100100100100100100100100100100100100100100 = (001) preperiod = 0 period = 3
1001110011 = (10011) preperiod = 0 period = 5
1110111011 = (1110) preperiod = 0 period = 4
0010010010 = (001) preperiod = 0 period = 3
001001001 = (001) preperiod = 0 period = 3
1111111111 = (1) preperiod = 0 period = 1
11 = (1) preperiod = 0 period = 1
00 = (0) preperiod = 0 period = 1
0100101101 = 0100 (101) preperiod = 4 period = 3
00100100101 = 0010010 (01) preperiod = 7 period = 2
100100100101 = 10010010 (01) preperiod = 8 period = 2
01111111111 = 0 (1) preperiod = 1 period = 1
00101010101010101 = 0 (01) preperiod = 1 period = 2
0100101010101010 = 010 (01) preperiod = 3 period = 2
``````

Questions:

1. I can do better?
2. Can you give examples of strings for which my program fails?
3. Does this code follow the best common practices?

## JAVA FILA How to implement this algorithm?

I am studying data structure, and one of the challenges is the following:
Create an algorithm that will paint a heart in the form of data in a matrix.

tail pack;
public class Fila {
private int vet[];
private int start, end, amount;

``````            Public Row (int size)
{
vet = new int[tamanho];
start = end = amount = 0;
}

public void in queue (int x)
{
vet[fim] = x;
++ order;
count ++;
if (final == vet.length)
end = 0;
}

public int parade ()
{
int int = vet[inicio];
starting ++;
if (start == vet.length)
start = 0;
return resp.
}

public boolean empty ()
{
(amount == 0)
return true;
other
return false;
}

public boolean full ()
{
if (quantity == vet.length)
return true;
other
return false;
}
``````

}

tail pack;
public class FilaTest {

``````public static void main (String args[])
{
int mat[][]= {{{}}
0,0,1,1,1,1,0,0,1,1,1,1,0,0 {},
0.1,0,0,0,0,1,1,0,0,0,0,1,0 {},
1,0,0,0,0,0,0,0,0,0,0,0,0,0,1 {},
1,0,0,0,0,0,0,0,0,0,0,0,0,0,1 {},
0.1,0,0,0,0,0,0,0,0,0,0,0,1,0 {},
0,0,1,0,0,0,0,0,0,0,0,0,1,0,0 {},
0,0,0,1,0,0,0,0,0,0,0,1,0,0,0 {},
0,0,0,0,1,0,0,0,0,1,1,0,0,0,0 {},
0,0,0,0,0,1,0,0,1,0,0,0,0,0 {},
0,0,0,0,0,0,1,1,0,0,0,0,0,0 {},
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 {}};

show Matrix (mat);
int x = 1, y = 2; // painting start point
System.out.println ("Initial coordinates: x =" + x + ", y =" + y + " n  n");
Row f = new Row (1000);
f.file (x);
f.find (y);
while (! f.vazia ())
{
f.desenfileirar x = ();
f.desenfileirar y = ();
yes (mat[x][y]    == 0) // can you paint?
{
mat[x][y]    = 2; // painted
((x + 1) <mat.length && mat.[x+1][y]    == 0) // below
{
f.file (x + 1);
f.enfilerar (and ++);
}
}

yes (mat[x][y]    == 0) // can you paint?
{
mat[x][y]    = 2; // painted
if ((x-1) <mat.length && mat[x-1][y]    == 0) // below
{
f.enfilerar (x-1);
f.find (y);
}
}

yes (mat[x][y]    == 0) // can you paint?
{
mat[x][y]    = 2; // painted
if ((y + 1) <mat.length && mat.[x][y+1]    == 0) // below
{
f.file (x);
f.file (y + 1);
}
}

yes (mat[x][y]    == 0) // can you paint?
{
mat[x][y]    = 2; // painted
if ((y-1) <mat.length && mat[x][y-1]    == 0) // below
{
f.file (x);
f.enfilerar (y-1);
}
}
}
show Matrix (mat);
}

private static void show Matrix (int[][]    mat.](int i = 0; i <mat.length; i ++) {}
(int j = 0; j <mat.[0].length; j ++)
System.out.print (mat[i][j]    + "");
System.out.println ();
}

}
``````

}

I have two classes, one that fills and parades, and one that manipulates the data. In the current code, the representation comes out like this:
The intention is to paint by inserting a number 2, where it has the 0. and 1 is the edge, the limit where it should be painted to form the drawing

## Time complexity: programming algorithm to minimize the number of late jobs

There are jobs (non-recurring) where each job has a time of arrival aπ and a cost ππ. All jobs share a limit duration. re (the deadline for each job is ai + d). The problem is to find a programming time (not preventive) π‘π for each job in a single processor / machine, so that the total number of lost deadlines is minimized (or maximize the number of jobs in real time).

Therefore, even in cases where all the deadlines can not be met, we want to find out the calendar that meets the maximum number of deadlines. Does this problem have a polynomial solution? I tried a dynamic programming approach, but I really can not identify the subproblems.

For example, given this set of works (where each work is described by (ai, ci)): [(0, 50), (5, 20), (25, 40)] where d = 60, the best we can do is meet 3/4 deadlines with a program like this: [(5,20), (25, 40), (0, 50)].