JAVA-12097: renamed algorithms-module to algorithms-modules
This commit is contained in:
14
algorithms-modules/algorithms-miscellaneous-4/README.md
Normal file
14
algorithms-modules/algorithms-miscellaneous-4/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
## Algorithms - Miscellaneous
|
||||
|
||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](https://github.com/eugenp/tutorials/blob/algorithms-sorting) and [genetic algorithms](https://github.com/eugenp/tutorials/blob/algorithms-genetic), have their own dedicated modules.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)
|
||||
30
algorithms-modules/algorithms-miscellaneous-4/pom.xml
Normal file
30
algorithms-modules/algorithms-miscellaneous-4/pom.xml
Normal file
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>algorithms-miscellaneous-4</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-4</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.algorithms.middleelementlookup;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Optional;
|
||||
|
||||
public class MiddleElementLookup {
|
||||
|
||||
public static Optional<String> findMiddleElementLinkedList(LinkedList<String> linkedList) {
|
||||
if (linkedList == null || linkedList.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2));
|
||||
}
|
||||
|
||||
public static Optional<String> findMiddleElementFromHead(Node head) {
|
||||
if (head == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// calculate the size of the list
|
||||
Node current = head;
|
||||
int size = 1;
|
||||
while (current.hasNext()) {
|
||||
current = current.next();
|
||||
size++;
|
||||
}
|
||||
|
||||
// iterate till the middle element
|
||||
current = head;
|
||||
for (int i = 0; i < (size - 1) / 2; i++) {
|
||||
current = current.next();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(current.data());
|
||||
}
|
||||
|
||||
public static Optional<String> findMiddleElementFromHead1PassRecursively(Node head) {
|
||||
if (head == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
MiddleAuxRecursion middleAux = new MiddleAuxRecursion();
|
||||
findMiddleRecursively(head, middleAux);
|
||||
return Optional.ofNullable(middleAux.middle.data());
|
||||
}
|
||||
|
||||
private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) {
|
||||
if (node == null) {
|
||||
// reached the end
|
||||
middleAux.length = middleAux.length / 2;
|
||||
return;
|
||||
}
|
||||
middleAux.length++;
|
||||
findMiddleRecursively(node.next(), middleAux);
|
||||
|
||||
if (middleAux.length == 0) {
|
||||
// found the middle
|
||||
middleAux.middle = node;
|
||||
}
|
||||
|
||||
middleAux.length--;
|
||||
}
|
||||
|
||||
public static Optional<String> findMiddleElementFromHead1PassIteratively(Node head) {
|
||||
if (head == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Node slowPointer = head;
|
||||
Node fastPointer = head;
|
||||
|
||||
while (fastPointer.hasNext() && fastPointer.next()
|
||||
.hasNext()) {
|
||||
fastPointer = fastPointer.next()
|
||||
.next();
|
||||
slowPointer = slowPointer.next();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(slowPointer.data());
|
||||
}
|
||||
|
||||
private static class MiddleAuxRecursion {
|
||||
Node middle;
|
||||
int length = 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.middleelementlookup;
|
||||
|
||||
public class Node {
|
||||
private Node next;
|
||||
private String data;
|
||||
|
||||
public Node(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String data() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return next != null;
|
||||
}
|
||||
|
||||
public Node next() {
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setNext(Node next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
/**
|
||||
* Constants used by the Multi-swarm optimization algorithms.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Constants {
|
||||
|
||||
/**
|
||||
* The inertia factor encourages a particle to continue moving in its
|
||||
* current direction.
|
||||
*/
|
||||
public static final double INERTIA_FACTOR = 0.729;
|
||||
|
||||
/**
|
||||
* The cognitive weight encourages a particle to move toward its historical
|
||||
* best-known position.
|
||||
*/
|
||||
public static final double COGNITIVE_WEIGHT = 1.49445;
|
||||
|
||||
/**
|
||||
* The social weight encourages a particle to move toward the best-known
|
||||
* position found by any of the particle’s swarm-mates.
|
||||
*/
|
||||
public static final double SOCIAL_WEIGHT = 1.49445;
|
||||
|
||||
/**
|
||||
* The global weight encourages a particle to move toward the best-known
|
||||
* position found by any particle in any swarm.
|
||||
*/
|
||||
public static final double GLOBAL_WEIGHT = 0.3645;
|
||||
|
||||
/**
|
||||
* Upper bound for the random generation. We use it to reduce the
|
||||
* computation time since we can rawly estimate it.
|
||||
*/
|
||||
public static final int PARTICLE_UPPER_BOUND = 10000000;
|
||||
|
||||
/**
|
||||
* Private constructor for utility class.
|
||||
*/
|
||||
private Constants() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
/**
|
||||
* Interface for a fitness function, used to decouple the main algorithm logic
|
||||
* from the specific problem solution.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public interface FitnessFunction {
|
||||
|
||||
/**
|
||||
* Returns the fitness of a particle given its position.
|
||||
*
|
||||
* @param particlePosition
|
||||
* the position of the particle
|
||||
* @return the fitness of the particle
|
||||
*/
|
||||
public double getFitness(long[] particlePosition);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Represents a collection of {@link Swarm}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Multiswarm {
|
||||
|
||||
/**
|
||||
* The swarms managed by this multiswarm.
|
||||
*/
|
||||
private Swarm[] swarms;
|
||||
|
||||
/**
|
||||
* The best position found within all the {@link #swarms}.
|
||||
*/
|
||||
private long[] bestPosition;
|
||||
|
||||
/**
|
||||
* The best fitness score found within all the {@link #swarms}.
|
||||
*/
|
||||
private double bestFitness = Double.NEGATIVE_INFINITY;
|
||||
|
||||
/**
|
||||
* A random generator.
|
||||
*/
|
||||
private Random random = new Random();
|
||||
|
||||
/**
|
||||
* The fitness function used to determine how good is a particle.
|
||||
*/
|
||||
private FitnessFunction fitnessFunction;
|
||||
|
||||
/**
|
||||
* Instantiates a new Multiswarm.
|
||||
*
|
||||
* @param numSwarms
|
||||
* the number of {@link #swarms}
|
||||
* @param particlesPerSwarm
|
||||
* the number of particle for each {@link #swarms}
|
||||
* @param fitnessFunction
|
||||
* the {@link #fitnessFunction}
|
||||
*/
|
||||
public Multiswarm(int numSwarms, int particlesPerSwarm, FitnessFunction fitnessFunction) {
|
||||
this.fitnessFunction = fitnessFunction;
|
||||
this.swarms = new Swarm[numSwarms];
|
||||
for (int i = 0; i < numSwarms; i++) {
|
||||
swarms[i] = new Swarm(particlesPerSwarm);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main loop of the algorithm. Iterates all particles of all
|
||||
* {@link #swarms}. For each particle, computes the new fitness and checks
|
||||
* if a new best position has been found among itself, the swarm and all the
|
||||
* swarms and finally updates the particle position and speed.
|
||||
*/
|
||||
public void mainLoop() {
|
||||
for (Swarm swarm : swarms) {
|
||||
for (Particle particle : swarm.getParticles()) {
|
||||
|
||||
long[] particleOldPosition = particle.getPosition().clone();
|
||||
|
||||
// Calculate the particle fitness.
|
||||
particle.setFitness(fitnessFunction.getFitness(particleOldPosition));
|
||||
|
||||
// Check if a new best position has been found for the particle
|
||||
// itself, within the swarm and the multiswarm.
|
||||
if (particle.getFitness() > particle.getBestFitness()) {
|
||||
particle.setBestFitness(particle.getFitness());
|
||||
particle.setBestPosition(particleOldPosition);
|
||||
|
||||
if (particle.getFitness() > swarm.getBestFitness()) {
|
||||
swarm.setBestFitness(particle.getFitness());
|
||||
swarm.setBestPosition(particleOldPosition);
|
||||
|
||||
if (swarm.getBestFitness() > bestFitness) {
|
||||
bestFitness = swarm.getBestFitness();
|
||||
bestPosition = swarm.getBestPosition().clone();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Updates the particle position by adding the speed to the
|
||||
// actual position.
|
||||
long[] position = particle.getPosition();
|
||||
long[] speed = particle.getSpeed();
|
||||
|
||||
position[0] += speed[0];
|
||||
position[1] += speed[1];
|
||||
|
||||
// Updates the particle speed.
|
||||
speed[0] = getNewParticleSpeedForIndex(particle, swarm, 0);
|
||||
speed[1] = getNewParticleSpeedForIndex(particle, swarm, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a new speed for a given particle of a given swarm on a given
|
||||
* axis. The new speed is computed using the formula:
|
||||
*
|
||||
* <pre>
|
||||
* ({@link Constants#INERTIA_FACTOR} * {@link Particle#getSpeed()}) +
|
||||
* (({@link Constants#COGNITIVE_WEIGHT} * random(0,1)) * ({@link Particle#getBestPosition()} - {@link Particle#getPosition()})) +
|
||||
* (({@link Constants#SOCIAL_WEIGHT} * random(0,1)) * ({@link Swarm#getBestPosition()} - {@link Particle#getPosition()})) +
|
||||
* (({@link Constants#GLOBAL_WEIGHT} * random(0,1)) * ({@link #bestPosition} - {@link Particle#getPosition()}))
|
||||
* </pre>
|
||||
*
|
||||
* @param particle
|
||||
* the particle whose new speed needs to be computed
|
||||
* @param swarm
|
||||
* the swarm which contains the particle
|
||||
* @param index
|
||||
* the index of the particle axis whose speeds needs to be
|
||||
* computed
|
||||
* @return the new speed of the particle passed on the given axis
|
||||
*/
|
||||
private int getNewParticleSpeedForIndex(Particle particle, Swarm swarm, int index) {
|
||||
return (int) ((Constants.INERTIA_FACTOR * particle.getSpeed()[index])
|
||||
+ (randomizePercentage(Constants.COGNITIVE_WEIGHT)
|
||||
* (particle.getBestPosition()[index] - particle.getPosition()[index]))
|
||||
+ (randomizePercentage(Constants.SOCIAL_WEIGHT)
|
||||
* (swarm.getBestPosition()[index] - particle.getPosition()[index]))
|
||||
+ (randomizePercentage(Constants.GLOBAL_WEIGHT)
|
||||
* (bestPosition[index] - particle.getPosition()[index])));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random number between 0 and the value passed as argument.
|
||||
*
|
||||
* @param value
|
||||
* the value to randomize
|
||||
* @return a random value between 0 and the one passed as argument
|
||||
*/
|
||||
private double randomizePercentage(double value) {
|
||||
return random.nextDouble() * value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #bestPosition}.
|
||||
*
|
||||
* @return the {@link #bestPosition}
|
||||
*/
|
||||
public long[] getBestPosition() {
|
||||
return bestPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #bestFitness}.
|
||||
*
|
||||
* @return the {@link #bestFitness}
|
||||
*/
|
||||
public double getBestFitness() {
|
||||
return bestFitness;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(bestFitness);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
result = prime * result + Arrays.hashCode(bestPosition);
|
||||
result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode());
|
||||
result = prime * result + ((random == null) ? 0 : random.hashCode());
|
||||
result = prime * result + Arrays.hashCode(swarms);
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Multiswarm other = (Multiswarm) obj;
|
||||
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
|
||||
return false;
|
||||
if (!Arrays.equals(bestPosition, other.bestPosition))
|
||||
return false;
|
||||
if (fitnessFunction == null) {
|
||||
if (other.fitnessFunction != null)
|
||||
return false;
|
||||
} else if (!fitnessFunction.equals(other.fitnessFunction))
|
||||
return false;
|
||||
if (random == null) {
|
||||
if (other.random != null)
|
||||
return false;
|
||||
} else if (!random.equals(other.random))
|
||||
return false;
|
||||
if (!Arrays.equals(swarms, other.swarms))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition)
|
||||
+ ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Represents a particle, the basic component of a {@link Swarm}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Particle {
|
||||
|
||||
/**
|
||||
* The current position of this particle.
|
||||
*/
|
||||
private long[] position;
|
||||
|
||||
/**
|
||||
* The speed of this particle.
|
||||
*/
|
||||
private long[] speed;
|
||||
|
||||
/**
|
||||
* The fitness of this particle for the current position.
|
||||
*/
|
||||
private double fitness;
|
||||
|
||||
/**
|
||||
* The best position found by this particle.
|
||||
*/
|
||||
private long[] bestPosition;
|
||||
|
||||
/**
|
||||
* The best fitness found by this particle.
|
||||
*/
|
||||
private double bestFitness = Double.NEGATIVE_INFINITY;
|
||||
|
||||
/**
|
||||
* Instantiates a new Particle.
|
||||
*
|
||||
* @param initialPosition
|
||||
* the initial {@link #position}
|
||||
* @param initialSpeed
|
||||
* the initial {@link #speed}
|
||||
*/
|
||||
public Particle(long[] initialPosition, long[] initialSpeed) {
|
||||
this.position = initialPosition;
|
||||
this.speed = initialSpeed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #position}.
|
||||
*
|
||||
* @return the {@link #position}
|
||||
*/
|
||||
public long[] getPosition() {
|
||||
return position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #speed}.
|
||||
*
|
||||
* @return the {@link #speed}
|
||||
*/
|
||||
public long[] getSpeed() {
|
||||
return speed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #fitness}.
|
||||
*
|
||||
* @return the {@link #fitness}
|
||||
*/
|
||||
public double getFitness() {
|
||||
return fitness;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #bestPosition}.
|
||||
*
|
||||
* @return the {@link #bestPosition}
|
||||
*/
|
||||
public long[] getBestPosition() {
|
||||
return bestPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #bestFitness}.
|
||||
*
|
||||
* @return the {@link #bestFitness}
|
||||
*/
|
||||
public double getBestFitness() {
|
||||
return bestFitness;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #position}.
|
||||
*
|
||||
* @param position
|
||||
* the new {@link #position}
|
||||
*/
|
||||
public void setPosition(long[] position) {
|
||||
this.position = position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #speed}.
|
||||
*
|
||||
* @param speed
|
||||
* the new {@link #speed}
|
||||
*/
|
||||
public void setSpeed(long[] speed) {
|
||||
this.speed = speed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #fitness}.
|
||||
*
|
||||
* @param fitness
|
||||
* the new {@link #fitness}
|
||||
*/
|
||||
public void setFitness(double fitness) {
|
||||
this.fitness = fitness;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #bestPosition}.
|
||||
*
|
||||
* @param bestPosition
|
||||
* the new {@link #bestPosition}
|
||||
*/
|
||||
public void setBestPosition(long[] bestPosition) {
|
||||
this.bestPosition = bestPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #bestFitness}.
|
||||
*
|
||||
* @param bestFitness
|
||||
* the new {@link #bestFitness}
|
||||
*/
|
||||
public void setBestFitness(double bestFitness) {
|
||||
this.bestFitness = bestFitness;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(bestFitness);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
result = prime * result + Arrays.hashCode(bestPosition);
|
||||
temp = Double.doubleToLongBits(fitness);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
result = prime * result + Arrays.hashCode(position);
|
||||
result = prime * result + Arrays.hashCode(speed);
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Particle other = (Particle) obj;
|
||||
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
|
||||
return false;
|
||||
if (!Arrays.equals(bestPosition, other.bestPosition))
|
||||
return false;
|
||||
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
|
||||
return false;
|
||||
if (!Arrays.equals(position, other.position))
|
||||
return false;
|
||||
if (!Arrays.equals(speed, other.speed))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
|
||||
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Represents a collection of {@link Particle}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Swarm {
|
||||
|
||||
/**
|
||||
* The particles of this swarm.
|
||||
*/
|
||||
private Particle[] particles;
|
||||
|
||||
/**
|
||||
* The best position found within the particles of this swarm.
|
||||
*/
|
||||
private long[] bestPosition;
|
||||
|
||||
/**
|
||||
* The best fitness score found within the particles of this swarm.
|
||||
*/
|
||||
private double bestFitness = Double.NEGATIVE_INFINITY;
|
||||
|
||||
/**
|
||||
* A random generator.
|
||||
*/
|
||||
private Random random = new Random();
|
||||
|
||||
/**
|
||||
* Instantiates a new Swarm.
|
||||
*
|
||||
* @param numParticles
|
||||
* the number of particles of the swarm
|
||||
*/
|
||||
public Swarm(int numParticles) {
|
||||
particles = new Particle[numParticles];
|
||||
for (int i = 0; i < numParticles; i++) {
|
||||
long[] initialParticlePosition = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
|
||||
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
|
||||
long[] initialParticleSpeed = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
|
||||
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
|
||||
particles[i] = new Particle(initialParticlePosition, initialParticleSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #particles}.
|
||||
*
|
||||
* @return the {@link #particles}
|
||||
*/
|
||||
public Particle[] getParticles() {
|
||||
return particles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #bestPosition}.
|
||||
*
|
||||
* @return the {@link #bestPosition}
|
||||
*/
|
||||
public long[] getBestPosition() {
|
||||
return bestPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #bestFitness}.
|
||||
*
|
||||
* @return the {@link #bestFitness}
|
||||
*/
|
||||
public double getBestFitness() {
|
||||
return bestFitness;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #bestPosition}.
|
||||
*
|
||||
* @param bestPosition
|
||||
* the new {@link #bestPosition}
|
||||
*/
|
||||
public void setBestPosition(long[] bestPosition) {
|
||||
this.bestPosition = bestPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #bestFitness}.
|
||||
*
|
||||
* @param bestFitness
|
||||
* the new {@link #bestFitness}
|
||||
*/
|
||||
public void setBestFitness(double bestFitness) {
|
||||
this.bestFitness = bestFitness;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(bestFitness);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
result = prime * result + Arrays.hashCode(bestPosition);
|
||||
result = prime * result + Arrays.hashCode(particles);
|
||||
result = prime * result + ((random == null) ? 0 : random.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Swarm other = (Swarm) obj;
|
||||
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
|
||||
return false;
|
||||
if (!Arrays.equals(bestPosition, other.bestPosition))
|
||||
return false;
|
||||
if (!Arrays.equals(particles, other.particles))
|
||||
return false;
|
||||
if (random == null) {
|
||||
if (other.random != null)
|
||||
return false;
|
||||
} else if (!random.equals(other.random))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition)
|
||||
+ ", bestFitness=" + bestFitness + ", random=" + random + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.baeldung.algorithms.permutation;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
public class Permutation {
|
||||
|
||||
public static <T> void printAllRecursive(T[] elements, char delimiter) {
|
||||
printAllRecursive(elements.length, elements, delimiter);
|
||||
}
|
||||
|
||||
public static <T> void printAllRecursive(int n, T[] elements, char delimiter) {
|
||||
|
||||
if(n == 1) {
|
||||
printArray(elements, delimiter);
|
||||
} else {
|
||||
for(int i = 0; i < n-1; i++) {
|
||||
printAllRecursive(n - 1, elements, delimiter);
|
||||
if(n % 2 == 0) {
|
||||
swap(elements, i, n-1);
|
||||
} else {
|
||||
swap(elements, 0, n-1);
|
||||
}
|
||||
}
|
||||
printAllRecursive(n - 1, elements, delimiter);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void printAllIterative(int n, T[] elements, char delimiter) {
|
||||
|
||||
int[] indexes = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
indexes[i] = 0;
|
||||
}
|
||||
|
||||
printArray(elements, delimiter);
|
||||
|
||||
int i = 0;
|
||||
while (i < n) {
|
||||
if (indexes[i] < i) {
|
||||
swap(elements, i % 2 == 0 ? 0: indexes[i], i);
|
||||
printArray(elements, delimiter);
|
||||
indexes[i]++;
|
||||
i = 0;
|
||||
}
|
||||
else {
|
||||
indexes[i] = 0;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends Comparable<T>> void printAllOrdered(T[] elements, char delimiter) {
|
||||
|
||||
Arrays.sort(elements);
|
||||
boolean hasNext = true;
|
||||
|
||||
while(hasNext) {
|
||||
printArray(elements, delimiter);
|
||||
int k = 0, l = 0;
|
||||
hasNext = false;
|
||||
for (int i = elements.length - 1; i > 0; i--) {
|
||||
if (elements[i].compareTo(elements[i - 1]) > 0) {
|
||||
k = i - 1;
|
||||
hasNext = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = elements.length - 1; i > k; i--) {
|
||||
if (elements[i].compareTo(elements[k]) > 0) {
|
||||
l = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
swap(elements, k, l);
|
||||
Collections.reverse(Arrays.asList(elements).subList(k + 1, elements.length));
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void printRandom(T[] elements, char delimiter) {
|
||||
|
||||
Collections.shuffle(Arrays.asList(elements));
|
||||
printArray(elements, delimiter);
|
||||
}
|
||||
|
||||
private static <T> void swap(T[] elements, int a, int b) {
|
||||
|
||||
T tmp = elements[a];
|
||||
elements[a] = elements[b];
|
||||
elements[b] = tmp;
|
||||
}
|
||||
|
||||
private static <T> void printArray(T[] elements, char delimiter) {
|
||||
|
||||
String delimiterSpace = delimiter + " ";
|
||||
for(int i = 0; i < elements.length; i++) {
|
||||
System.out.print(elements[i] + delimiterSpace);
|
||||
}
|
||||
System.out.print('\n');
|
||||
}
|
||||
|
||||
public static void main(String[] argv) {
|
||||
|
||||
Integer[] elements = {1,2,3,4};
|
||||
|
||||
System.out.println("Rec:");
|
||||
printAllRecursive(elements, ';');
|
||||
|
||||
System.out.println("Iter:");
|
||||
printAllIterative(elements.length, elements, ';');
|
||||
|
||||
System.out.println("Orderes:");
|
||||
printAllOrdered(elements, ';');
|
||||
|
||||
System.out.println("Random:");
|
||||
printRandom(elements, ';');
|
||||
|
||||
System.out.println("Random:");
|
||||
printRandom(elements, ';');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.algorithms.smallestinteger;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SmallestMissingPositiveInteger {
|
||||
public static int searchInSortedArray(int[] input) {
|
||||
for (int i = 0; i < input.length; i++) {
|
||||
if (i != input[i]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return input.length;
|
||||
}
|
||||
|
||||
public static int searchInUnsortedArraySortingFirst(int[] input) {
|
||||
Arrays.sort(input);
|
||||
return searchInSortedArray(input);
|
||||
}
|
||||
|
||||
public static int searchInUnsortedArrayBooleanArray(int[] input) {
|
||||
boolean[] flags = new boolean[input.length];
|
||||
for (int number : input) {
|
||||
if (number < flags.length) {
|
||||
flags[number] = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < flags.length; i++) {
|
||||
if (!flags[i]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return flags.length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
public class EnglishAlphabetLetters {
|
||||
|
||||
public static boolean checkStringForAllTheLetters(String input) {
|
||||
boolean[] visited = new boolean[26];
|
||||
|
||||
int index = 0;
|
||||
|
||||
for (int id = 0; id < input.length(); id++) {
|
||||
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
|
||||
index = input.charAt(id) - 'a';
|
||||
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
|
||||
index = input.charAt(id) - 'A';
|
||||
}
|
||||
visited[index] = true;
|
||||
}
|
||||
|
||||
for (int id = 0; id < 26; id++) {
|
||||
if (!visited[id]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkStringForAllLetterUsingStream(String input) {
|
||||
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
|
||||
return c == 26;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
checkStringForAllLetterUsingStream("intit");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class LongestSubstringNonRepeatingCharacters {
|
||||
|
||||
public static String getUniqueCharacterSubstringBruteForce(String input) {
|
||||
String output = "";
|
||||
for (int start = 0; start < input.length(); start++) {
|
||||
Set<Character> visited = new HashSet<>();
|
||||
int end = start;
|
||||
for (; end < input.length(); end++) {
|
||||
char currChar = input.charAt(end);
|
||||
if (visited.contains(currChar)) {
|
||||
break;
|
||||
} else {
|
||||
visited.add(currChar);
|
||||
}
|
||||
}
|
||||
if (output.length() < end - start + 1) {
|
||||
output = input.substring(start, end);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static String getUniqueCharacterSubstring(String input) {
|
||||
Map<Character, Integer> visited = new HashMap<>();
|
||||
String output = "";
|
||||
for (int start = 0, end = 0; end < input.length(); end++) {
|
||||
char currChar = input.charAt(end);
|
||||
if (visited.containsKey(currChar)) {
|
||||
start = Math.max(visited.get(currChar) + 1, start);
|
||||
}
|
||||
if (output.length() < end - start + 1) {
|
||||
output = input.substring(start, end + 1);
|
||||
}
|
||||
visited.put(currChar, end);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
if(args.length > 0) {
|
||||
System.out.println(getUniqueCharacterSubstring(args[0]));
|
||||
} else {
|
||||
System.err.println("This program expects command-line input. Please try again!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class SubstringPalindrome {
|
||||
|
||||
public Set<String> findAllPalindromesUsingCenter(String input) {
|
||||
final Set<String> palindromes = new HashSet<>();
|
||||
if (input == null || input.isEmpty()) {
|
||||
return palindromes;
|
||||
}
|
||||
if (input.length() == 1) {
|
||||
palindromes.add(input);
|
||||
return palindromes;
|
||||
}
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
palindromes.addAll(findPalindromes(input, i, i + 1));
|
||||
palindromes.addAll(findPalindromes(input, i, i));
|
||||
}
|
||||
return palindromes;
|
||||
}
|
||||
|
||||
private Set<String> findPalindromes(String input, int low, int high) {
|
||||
Set<String> result = new HashSet<>();
|
||||
while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
|
||||
result.add(input.substring(low, high + 1));
|
||||
low--;
|
||||
high++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public Set<String> findAllPalindromesUsingBruteForceApproach(String input) {
|
||||
Set<String> palindromes = new HashSet<>();
|
||||
if (input == null || input.isEmpty()) {
|
||||
return palindromes;
|
||||
}
|
||||
if (input.length() == 1) {
|
||||
palindromes.add(input);
|
||||
return palindromes;
|
||||
}
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
for (int j = i + 1; j <= input.length(); j++)
|
||||
if (isPalindrome(input.substring(i, j))) {
|
||||
palindromes.add(input.substring(i, j));
|
||||
}
|
||||
}
|
||||
return palindromes;
|
||||
}
|
||||
|
||||
private boolean isPalindrome(String input) {
|
||||
StringBuilder plain = new StringBuilder(input);
|
||||
StringBuilder reverse = plain.reverse();
|
||||
return (reverse.toString()).equals(input);
|
||||
}
|
||||
|
||||
public Set<String> findAllPalindromesUsingManachersAlgorithm(String input) {
|
||||
Set<String> palindromes = new HashSet<>();
|
||||
String formattedInput = "@" + input + "#";
|
||||
char inputCharArr[] = formattedInput.toCharArray();
|
||||
int max;
|
||||
int radius[][] = new int[2][input.length() + 1];
|
||||
for (int j = 0; j <= 1; j++) {
|
||||
radius[j][0] = max = 0;
|
||||
int i = 1;
|
||||
while (i <= input.length()) {
|
||||
palindromes.add(Character.toString(inputCharArr[i]));
|
||||
while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
|
||||
max++;
|
||||
radius[j][i] = max;
|
||||
int k = 1;
|
||||
while ((radius[j][i - k] != max - k) && (k < max)) {
|
||||
radius[j][i + k] = Math.min(radius[j][i - k], max - k);
|
||||
k++;
|
||||
}
|
||||
max = Math.max(max - k, 0);
|
||||
i += k;
|
||||
}
|
||||
}
|
||||
for (int i = 1; i <= input.length(); i++) {
|
||||
for (int j = 0; j <= 1; j++) {
|
||||
for (max = radius[j][i]; max > 0; max--) {
|
||||
palindromes.add(input.substring(i - max - 1, max + j + i - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return palindromes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
|
||||
import com.baeldung.algorithms.middleelementlookup.Node;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class MiddleElementLookupUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFindingMiddleLinkedList_thenMiddleFound() {
|
||||
assertEquals("3", MiddleElementLookup
|
||||
.findMiddleElementLinkedList(createLinkedList(5))
|
||||
.get());
|
||||
assertEquals("2", MiddleElementLookup
|
||||
.findMiddleElementLinkedList(createLinkedList(4))
|
||||
.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindingMiddleFromHead_thenMiddleFound() {
|
||||
assertEquals("3", MiddleElementLookup
|
||||
.findMiddleElementFromHead(createNodesList(5))
|
||||
.get());
|
||||
assertEquals("2", MiddleElementLookup
|
||||
.findMiddleElementFromHead(createNodesList(4))
|
||||
.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
|
||||
assertEquals("3", MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassRecursively(createNodesList(5))
|
||||
.get());
|
||||
assertEquals("2", MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassRecursively(createNodesList(4))
|
||||
.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
|
||||
assertEquals("3", MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassIteratively(createNodesList(5))
|
||||
.get());
|
||||
assertEquals("2", MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassIteratively(createNodesList(4))
|
||||
.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListEmptyOrNull_thenMiddleNotFound() {
|
||||
// null list
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementLinkedList(null)
|
||||
.isPresent());
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementFromHead(null)
|
||||
.isPresent());
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassIteratively(null)
|
||||
.isPresent());
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassRecursively(null)
|
||||
.isPresent());
|
||||
|
||||
// empty LinkedList
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementLinkedList(new LinkedList<>())
|
||||
.isPresent());
|
||||
|
||||
// LinkedList with nulls
|
||||
LinkedList<String> nullsList = new LinkedList<>();
|
||||
nullsList.add(null);
|
||||
nullsList.add(null);
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementLinkedList(nullsList)
|
||||
.isPresent());
|
||||
|
||||
// nodes with null values
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementFromHead(new Node(null))
|
||||
.isPresent());
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassIteratively(new Node(null))
|
||||
.isPresent());
|
||||
assertFalse(MiddleElementLookup
|
||||
.findMiddleElementFromHead1PassRecursively(new Node(null))
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
private static LinkedList<String> createLinkedList(int n) {
|
||||
LinkedList<String> list = new LinkedList<>();
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
list.add(String.valueOf(i));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static Node createNodesList(int n) {
|
||||
Node head = new Node("1");
|
||||
Node current = head;
|
||||
|
||||
for (int i = 2; i <= n; i++) {
|
||||
Node newNode = new Node(String.valueOf(i));
|
||||
current.setNext(newNode);
|
||||
current = newNode;
|
||||
}
|
||||
|
||||
return head;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
/**
|
||||
* Specific fitness function implementation to solve the League of Legends
|
||||
* problem. This is the problem statement: <br>
|
||||
* <br>
|
||||
* In League of Legends, a player's Effective Health when defending against
|
||||
* physical damage is given by E=H(100+A)/100, where H is health and A is armor.
|
||||
* Health costs 2.5 gold per unit, and Armor costs 18 gold per unit. You have
|
||||
* 3600 gold, and you need to optimize the effectiveness E of your health and
|
||||
* armor to survive as long as possible against the enemy team's attacks. How
|
||||
* much of each should you buy? <br>
|
||||
* <br>
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class LolFitnessFunction implements FitnessFunction {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* com.baeldung.algorithms.multiswarm.FitnessFunction#getFitness(long[])
|
||||
*/
|
||||
@Override
|
||||
public double getFitness(long[] particlePosition) {
|
||||
|
||||
long health = particlePosition[0];
|
||||
long armor = particlePosition[1];
|
||||
|
||||
// No negatives values accepted.
|
||||
if (health < 0 && armor < 0) {
|
||||
return -(health * armor);
|
||||
} else if (health < 0) {
|
||||
return health;
|
||||
} else if (armor < 0) {
|
||||
return armor;
|
||||
}
|
||||
|
||||
// Checks if the solution is actually feasible provided our gold.
|
||||
double cost = (health * 2.5) + (armor * 18);
|
||||
if (cost > 3600) {
|
||||
return 3600 - cost;
|
||||
} else {
|
||||
// Check how good is the solution.
|
||||
long fitness = (health * (100 + armor)) / 100;
|
||||
return fitness;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.algorithms.multiswarm;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.support.MayFailRule;
|
||||
|
||||
/**
|
||||
* Test for {@link Multiswarm}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class MultiswarmUnitTest {
|
||||
|
||||
/**
|
||||
* Rule for handling expected failures. We use this since this test may
|
||||
* actually fail due to bad luck in the random generation.
|
||||
*/
|
||||
@Rule
|
||||
public MayFailRule mayFailRule = new MayFailRule();
|
||||
|
||||
/**
|
||||
* Tests the multiswarm algorithm with a generic problem. The problem is the
|
||||
* following: <br>
|
||||
* <br>
|
||||
* In League of Legends, a player's Effective Health when defending against
|
||||
* physical damage is given by E=H(100+A)/100, where H is health and A is
|
||||
* armor. Health costs 2.5 gold per unit, and Armor costs 18 gold per unit.
|
||||
* You have 3600 gold, and you need to optimize the effectiveness E of your
|
||||
* health and armor to survive as long as possible against the enemy team's
|
||||
* attacks. How much of each should you buy? <br>
|
||||
* <br>
|
||||
* The solution is H = 1080, A = 50 for a total fitness of 1620. Tested with
|
||||
* 50 swarms each with 1000 particles.
|
||||
*/
|
||||
@Test
|
||||
public void givenMultiswarm_whenThousandIteration_thenSolutionFound() {
|
||||
Multiswarm multiswarm = new Multiswarm(50, 1000, new LolFitnessFunction());
|
||||
|
||||
// Iterates 1000 times through the main loop and prints the result.
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
multiswarm.mainLoop();
|
||||
}
|
||||
|
||||
System.out.println("Best fitness found: " + multiswarm.getBestFitness() + "[" + multiswarm.getBestPosition()[0]
|
||||
+ "," + multiswarm.getBestPosition()[1] + "]");
|
||||
Assert.assertEquals(1080, multiswarm.getBestPosition()[0]);
|
||||
Assert.assertEquals(50, multiswarm.getBestPosition()[1]);
|
||||
Assert.assertEquals(1620, (int) multiswarm.getBestFitness());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.algorithms.smallestinteger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class SmallestMissingPositiveIntegerUnitTest {
|
||||
@Test
|
||||
void givenArrayWithThreeMissing_whenSearchInSortedArray_thenThree() {
|
||||
int[] input = new int[] {0, 1, 2, 4, 5};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithOneAndThreeMissing_whenSearchInSortedArray_thenOne() {
|
||||
int[] input = new int[] {0, 2, 4, 5};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutMissingInteger_whenSearchInSortedArray_thenArrayLength() {
|
||||
int[] input = new int[] {0, 1, 2, 3, 4, 5};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(input.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithThreeMissing_whenSearchInUnsortedArraySortingFirst_thenThree() {
|
||||
int[] input = new int[] {1, 4, 0, 5, 2};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
|
||||
|
||||
assertThat(result).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArraySortingFirst_thenOne() {
|
||||
int[] input = new int[] {4, 2, 0, 5};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
|
||||
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutMissingInteger_whenSearchInUnsortedArraySortingFirst_thenArrayLength() {
|
||||
int[] input = new int[] {4, 5, 1, 3, 0, 2};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
|
||||
|
||||
assertThat(result).isEqualTo(input.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenThree() {
|
||||
int[] input = new int[] {1, 4, 0, 5, 2};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenOne() {
|
||||
int[] input = new int[] {4, 2, 0, 5};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutMissingInteger_whenSearchInUnsortedArrayBooleanArray_thenArrayLength() {
|
||||
int[] input = new int[] {4, 5, 1, 3, 0, 2};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(input.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutZero_whenSearchInUnsortedArrayBooleanArray_thenZero() {
|
||||
int[] input = new int[] {11, 13, 14, 15};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EnglishAlphabetLettersUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenContainsAllCharacter_thenTrue() {
|
||||
String input = "Farmer jack realized that big yellow quilts were expensive";
|
||||
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
|
||||
String input = "Farmer jack realized that big yellow quilts were expensive";
|
||||
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
|
||||
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
|
||||
|
||||
public class LongestSubstringNonRepeatingCharactersUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
|
||||
assertEquals("", getUniqueCharacterSubstringBruteForce(""));
|
||||
assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
|
||||
assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
|
||||
assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
|
||||
assertEquals("", getUniqueCharacterSubstring(""));
|
||||
assertEquals("A", getUniqueCharacterSubstring("A"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
|
||||
assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
|
||||
assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SubstringPalindromeUnitTest {
|
||||
|
||||
private static final String INPUT_BUBBLE = "bubble";
|
||||
private static final String INPUT_CIVIC = "civic";
|
||||
private static final String INPUT_INDEED = "indeed";
|
||||
private static final String INPUT_ABABAC = "ababac";
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_BUBBLE = new HashSet<String>() {
|
||||
{
|
||||
add("b");
|
||||
add("u");
|
||||
add("l");
|
||||
add("e");
|
||||
add("bb");
|
||||
add("bub");
|
||||
}
|
||||
};
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_CIVIC = new HashSet<String>() {
|
||||
{
|
||||
add("civic");
|
||||
add("ivi");
|
||||
add("i");
|
||||
add("c");
|
||||
add("v");
|
||||
}
|
||||
};
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_INDEED = new HashSet<String>() {
|
||||
{
|
||||
add("i");
|
||||
add("n");
|
||||
add("d");
|
||||
add("e");
|
||||
add("ee");
|
||||
add("deed");
|
||||
}
|
||||
};
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_ABABAC = new HashSet<String>() {
|
||||
{
|
||||
add("a");
|
||||
add("b");
|
||||
add("c");
|
||||
add("aba");
|
||||
add("bab");
|
||||
add("ababa");
|
||||
}
|
||||
};
|
||||
|
||||
private SubstringPalindrome palindrome = new SubstringPalindrome();
|
||||
|
||||
@Test
|
||||
public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
|
||||
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
|
||||
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
|
||||
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
|
||||
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCenterApproach_thenFindsAllPalindromes() {
|
||||
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
|
||||
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
|
||||
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
|
||||
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
|
||||
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
|
||||
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
|
||||
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
|
||||
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.algorithms.support;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.TestRule;
|
||||
import org.junit.runner.Description;
|
||||
import org.junit.runners.model.Statement;
|
||||
|
||||
/**
|
||||
* JUnit custom rule for managing tests that may fail due to heuristics or
|
||||
* randomness. In order to use this, just instantiate this object as a public
|
||||
* field inside the test class and annotate it with {@link Rule}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class MayFailRule implements TestRule {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement,
|
||||
* org.junit.runner.Description)
|
||||
*/
|
||||
@Override
|
||||
public Statement apply(Statement base, Description description) {
|
||||
return new Statement() {
|
||||
@Override
|
||||
public void evaluate() throws Throwable {
|
||||
try {
|
||||
base.evaluate();
|
||||
} catch (Throwable e) {
|
||||
// Ignore the exception since we expect this.
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user