Initial commit

This commit is contained in:
2025-04-13 20:30:02 +02:00
commit 4f8e93c2c6
37 changed files with 2945 additions and 0 deletions

25
.gitignore vendored Normal file
View File

@@ -0,0 +1,25 @@
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

62
pom.xml Normal file
View File

@@ -0,0 +1,62 @@
<?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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.tenvoorde</groupId>
<artifactId>geocaching</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>de.grundid.opendatalab</groupId>
<artifactId>geojson-jackson</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.16.1</version>
</dependency>
<dependency>
<groupId>org.wololo</groupId>
<artifactId>jts2geojson</artifactId>
<version>0.14.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,38 @@
public class Determinant {
static int d1 = det1(7,2,4,2,8,7);
static int d2 = det2(7,2,4,2,8,7);
public static void main(String[] args) {
for (int n1 = 0; n1 <= 9; n1++) {
for (int n2 = 0; n2 <= 9; n2++) {
for (int n3 = 0; n3 <= 9; n3++) {
for (int e1 = 0; e1 <= 9; e1++) {
for (int e2 = 0; e2 <= 9; e2++) {
for (int e3 = 0; e3 <= 9; e3++) {
// int det1 = -15 * e1 - 5 * e2 + 40 * e3 + 2 * e2 * n1 - 7 * e3 * n1 - 2 * e1 * n2
// + 3 * e3 * n2 + 7 * e1 * n3 - 3 * e2 * n3;
// int det2 = 4 + 20 * e1 + 21 * e1 * e2 - 7 * e3 - 6 * e2 * n1 - 10 * e3 * n1 - 10 * n2
// - 7 * e2 * n2 + 5 * e2 * n1 * n2 - 6 * e1 * n3 + 3 * e3 * n1 * n3 + 2 * n2 * n3;
if (det1(n1,n2,n3,e1,e2,e3) == d1 && det2(n1,n2,n3,e1,e2,e3) == d2) {
System.out.println("" + n1 + n2 + n3 + e1 + e2 + e3);
}
}
}
}
}
}
}
}
static int det1(int n1, int n2, int n3, int e1, int e2, int e3) {
return -15 * e1 - 5 * e2 + 40 * e3 + 2 * e2 * n1 - 7 * e3 * n1 - 2 * e1 * n2
+ 3 * e3 * n2 + 7 * e1 * n3 - 3 * e2 * n3;
}
static int det2(int n1, int n2, int n3, int e1, int e2, int e3) {
return 4 + 20 * e1 + 21 * e1 * e2 - 7 * e3 - 6 * e2 * n1 - 10 * e3 * n1 - 10 * n2
- 7 * e2 * n2 + 5 * e2 * n1 * n2 - 6 * e1 * n3 + 3 * e3 * n1 * n3 + 2 * n2 * n3;
}
}

View File

@@ -0,0 +1,16 @@
public class Grutten {
private static long josephus(long total, int skip) {
long g = 1;
for (long i = 1; i <= total; i++) {
g = ((g + skip - 1) % i) + 1;
}
return g;
}
public static void main(String[] args) {
System.out.println(josephus(7382786182L, 18));
}
}

View File

@@ -0,0 +1,31 @@
//* @author: 82638882@163.com
import java.io.*;
import java.util.Arrays;
public class LadderProblem {
public static void main(String[] args) throws IOException {
// String[] ss = in.readLine().split(" ");
// double x = Double.parseDouble(ss[0]);
// double y = Double.parseDouble(ss[1]);
// double c = Double.parseDouble(ss[2]);
double x = 10;
double y = 12;
double c = 5;
double max = Math.min(x, y), min = 0;
for (int i = 0; max - min > 0.0000000001; i++) {
double mid = (min + max) / 2;
double d1 = Math.sqrt(x * x - mid * mid);
double d2 = Math.sqrt(y * y - mid * mid);
if (c * (d1 + d2) == (d1 * d2)) {
min = max = mid;
break;
} else if (c * (d1 + d2) > (d1 * d2))
max = mid;
else
min = mid;
}
System.out.printf("%.10f\n", (min + max) / 2);
}
}

26
src/main/java/Slak.java Normal file
View File

@@ -0,0 +1,26 @@
import java.math.BigDecimal;
import java.math.MathContext;
public class Slak {
private static final double INIT_LENGTE = 1;
private static final double GROEI_PER_DAG = 1;
private static final double WANDELING_PER_DAG = 0.12;
public static void main(String[] args) {
double lengte_touw = INIT_LENGTE;
//noinspection deprecation
BigDecimal positie = new BigDecimal(0).setScale(10, BigDecimal.ROUND_HALF_UP);
// double positie = 0;
long dag = 0;
do {
dag++;
positie = positie.add(new BigDecimal(WANDELING_PER_DAG));
if (positie.compareTo(new BigDecimal(lengte_touw)) > 0) break;
lengte_touw += GROEI_PER_DAG;
positie = positie.multiply(new BigDecimal(lengte_touw / (lengte_touw - GROEI_PER_DAG)));
} while (positie.compareTo(new BigDecimal(lengte_touw)) < 0);
System.out.println(dag);
}
}

View File

@@ -0,0 +1,24 @@
public class SlakJohan {
public static void main(String[] args) {
double slak = 0;
for (int i = 1; i < 200000000; i++) {
slak = (slak + 0.05); // actie 1: schuiven
if (slak >= i) { // actie 2: checken
System.out.println("Lengte touw = " + (i + 1) + ", slak = " + slak);
break;
}
slak *= ((i + 1) / (double) i); // 3: direct daarna uitrekken
if (i < 10) { // debug
System.out.println(
"Slak[" + i + "] = " + slak + ", lengte touw = " + (i + 1) + ", dif = " + (slak - ((i + 1))));
}
if (i % 100000 == 0) { // debug
System.out.println(
"Slak[" + i + "] = " + slak + ", lengte touw = " + (i + 1) + ", dif = " + (slak - ((i + 1))));
}
}
System.out.println("Lengte touw geen uitkomst");
}
}

131
src/main/java/Test.java Normal file
View File

@@ -0,0 +1,131 @@
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Random;
public class Test {
// published: 200479, 468608
// cache: 198667, 467811
private static final int foost = 108549;
private static final int fnoord = 480361;
//108549,
private static final int min_distance = 3219;
private static final int max_distance = 10000;
private static final String filename = "d:\\temp\\gc6dyy3.txt";
@SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
// snail();
test();
if (0 < 1) return;
Random generator = new Random();
Long oost;
Long noord;
Long distance;
int step = 0;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"))) {
do {
oost = (long) generator.nextInt(900000) + 100000;
noord = (long) generator.nextInt(900000) + 100000;
distance = (long) Math.sqrt((oost - foost) * (oost - foost) + (noord - fnoord) * (noord - fnoord));
if (distance > min_distance && distance < max_distance) {
writer.write(oost.toString());
writer.write(noord.toString());
step++;
if (step % 12 == 0) {
writer.newLine();
}
}
} while (step < 12000);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void test() throws IOException {
Path path = Paths.get(filename);
byte[] data = Files.readAllBytes(path);
int goed = 0;
for (int pos = 0; pos < data.length - 13; pos++) {
String oost = "";
String noord = "";
int subpos = pos;
for (int i = 1; i <= 6; i++) {
while (data[subpos] == 13 || data[subpos] == 10) {
subpos++;
}
oost += Integer.toString(data[subpos] - '0');
subpos++;
}
for (int i = 1; i <= 6; i++) {
while (data[subpos] == 13 || data[subpos] == 10) {
subpos++;
}
noord += Integer.toString(data[subpos] - '0');
subpos++;
}
Long lnoord = Long.parseLong(noord);
Long loost = Long.parseLong(oost);
Long distance = (long) Math.sqrt((loost - foost) * (loost - foost) + (lnoord - fnoord) * (lnoord - fnoord));
if (distance < min_distance) {
System.out.println(oost + " " + noord + " " + distance);
} else {
goed++;
}
}
System.out.println(goed);
}
private static void snail() {
double length = 20;
double walk = 1;
double position = 0;
double growth = 20;
long step = 0;
do {
step++;
position += walk;
length += growth;
position *= (length / (length - growth));
} while (position < length);
System.out.println(step);
}
private static void test2() {
var a = new ArrayList<>();
a.size();
int[] b;
b = new int[5];
int c = b.length;
String d = "abc";
d.length();
}
}

View File

@@ -0,0 +1,4 @@
public class TrackableCrawler {
}

View File

@@ -0,0 +1,155 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
public class Traveling {
private static double minimum = 100000;
private static Map<Pair<City,City>, Double> distances = new HashMap<>();
class tspThread implements Runnable {
List<City> toVisit, visited;
public tspThread(List<City> toVisit, List<City> visited) {
this.toVisit = toVisit;
this.visited = visited;
}
public void run() {
System.out.println("Thread gestart met begin " + this.visited.get(0));
findBestRoute(toVisit, visited);
System.out.println("--- thread klaar ---");
}
}
public void start() {
List<City> cities = new ArrayList<>(Arrays.asList(
new City("n", 6, 1)
, new City("f", 3, 2)
, new City("a", 5, 4)
, new City("b", 7, 4)
, new City("k", 10, 4)
, new City("g", 1, 5)
, new City("c", 9, 6)
, new City("e", 4, 7)
, new City("d", 8, 8)
, new City("q", 10, 8)
, new City("h", 4, 10)
, new City("p", 7, 10)
, new City("m", 10, 10)
));
buildDistancesMap(cities);
for (City cityToVisit : cities) {
List<City> toVisitClone = new ArrayList<>(cities);
List<City> visitedClone = new ArrayList<>();
toVisitClone.remove(cityToVisit);
visitedClone.add(cityToVisit);
System.out.println("<" + cityToVisit.getName() + ">");
Thread thread = new Thread(new tspThread(toVisitClone, visitedClone));
thread.start();
//findBestRoute(toVisitClone, visitedClone);
}
}
public static void main(String[] args) {
new Traveling().start();
}
private static void buildDistancesMap(List<City> cities) {
for (City from : cities) {
for (City to : cities) {
distances.put(Pair.of(from, to), from.distance(to));
}
}
}
public static void findBestRoute(List<City> toVisit, List<City> visited) {
if (toVisit.isEmpty()) {
if (distance(visited) <= minimum) {
minimum = distance(visited);
System.out.format("%s %f%n", visited, minimum);
}
return;
}
for (City cityToVisit : toVisit) {
List<City> toVisitClone = new ArrayList<>(toVisit);
List<City> visitedClone = new ArrayList<>(visited);
toVisitClone.remove(cityToVisit);
visitedClone.add(cityToVisit);
findBestRoute(toVisitClone, visitedClone);
}
}
public static double distance(List<City> cities) {
double distance = 0.0D;
City city1 = null;
City city2 = null;
for (City city : cities) {
city1 = city2;
city2 = city;
if (city1 != null) {
distance += distances.get(Pair.of(city1, city2));
}
}
return distance;
}
}
class City {
private String name;
private int x;
private int y;
public double distance(City that) {
return Math.sqrt((this.x - that.x)*(this.x - that.x) + (this.y - that.y)*(this.y - that.y));
}
public City(String name, int x, int y) {
super();
this.name = name;
this.x = x;
this.y = y;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,29 @@
package collatz;
import java.util.Comparator;
import java.util.TreeSet;
public class Collatz {
public static long collatz(long n) {
long steps = 0;
while (n > 1) {
steps++;
if (n % 2 == 0) {
n /= 2;
} else {
n *= 3;
n++;
}
}
return steps;
}
public static void main(String[] args) {
System.out.println(set);
System.out.println(collatz(27));
}
}

View File

@@ -0,0 +1,18 @@
package fibo;
public class Fibo {
public static void main(String[] args) {
int N = 5212034;
double phi = (Math.sqrt(5) + 1)/2;
int M = (int) (N/phi);
do {
System.out.println(M);
M = N - M;
N = N - M;
} while (M > 0 && N > 0);
}
}

View File

@@ -0,0 +1,79 @@
package frobenius;
import java.util.Arrays;
import java.util.Random;
public class FrobeniusNums {
private static final int upperRange = 30;
private static final int toSearch = 129;
public static void main(String[] args) {
int[] numbers;
int frob = 0;
int frobMax = 0;
do {
numbers = new int[]{getRandomNumberInRange(3, upperRange), getRandomNumberInRange(3, upperRange), getRandomNumberInRange(3, upperRange)};
if (numbers[0] == numbers[1] || numbers[0] == numbers[2] || numbers[1] == numbers[2]) continue;
frob = frobenius(numbers);
if (frob > frobMax) {
frobMax = frob;
System.out.printf("%d: %s\n", frobMax, Arrays.toString(numbers));
}
if (frob == toSearch) {
System.out.printf("%d: %s\n", toSearch, Arrays.toString(numbers));
}
} while (frob != 10000);
System.out.println(Arrays.toString(numbers));
}
private static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
static int frobenius(int[] nums) {
int[] ns = new int[nums[0]];
Arrays.fill(ns, -1);
ns[0] = 0;
for (int i = 1; i < nums.length; i++) {
int d = gcd(nums[0], nums[i]);
for (int r = 0; r < d; r++) {
int n = -1;
if (r == 0)
n = 0;
else {
int q = r;
while (q < nums[0]) {
if (ns[q] != -1 && (ns[q] < n || n == -1))
n = ns[q];
q += d;
}
}
if (n != -1)
for (int j = 0; j < nums[0] / d; j++) {
n += nums[i];
int p = n % nums[0];
if (ns[p] != -1 && (ns[p] < n || n == -1))
n = ns[p];
ns[p] = n;
}
}
}
int max = 0;
for (int i = 0; i < nums[0]; i++)
if (ns[i] == -1 || ns[i] > max)
max = ns[i];
if (max == -1) return -1;
return max - nums[0];
}
static int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
}

View File

@@ -0,0 +1,101 @@
package gsakpolygons;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
import org.wololo.geojson.Feature;
import org.wololo.geojson.FeatureCollection;
import org.wololo.jts2geojson.GeoJSONReader;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import static java.util.Collections.max;
import static java.util.Collections.min;
public class GSAKPolygons {
private static final String PREFIX = "D:\\Nextcloud\\Geocaching\\polygons\\";
private static final String OUTPUT_FOLDER = PREFIX + "new\\";
private static final boolean USE_NUMERIC_FILENAMES = true;
private static final String FILE_EXTENSION = ".txt";
private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
private static final GeoJSONReader reader = new GeoJSONReader();
private static int fileCounter = 0;
private static List<MetaData> metadata = new ArrayList<>();
public static void main(String[] args) throws IOException {
FileInputStream inputStream = new FileInputStream(PREFIX + "Argentina_AL5.GeoJson");
FeatureCollection featureCollection = objectMapper.readValue(inputStream, FeatureCollection.class);
for (Feature feature : featureCollection.getFeatures()) {
String gsakName = (String) feature.getProperties().get("name");
MultiPolygon multiPolygon = (MultiPolygon) reader.read(feature.getGeometry());
if (multiPolygon.getNumGeometries() > 1) {
for (int geomNr = 0; geomNr < multiPolygon.getNumGeometries(); geomNr++) {
Geometry geometry = multiPolygon.getGeometryN(geomNr);
String fileName = (USE_NUMERIC_FILENAMES ? Integer.toString(++fileCounter) : gsakName + "_" + (geomNr + 1));
processPolygon(geometry, gsakName, fileName);
}
} else {
Geometry geometry = multiPolygon.getGeometryN(0);
String fileName = (USE_NUMERIC_FILENAMES ? Integer.toString(++fileCounter) : gsakName);
processPolygon(geometry, gsakName, fileName);
}
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUTPUT_FOLDER + "meta.txt")))) {
for (MetaData meta : metadata) {
writer.write(meta.asCsv());
writer.write("\n");
}
}
}
private static void processPolygon(Geometry geometry, String gsakName, String fileName) throws IOException {
System.out.println(fileName);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUTPUT_FOLDER + fileName + FILE_EXTENSION), "utf-8"))) {
writer.write("# GsakName=" + gsakName + "\n" +
"# This Country polygon is based on data (c) OpenStreetMap contributors\n" +
"# The OpenStreetMap data is made available under the Open Database License, see http://www.openstreetmap.org/copyright\n" +
"# This polygon file is made available under the same Open Database License: http://opendatacommons.org/licenses/odbl/1.0/.\n");
for (Coordinate coordinate : geometry.getCoordinates()) {
writer.write(coordinate.y + "," + coordinate.x);
writer.write("\n");
}
Polygon boundingBox = (Polygon) geometry.getEnvelope();
Coordinate[] coordinates = boundingBox.getCoordinates();
List<Double> latitudes = Arrays.stream(coordinates).map(Coordinate::getY).collect(Collectors.toList());
List<Double> longitudes = Arrays.stream(coordinates).map(Coordinate::getX).collect(Collectors.toList());
metadata.add(MetaData.builder().fileName(fileName).gsakName(gsakName).minLat(min(latitudes)).maxLat(max(latitudes)).minLon(min(longitudes)).maxLon(max(longitudes)).build());
}
}
}
@Builder
class MetaData {
// Filename, maxlat, minlat, maxlon, minlon, gsakname
private String fileName;
private double maxLat;
private double minLat;
private double maxLon;
private double minLon;
private String gsakName;
public String asCsv() {
return String.format(Locale.ROOT, "%s,%f,%f,%f,%f,%s", fileName, maxLat, minLat, maxLon, minLon, gsakName);
}
}

View File

@@ -0,0 +1,27 @@
package hash;
import org.apache.commons.codec.digest.DigestUtils;
public class Dre1968 {
private static final String template = "N52 %02d.%03d E005 %02d.%03d";
private static final String hashToFind = "4E77A87A1E3E9E362625A0A86508E1B8";
public static void main(String[] args) {
// String digest = DigestUtils.md5Hex("");
for (int nMin = 3; nMin <= 8; nMin++) {
for (int eMin = 49; eMin <= 57; eMin++) {
System.out.println(nMin + " " + eMin);
for (int nSec = 0; nSec <= 999; nSec++) {
for (int eSec = 0; eSec <= 999; eSec++) {
// System.out.println(String.format(template, nMin, nSec, eMin, eSec));
if (hashToFind.equalsIgnoreCase(DigestUtils.md5Hex(String.format(template, nMin, nSec, eMin, eSec)))) {
System.out.println(String.format(template, nMin, nSec, eMin, eSec));
System.exit(0);
}
}
}
}
}
}
}

View File

@@ -0,0 +1,506 @@
package hash;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
public class Hachee {
private static final List<String> aardappels = Arrays.asList(
"DORE",
"NIER",
"AGRIA",
"ALPHA",
"IRENE",
"KRIEL",
"MALTA",
"PATAT",
"POTER",
"RAPER",
"RODEN",
"ROTJE",
"GLORIA",
"LEGGER",
"ROOSJE",
"TOFFEL",
"BINTJE",
"FURORE",
"NICOLA",
"PIEPER",
"ROOIEN",
"ZANDER",
"AFKOKER",
"ASTARTE",
"ELEMENT",
"GLIMMER",
"SATURNA",
"BILDSTAR",
"HOORNTJE",
"BILTSTAR",
"DRIELING",
"PREMIERE",
"ROODNEUS",
"OPPERDOES",
"ARNHEMMER",
"CHARLOTTE",
"KEMPENAAR",
"PIMPERNEL",
"PREVALENT",
"PROMINENT",
"BEVELANDER",
"EERSTELING",
"NEGENWEKER",
"EIGENHEIMER",
"PAARSPETTEN",
"PAARSPITTEN",
"LEKKERLANDER");
private static final List<String> groentes = Arrays.asList(
"UI",
"LOF",
"SLA",
"BIET",
"EPPE",
"ERWT",
"MAIS",
"OKRA",
"PEUL",
"UIEN",
"BOON",
"KNOL",
"KOOL",
"MOES",
"PEEN",
"PREI",
"RAAP",
"BOSUI",
"KROOT",
"ATJAR",
"BONEN",
"IJSSLA",
"KUSSA",
"LATUW",
"RADIJS",
"TAHOE",
"TAUGE",
"FRISEE",
"KROTEN",
"MIELIE",
"RUCOLA",
"SAVOOI",
"SIEPEL",
"SJALOT",
"SPRUIT",
"WORTEL",
"BIETEN",
"DUNSEL",
"LINZEN",
"MOLSLA",
"PAKSOI",
"SAJOER",
"SALADE",
"SNIJSLA",
"TOMAAT",
"VENKEL",
"VETSLA",
"WITLOF",
"ZURING",
"BOLETEN",
"DOPERWT",
"KOOLSLA",
"LENTEUI",
"MEIKNOL",
"POMPOEN",
"RAMENAS",
"SNIJBIET",
"SNIJBOON",
"TOMATEN",
"ALFALFA",
"ANDIJVIE",
"ASPERGE",
"BIETJES",
"BOSPEEN",
"DOPPERS",
"KOPKOOL",
"KROPSLA",
"KRULSLA",
"LAMSOOR",
"MEIRAAP",
"PAPRIKA",
"RETTICH",
"SELDERIJ",
"SLABOON",
"TUINSLA",
"VELDSLA",
"VOEDSEL",
"WARMOES",
"WASBOON",
"WASPEEN",
"WITLOOF",
"AKKERSLA",
"ARTISJOK",
"ASPERGES",
"BIESLOOK",
"BOTERSLA",
"BUISKOOL",
"GROENLOF",
"KNOFLOOK",
"PEENTJES",
"PEULTJES",
"RAMMENAS",
"RODEKOOL",
"SPRUITEN",
"STOOFSLA",
"TUINKERS",
"VELDERWT",
"WORTELEN",
"BROCCOLI",
"KNOLRAAP",
"KOOLRAAP",
"KOOLRABI",
"KROPKOOL",
"PEULERWT",
"PORTULAK",
"RABARBER",
"SELDERIE",
"SLABONEN",
"SNIJBONEN",
"SPINAZIE",
"STOKBOON",
"STOKERWT",
"TUINBOON",
"ZUURKOOL",
"APPELMOES",
"BLOEMKOOL",
"FLAGEOLET",
"KAPUCIJNER",
"KASTANJES",
"KOMKOMMER",
"PASTINAAK",
"SEPARABEL",
"SPITSKOOL",
"TUINBONEN",
"WATERKERS",
"AUBERGINE",
"COURGETTE",
"DOPERWTEN",
"IJSBERGSLA",
"MOESKRUID",
"POSTELEIN",
"SLUITKOOL",
"SPRUITJES",
"VETSALADE",
"WITTEKOOL",
"AUBERGINES",
"CHAMPIGNON",
"DOPERWTJES",
"KAPUCIJNERS",
"KOOLSTRONK",
"PETERSELIE",
"RAAPSTELEN",
"STOOFPEREN",
"SUIKERMAIS",
"VENKELKNOL",
"WINTERPEEN",
"WORTELTJES",
"BOERENKOOL",
"GROENEKOOL",
"KABUISKOOL",
"KASANDIJVIE",
"KOUSENBAND",
"WINTERPREI",
"ARTISJOKKEN",
"CHAMPIGNONS",
"CITROENGRAS",
"FLESKALEBAS",
"KNOLSELDERIJ",
"PUNTPAPRIKA",
"SAVOOIEKOOL",
"SELDERIJKNOL",
"BLADSELDERIJ",
"SPERZIEBOON",
"BLADSPINAZIE",
"BLEEKSELDERIJ",
"CANTHARELLEN",
"CAYENNEPEPER",
"KNOLSELDERIE",
"SCHORSENEREN",
"SELDERIEKNOL",
"SELDERIEKOOL",
"SPERZIEBONEN",
"STOOFASPERGE",
"WINTERWORTEL",
"BLADSELDERIE",
"EIKENBLADSLA",
"SLEEPASPERGE",
"WINTERANDIJVIE",
"WINTERWORTELS",
"BLEEKSELDERIE",
"MUSKAATPOMPOEN",
"PRINSESSENBONEN",
"WINTERPOSTELEIN");
private static final List<String> vlezen = Arrays.asList(
"KIP",
"HAM",
"BASK",
"HESP",
"SATE",
"BIEF",
"PATE",
"PORK",
"ROTI",
"STEW",
"TONG",
"ZULT",
"GYROS",
"KEBAK",
"ASPIC",
"BACON",
"KEBAB",
"SPIES",
"STEAK",
"WORST",
"PASTEI",
"POELET",
"SALAMI",
"BAKLAP",
"GEHAKT",
"HACHEE",
"HAMLAP",
"RAGOUT",
"REERUG",
"RIBLAP",
"ROLHAM",
"SAUCIJS",
"BEENHAM",
"BIEFLAP",
"CERVELA",
"GOULASH",
"LAMSRUG",
"PERSKOP",
"STOVERIJ",
"WORSTJE",
"GEBRAAD",
"KOTELET",
"LAMSRIB",
"PRESKOP",
"REEBOUT",
"RIBSTUK",
"ROLLADE",
"ROLPENS",
"ROSBIEF",
"SHOARMA",
"SLAVINK",
"SOEPKIP",
"SPEKLAP",
"TARTAAR",
"HAMLAPJE",
"METWORST",
"MOUSSAKA",
"OSSETONG",
"OSSOBUCO",
"PARMAHAM",
"ROOKSPEK",
"ROOMPATE",
"ROOMSATE",
"SJASLIEK",
"SPARERIB",
"TAGLIATA",
"ZWEZERIK",
"BERLINER",
"BIEFSTUK",
"ESCALOPE",
"FRIKADEL",
"KLAPSTUK",
"LAMSBOUT",
"NIERSTUK",
"NIERTJES",
"ROLLENDE",
"SAUCISSE",
"SHOWARMA",
"STOOFLAP",
"ANDOUILLE",
"BALKENBRIJ",
"CASSEROLE",
"CASSOULET",
"KALFSTONG",
"KIPBURGER",
"LAMSZADEL",
"LEVERKAAS",
"OSSENTONG",
"EENDVOGEL",
"ENTRECOTE",
"FRICASSEE",
"GALANTINE",
"GEHAKTBAL",
"HAMBURGER",
"HOOFDKAAS",
"KARBONADE",
"KATENSPEK",
"KNAKWORST",
"OSSENHAAS",
"PLOKWORST",
"ROASTBEEF",
"ROOKWORST",
"RUNDERLAP",
"RUNDVLEES",
"SCHNITZEL",
"SPARERIBS",
"SUDDERLAP",
"SUKADELAP",
"TOURNEDOS",
"UIERBOORD",
"BLINDEVINK",
"BLOEDWORST",
"EENDENBOUT",
"FRICANDEAU",
"HAZENPEPER",
"KALFSLAPJE",
"LAMSGEHAKT",
"LAMSOESTER",
"LEVERWORST",
"PEKELVLEES",
"PEPERSTEAK",
"SUKADESTUK",
"WILDPASTEI",
"BOERENPATE",
"BRAADVLEES",
"BRAADWORST",
"KIPROLLADE",
"LENDENSTUK",
"OSSENVLEES",
"REEGEBRAAD",
"RUNDERHAAS",
"STOOFLAPJE",
"GEHAKTBROOD",
"LAMSSCHOTEL",
"LEVERPASTEI",
"TONGENWORST",
"VOGELNESTJE",
"CASSELERRIB",
"KALFSGEHAKT",
"KALFSOESTER",
"KASSELERRIB",
"LAMSKOTELET",
"RUNDERLEVER",
"SCHAPENBOUT",
"KALFSROLLADE",
"KIPSCHNITZEL",
"RIBKARBONADE",
"GEHAKTBALLEN",
"KALFSKOTELET",
"RUNDERGEHAKT",
"VARKENSLEVER",
"VARKENSVLEES",
"BOOMSTAMMETJE",
"CHATEAUBRIAND",
"LENDEBIEFSTUK",
"GEHAKTSCHOTEL",
"HAASKARBONADE",
"LAMSKARBONADE",
"RUNDERROLLADE",
"VARKENSGEHAKT",
"VARKENSOESTER",
"KALFSFRICANDEAU",
"WIENERSCHNITZEL",
"PAARDENROOKVLEES",
"STRUISVOGELBIEFSTUK");
private static final List<String> sauzen = Arrays.asList(
"AIOLI",
"ANDALOUSESAUS",
"BEARNAISESAUS",
"BECHAMELSAUS",
"BLACKWELLSAUS",
"BOLOGNESESAUS",
"CHUTNEY",
"CHIMICHURRI",
"COCKTAILSAUS",
"CURRY",
"CURRYKETCHUP",
"DIPSAUS",
"DRESSING",
"FRITESSAUS",
"GUACAMOLE",
"GROENE SAUS",
"HARISSA",
"HOLLANDAISESAUS",
"CHINESE HOISINSAUS",
"HUMMUS",
"JOPPIESAUS",
"KAASSAUS",
"KETJAP",
"KNOFLOOKSAUS",
"MADERASAUS",
"MAMMOETSAUS",
"MANGOCHUTNEY",
"MAYONAISE",
"MOJO",
"MOSTERD",
"OESTERSAUS",
"PESTO",
"PINDASAUS",
"PICCALILLY",
"PIRIPIRI",
"ROUX",
"SALSA",
"SALSA VERDE",
"SAMBAL",
"SAMOERAISAUS",
"SATESAUS",
"ROQUEFORTSAUS",
"STOOFVLEESSAUS",
"STROGANOFFSAUS",
"TABASCO",
"TAHINI",
"TAPENADE",
"TARTAARSAUS",
"TOMATENKETCHUP",
"TOMATENSAUS",
"TOMOTTOSAUS",
"TZATZIKI",
"VINAIGRETTE",
"VISSAUS",
"VLAMMENSAUS",
"VLEESJUS",
"WHISKYSAUS",
"WITTE SAUS",
"WORCESTERSAUS",
"ZULUSAUS");
private static final String GOAL = "818028943427c1157af2aa007a4ab802cb53312a";
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println(str2hash("92.111.40.218 AARDAPPEL GROENTE VLEES SAUS"));
for (String aardappel : aardappels) {
System.out.println("@" + aardappel);
for (String groente : groentes) {
for (String vlees : vlezen) {
for (String saus : sauzen) {
if (str2hash(String.format("92.111.40.218 %s %s %s %s", aardappel, groente, vlees, saus)).equals(GOAL)) {
System.out.println(aardappel);
System.out.println(groente);
System.out.println(vlees);
System.out.println(saus);
}
}
}
}
}
}
private static String str2hash(String s) throws NoSuchAlgorithmException {
// MessageDigest md5 = MessageDigest.getInstance("SHA256");
// md5.update(s.getBytes());
//byte[] digest = md5.digest();
// return String.format("%032x", new BigInteger(1, md5.digest()));
byte[] digest = Ripemd160.getHash(s.getBytes());
return String.format("%032x", new BigInteger(1, digest));
}
}

View File

@@ -0,0 +1,157 @@
/*
* Bitcoin cryptography library
* Copyright (c) Project Nayuki
*
* https://www.nayuki.io/page/bitcoin-cryptography-library
* https://github.com/nayuki/Bitcoin-Cryptography-Library
*/
package hash;
import static java.lang.Integer.rotateLeft;
import java.util.Arrays;
import java.util.Objects;
/**
* Computes the RIPEMD-160 hash of an array of bytes. Not instantiable.
*/
public final class Ripemd160 {
private static final int BLOCK_LEN = 64; // In bytes
/*---- Static functions ----*/
/**
* Computes and returns a 20-byte (160-bit) hash of the specified binary message.
* Each call will return a new byte array object instance.
* @param msg the message to compute the hash of
* @return a 20-byte array representing the message's RIPEMD-160 hash
* @throws NullPointerException if the message is {@code null}
*/
public static byte[] getHash(byte[] msg) {
// Compress whole message blocks
Objects.requireNonNull(msg);
int[] state = {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0};
int off = msg.length / BLOCK_LEN * BLOCK_LEN;
compress(state, msg, off);
// Final blocks, padding, and length
byte[] block = new byte[BLOCK_LEN];
System.arraycopy(msg, off, block, 0, msg.length - off);
off = msg.length % block.length;
block[off] = (byte)0x80;
off++;
if (off + 8 > block.length) {
compress(state, block, block.length);
Arrays.fill(block, (byte)0);
}
long len = (long)msg.length << 3;
for (int i = 0; i < 8; i++)
block[block.length - 8 + i] = (byte)(len >>> (i * 8));
compress(state, block, block.length);
// Int32 array to bytes in little endian
byte[] result = new byte[state.length * 4];
for (int i = 0; i < result.length; i++)
result[i] = (byte)(state[i / 4] >>> (i % 4 * 8));
return result;
}
/*---- Private functions ----*/
private static void compress(int[] state, byte[] blocks, int len) {
if (len % BLOCK_LEN != 0)
throw new IllegalArgumentException();
for (int i = 0; i < len; i += BLOCK_LEN) {
// Message schedule
int[] schedule = new int[16];
for (int j = 0; j < BLOCK_LEN; j++)
schedule[j / 4] |= (blocks[i + j] & 0xFF) << (j % 4 * 8);
// The 80 rounds
int al = state[0], ar = state[0];
int bl = state[1], br = state[1];
int cl = state[2], cr = state[2];
int dl = state[3], dr = state[3];
int el = state[4], er = state[4];
for (int j = 0; j < 80; j++) {
int temp;
temp = rotateLeft(al + f(j, bl, cl, dl) + schedule[RL[j]] + KL[j / 16], SL[j]) + el;
al = el;
el = dl;
dl = rotateLeft(cl, 10);
cl = bl;
bl = temp;
temp = rotateLeft(ar + f(79 - j, br, cr, dr) + schedule[RR[j]] + KR[j / 16], SR[j]) + er;
ar = er;
er = dr;
dr = rotateLeft(cr, 10);
cr = br;
br = temp;
}
int temp = state[1] + cl + dr;
state[1] = state[2] + dl + er;
state[2] = state[3] + el + ar;
state[3] = state[4] + al + br;
state[4] = state[0] + bl + cr;
state[0] = temp;
}
}
private static int f(int i, int x, int y, int z) {
assert 0 <= i && i < 80;
if (i < 16) return x ^ y ^ z;
if (i < 32) return (x & y) | (~x & z);
if (i < 48) return (x | ~y) ^ z;
if (i < 64) return (x & z) | (y & ~z);
return x ^ (y | ~z);
}
/*---- Class constants ----*/
private static final int[] KL = {0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E}; // Round constants for left line
private static final int[] KR = {0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000}; // Round constants for right line
private static final int[] RL = { // Message schedule for left line
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13};
private static final int[] RR = { // Message schedule for right line
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11};
private static final int[] SL = { // Left-rotation for left line
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6};
private static final int[] SR = { // Left-rotation for right line
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11};
/*---- Miscellaneous ----*/
private Ripemd160() {} // Not instantiable
}

View File

@@ -0,0 +1,110 @@
package lingbeek;
public class LingbeekBirthday {
public static void main(String[] args) {
puzzel2();
}
public static void puzzel2() {
String getal = "718221388361140459273845060881935892202463276395185767703202931844979553404160205473165154807716047721360387093977836573461869078903866177517609401066995933056937641429822696075026042708998059408245652909668617234963230159004523361922445118939939425246591630178718041250790393911485448198886968520292419143016465413331107690345523662227756770090925212522853663683587115889316348412482481435850444765959813967931241192116530004379144859416555126822428355054939181176327053123262208427234806432042801083591095061910485620434178736995513637382640868397650863502002563325892782309465718819728901067970753170885152774767519324699535246704946474908543771629786109206017292416056868587459999802797209566648129905865161668379298914522843344050237568463975430764997329482907540684058754472128156434536314672907436279703636811174767549267019613087844658170533886775690229572515615825038183957272309738331226296504597797142318758354872756609064068357178635668850213496389401828224429501408463336955800619499038431637344375259571562615451815648323843802309260072491322883789721070700813804934145478570772226861124445569426679549892906002113429532043386726315834027769929259745736978918570066127364472548758413479889126261314951579365554009611739580747480367882483804688653102749852533773280287182213883611404592738450608819358922024632763951857677032029318449795534041602054731651548077160477213603870939778365734618690789038661775176094010669959330569376414298226960750260427089980594082456529096686172349632301590045233619224451189399394252465916301787180412507903939114854481988869685202924191430164654133311076903455236622277567700909252125228536636835871158893163484124824814358504447659598139679312411921165300043791448594165551268224283550549391811763270531232622084272348064320428010835910950619104856204341787369955136373826408683976508635020025633258927823094657188197289010679707531708851527747675193246995352467049464749085437716297861092060172924160568685874599998027972095666481299058651616683792989145228433440502375684639754307649973294829075406840587544721281564345363146729074362797036368111747675492670196130878446581705338867756902295725156158250381839572723097383312262965045977971423187583548727566090640683571786356688502134963894018282244295014084633369558006194990384316373443752595715626154518156483238438023092600724913228837897210707008138049341454785707722268611244455694266795498929";
getal += "0600211342953204338672631583402776992925974573697891857006612736447254875841347988912626131495157936555400961173958074748036788248380468865310274985253377328028718221388361140459273845060881935892202463276395185767703202931844979553404160205473165154807716047721360387093977836573461869078903866177517609401066995933056937641429822696075026042708998059408245652909668617234963230159004523361922445118939939425246591630178718041250790393911485448198886968520292419143016465413331107690345523662227756770090925212522853663683587115889316348412482481435850444765959813967931241192116530004379144859416555126822428355054939181176327053123262208427234806432042801083591095061910485620434178736995513637382640868397650863502002563325892782309465718819728901067970753170885152774767519324699535246704946474908543771629786109206017292416056868587459999802797209566648129905865161668379298914522843344050237568463975430764997329482907540684058754472128156434536314672907436279703636811174767549267019613087844658170533886775690229572515615825038183957272309738331226296504597797142318758354872756609064068357178635668850213496389401828224429501408463336955800619499038431637344375259571562615451815648323843802309260072491322883789721070700813804934145478570772226861124445569426679549892906002113429532043386726315834027769929259745736978918570066127364472548758413479889126261314951579365554009611739580747480367882483804688653102749852533773280287182213883611404592738450608819358922024632763951857677032029318449795534041602054731651548077160477213603870939778365734618690789038661775176094010669959330569376414298226960750260427089980594082456529096686172349632301590045233619224451189399394252465916301787180412507903939114854481988869685202924191430164654133311076903455236622277567700909252125228536636835871158893163484124824814358504447659598139679312411921165300043791448594165551268224283550549391811763270531232622084272348064320428010835910950619104856204341787369955136373826408683976508635020025633258927823094657188197289010679707531708851527747675193246995352467049464749085437716297861092060172924160568685874599998027972095666481299058651616683792989145228433440502375684639754307649973294829075406840587544721281564345363146729074362797036368111747675492670196130878446581705338867756902295725156158250381839572723097383312262965045977971423187583548727566090640683571786356688502134963894018282";
getal += "2442950140846333695580061949903843163734437525957156261545181564832384380230926007249132288378972107070081380493414547857077222686112444556942667954989290600211342953204338672631583402776992925";
char[] chars = getal.toCharArray();
long max = 0;
for (int i=0; i < (chars.length - 12); i++) {
long prod = 1;
for (int j=0; j<13; j++) {
prod *= (chars[i+j] - '0');
if (prod > max) max = prod;
}
System.out.println(prod);
}
System.out.println(max);
}
public static void puzzel1() {
int[][] grid = {
{34,9,22,97,58,34,9,40,44,74,4,4,7,68,42,32,40,77,83,8},
{49,49,99,40,37,83,38,47,60,87,37,40,98,45,69,48,4,46,62,0},
{83,49,53,75,41,79,34,29,95,73,40,67,45,88,50,5,49,35,56,64},
{42,70,94,25,4,60,33,42,69,24,68,46,3,52,46,73,57,2,56,93},
{22,53,36,73,43,67,65,99,43,92,56,14,22,40,40,28,66,55,35,80},
{24,47,52,60,99,5,44,32,44,74,55,45,68,56,84,20,54,37,32,40},
{52,28,83,28,64,25,67,30,96,58,40,67,49,44,70,66,38,58,64,70},
{67,56,22,68,2,62,32,20,94,65,94,59,65,8,40,93,66,49,94,23},
{24,84,48,4,66,75,99,26,97,37,70,68,96,86,34,88,54,89,65,72},
{23,56,25,9,74,0,76,44,20,44,54,34,50,63,55,97,54,53,55,94},
{68,37,45,28,22,74,53,67,34,93,25,80,4,62,36,34,9,45,46,92},
{36,59,34,42,96,54,53,47,44,48,88,24,30,37,41,24,56,29,84,47},
{86,46,14,77,54,73,89,7,4,41,44,57,41,60,23,48,43,44,37,48},
{39,80,83,68,4,94,47,69,28,75,92,35,86,42,37,77,4,89,44,40},
{4,42,8,85,83,54,99,36,7,97,47,52,36,26,26,79,55,27,98,66},
{88,56,68,87,47,62,20,72,5,46,55,67,46,44,32,52,65,95,45,69},
{4,42,36,75,58,24,59,33,24,94,72,38,8,46,29,52,40,62,76,56},
{20,69,56,43,72,50,25,88,54,62,99,69,82,67,49,84,74,44,56,36},
{20,75,54,29,68,53,90,3,74,53,49,73,48,86,83,36,25,47,4,14},
{3,70,44,73,85,43,44,69,36,82,55,48,63,15,42,3,99,29,67,48}
};
int max = 0, result;
for (int row = 0; row < grid.length; row++ ) {
for (int col = 0; col < grid[row].length; col++) {
if (col < 17) {
result = grid[row][col] * grid [row][col+1] * grid[row][col+2] * grid[row][col+3];
if (result > max) {
System.out.println("["+row+"]["+col+"] 1");
max = result;
}
}
if (row < 17) {
result = grid[row][col] * grid [row+1][col] * grid[row+2][col] * grid[row+3][col];
if (result > max) {
System.out.println("["+row+"]["+col+"] 2 " + grid[row][col]);
max = result;
}
}
if (col < 17 && row > 2) {
result = grid[row][col] * grid [row-1][col+1] * grid[row-2][col+2] * grid[row-3][col+3];
if (result > max) {
System.out.println("["+row+"]["+col+"] 3");
max = result;
}
}
if (col < 17 && row < 17) {
result = grid[row][col] * grid [row+1][col+1] * grid[row+2][col+2] * grid[row+3][col+3];
if (result > max) {
System.out.println("["+row+"]["+col+"] 4");
max = result;
}
}
if (col > 2 && row < 17) {
result = grid[row][col] * grid [row+1][col-1] * grid[row+2][col-2] * grid[row+3][col-3];
if (result > max) {
System.out.println("["+row+"]["+col+"] 5");
max = result;
}
}
if (col > 2 && row > 2) {
result = grid[row][col] * grid [row-1][col-1] * grid[row-2][col-2] * grid[row-3][col-3];
if (result > max) {
System.out.println("["+row+"]["+col+"]");
max = result;
}
}
//System.out.print(grid[row][col]);
}
//System.out.println();
}
System.out.println(max);
}
}

View File

@@ -0,0 +1,196 @@
package logistics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
//interface Node {
// boolean visited = false;
// void addNode(Node node, int distance);
// Map<Node, Integer> getNodes();
// String getName();
//}
abstract class Node {
private String name;
private Map<Node, Integer> connectedNodes = new HashMap<>();
private boolean visited;
public void addNode(Node node, int distance) {
connectedNodes.put(node, distance);
}
public Map<Node, Integer> getNodes() {
return connectedNodes;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
void enter(Car car) {
this.visited = true;
};
}
class Stop extends Node {
Stop(String name) {
this.setName(name);
}
}
class GasStation extends Node {
private int gasAdded;
GasStation(String name, int gasAdded) {
this.setName(name);
this.gasAdded = gasAdded;
}
@Override
public void enter(Car car) {
super.enter(car);
car.addGas(this.gasAdded);
}
}
class Car {
private int fuel;
private int distance = 0;
private Node position;
public void addGas(int gasAdded) {
this.fuel += gasAdded;
}
public void driveTo(Node node, int distance) {
this.position = node;
this.fuel -= distance;
this.distance += distance;
node.enter(this);
}
public int getFuel() {
return fuel;
}
public void setFuel(int fuel) {
this.fuel = fuel;
}
public Node getPosition() {
return position;
}
public void setPosition(Node position) {
this.position = position;
}
public int getDistance() {
return distance;
}
}
public class LogisticsPuzzle {
static Car car = new Car();
static List<Node> allNodes;
public static void main(String[] args) {
car.setFuel(30);
// Node s1 = new Stop("s1");
// Node s2 = new Stop("s2");
// Node s3 = new Stop("s3");
// Node g1 = new GasStation("g1", 30);
// s1.addNode(s2, 10);
// s1.addNode(s3, 5);
// s2.addNode(s3, 20);
// s3.addNode(s1, 5);
// s3.addNode(g1, 10);
// g1.addNode(s2, 12);
Node node;
for (Integer n = 1; n <= 10; n++) {
if (new Random().nextInt(5) == 0) {
node = new GasStation(n.toString(), 20 + new Random().nextInt(25));
} else {
node = new Stop(n.toString());
}
allNodes.add(node);
}
//allNodes = Arrays.asList(new Node[] { s1, s2, s3, g1} );
// car.driveTo(s1, 0);
System.out.println("Position Fuel Dist Nodes");
printState();
do {
Map<Node,Integer> nodes = car.getPosition().getNodes();
Iterator<Node> iterator = nodes.keySet().iterator();
while (iterator.hasNext()) {
/*Node*/ node = iterator.next();
if (nodes.get(node) > car.getFuel()) {
iterator.remove();
}
}
if (nodes.isEmpty()) {
System.out.println("Geen benzine meer.");
break;
}
Random random = new Random();
List<Node> keys = new ArrayList<Node>(nodes.keySet());
Node nextStop = keys.get( random.nextInt(keys.size()) );
int distance = nodes.get(nextStop);
car.driveTo(nextStop, distance);
printState();
if (allNodesVisited()) {
System.out.println("Klaar");
break;
}
} while (true);
}
static boolean allNodesVisited() {
boolean allVisited = true;
for (Node node : allNodes) {
// System.out.println(node.getName() + node.isVisited());
allVisited = allVisited && node.isVisited();
}
return allVisited;
}
static void printState() {
System.out.print(car.getPosition().getName() + " " + car.getFuel() + " " + car.getDistance() + " ");
for (Node node : car.getPosition().getNodes().keySet()) {
System.out.print(node.getName() + " ");
}
System.out.println();
};
}

View File

@@ -0,0 +1,132 @@
package numbersquare;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
enum Direction {
UP, LEFT, DOWN, RIGHT;
}
public class NumberSquarePuzzle {
public static final int SIZE = 7;
public static void main(String[] args) {
int [][] square = {
// {4,2,2,3,3},
// {2,2,2,2,2},
// {3,2,2,2,2},
// {1,2,3,2,3},
// {3,2,2,2,0}
{6,3,2,4,6,2,5},
{3,5,2,4,4,4,1},
{3,3,2,3,3,4,2},
{3,4,1,2,2,5,3},
{4,4,4,2,3,2,4},
{2,5,4,2,3,2,5},
{3,5,2,1,4,4,0}
};
// 6 (0,0) => 3 (6,0)
// 3 (6,0) => 1 (6,3)
// 1 (6,3) => 2 (6,2)
// 2 (6,2) => 4 (4,2)
// 4 (4,2) => 2 (0,2)
// 2 (0,2) => 2 (2,2)
// 2 (2,2) => 3 (2,0)
// 3 (2,0) => 2 (5,0)
// 2 (5,0) => 4 (5,2)
// 4 (5,2) => 2 (1,2)
// 2 (1,2) => 4 (1,4)
// 4 (1,4) => 3 (1,0)
// 3 (1,0) => 4 (4,0)
// 4 (4,0) => 3 (4,4)
// 3 (4,4) => 4 (4,1)
// 4 (4,1) => 2 (4,5)
// 2 (4,5) => 4 (6,5)
// 4 (6,5) => 5 (6,1)
// 5 (6,1) => 0 (6,6)
// 6 (0,0) => 3 (6,0)
// 3 (6,0) => 1 (6,3)
// 1 (6,3) => 2 (6,2)
// 2 (6,2) => 4 (4,2)
// 4 (4,2) => 2 (0,2)
// 2 (0,2) => 2 (2,2)
// 2 (2,2) => 3 (2,0)
// 3 (2,0) => 2 (5,0)
// 2 (5,0) => 4 (5,2)
// 4 (5,2) => 2 (1,2)
// 2 (1,2) => 3 (1,0)
// 3 (1,0) => 4 (4,0)
// 4 (4,0) => 3 (4,4)
// 3 (4,4) => 4 (4,1)
// 4 (4,1) => 2 (4,5)
// 2 (4,5) => 4 (2,5)
// 4 (2,5) => 4 (6,5)
// 4 (6,5) => 5 (6,1)
// 5 (6,1) => 0 (6,6)
boolean [][] visited;
int posRow;
int posCol;
int curVal;
int attempt = 0;
do {
attempt++;
posRow = 0;
posCol = 0;
List<Direction> directions;
visited = new boolean[SIZE][SIZE];
do {
directions = new ArrayList<>();
visited[posRow][posCol] = true;
curVal = square[posRow][posCol];
if ((posCol + curVal) < SIZE) {
directions.add(Direction.RIGHT);
}
if ((posCol - curVal) >= 0) {
directions.add(Direction.LEFT);
}
if ((posRow + curVal) < SIZE) {
directions.add(Direction.DOWN);
}
if ((posRow - curVal) >= 0) {
directions.add(Direction.UP);
}
Direction direction = directions.get(new Random().nextInt(directions.size()));
System.out.print(curVal + " (" + posRow + "," + posCol + ") => ");
if (direction == Direction.RIGHT) {
posCol += curVal;
}
if (direction == Direction.LEFT) {
posCol -= curVal;
}
if (direction == Direction.DOWN) {
posRow += curVal;
}
if (direction == Direction.UP) {
posRow -= curVal;
}
System.out.println(square[posRow][posCol] + " (" + posRow + "," + posCol + ")");
if (visited[posRow][posCol]) {
System.out.println("Visited " + attempt);
break;
}
} while (posRow != (SIZE - 1) || posCol != (SIZE - 1));
} while (posRow != (SIZE - 1) || posCol != (SIZE - 1));
}
}

View File

@@ -0,0 +1,61 @@
package polygons;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiPolygon;
import org.wololo.geojson.Feature;
import org.wololo.geojson.FeatureCollection;
import org.wololo.jts2geojson.GeoJSONReader;
import java.io.*;
public class PolygonConverter {
private static final String prefix = "D:\\Nextcloud\\Geocaching\\polygons\\";
private static final String outputFolder = prefix + "new\\";
private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
private static final GeoJSONReader reader = new GeoJSONReader();
private static final boolean USE_NUMERIC_FILENAMES = true;
private static int FILE_COUNTER = 0;
public static void main(String[] args) throws IOException {
FileInputStream inputStream = new FileInputStream(prefix + "russia_counties.GeoJson");
FeatureCollection featureCollection = objectMapper.readValue(inputStream, FeatureCollection.class);
for (Feature feature : featureCollection.getFeatures()) {
String baseName = (String) feature.getProperties().get("name");
MultiPolygon multiPolygon = (MultiPolygon) reader.read(feature.getGeometry());
if (multiPolygon.getNumGeometries() > 1) {
for (int geomNr = 0; geomNr < multiPolygon.getNumGeometries(); geomNr++) {
Geometry geometry = multiPolygon.getGeometryN(geomNr);
String fileName = (USE_NUMERIC_FILENAMES ? Integer.toString(++FILE_COUNTER) : baseName + "_" + (geomNr + 1)) + ".txt";
processPolygon(geometry, baseName, fileName);
}
} else {
Geometry geometry = multiPolygon.getGeometryN(0);
String fileName = (USE_NUMERIC_FILENAMES ? Integer.toString(++FILE_COUNTER) : baseName) + ".txt";
processPolygon(geometry, baseName, fileName);
}
}
}
private static void processPolygon(Geometry geometry, String name, String fileName) throws IOException {
System.out.println(fileName);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFolder + fileName), "utf-8"))) {
writer.write("# GsakName=" + name + "\n" +
"# This Country polygon is based on data (c) OpenStreetMap contributors\n" +
"# The OpenStreetMap data is made available under the Open Database License, see http://www.openstreetmap.org/copyright\n" +
"# This polygon file is made available under the same Open Database License: http://opendatacommons.org/licenses/odbl/1.0/.\n");
// Geometry reducedPolygon = reducePolygon(polygon);
//geometry.getBoundary()
for (Coordinate coordinate : geometry.getCoordinates()) {
writer.write(coordinate.y + "," + coordinate.x);
writer.write("\n");
}
}
}
}

View File

@@ -0,0 +1,76 @@
package setGame;
class Card {
P1 p1;
P2 p2;
P3 p3;
P4 p4;
P5 p5;
public P1 getP1() {
return p1;
}
public void setP1(P1 p1) {
this.p1 = p1;
}
public P2 getP2() {
return p2;
}
public void setP2(P2 p2) {
this.p2 = p2;
}
public P3 getP3() {
return p3;
}
public void setP3(P3 p3) {
this.p3 = p3;
}
public P4 getP4() {
return p4;
}
public void setP4(P4 p4) {
this.p4 = p4;
}
public P5 getP5() {
return p5;
}
public void setP5(P5 p5) {
this.p5 = p5;
}
public Card(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
super();
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
this.p5 = p5;
}
@Override
public boolean equals(Object o) {
Card that = (Card) o;
return this.p1 == that.p1 && this.p2 == that.p2 && this.p3 == that.p3 && this.p4 == that.p4 && this.p5 == that.p5;
}
@Override
public int hashCode() {
return 1;
}
@Override
public String toString() {
return p1 + " " + p2 + " " + p3 + " " + p4 + " " + p5;
}
public static Card randomCard() {
return new Card(P1.randomP1(), P2.randomP2(), P3.randomP3(), P4.randomP4(), P5.randomP5());
}
}

View File

@@ -0,0 +1,18 @@
package setGame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
enum P1 {
A1, A2, A3, A4, A5;
private static final List<P1> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static P1 randomP1() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}

View File

@@ -0,0 +1,18 @@
package setGame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
enum P2 {
B1, B2, B3, B4, B5;
private static final List<P2> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static P2 randomP2() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}

View File

@@ -0,0 +1,18 @@
package setGame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
enum P3 {
C1, C2, C3, C4, C5;
private static final List<P3> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static P3 randomP3() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}

View File

@@ -0,0 +1,18 @@
package setGame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
enum P4 {
D1, D2, D3, D4, D5;
private static final List<P4> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static P4 randomP4() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}

View File

@@ -0,0 +1,18 @@
package setGame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
enum P5 {
E1, E2, E3, E4, E5;
private static final List<P5> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static P5 randomP5() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}

View File

@@ -0,0 +1,14 @@
package setGame;
import java.util.List;
import java.util.Set;
class SearchResult {
public Set<Card> cards;
public List<Set<Card>> sets;
public SearchResult(Set<Card> cards, List<Set<Card>> sets) {
super();
this.cards = cards;
this.sets = sets;
}
}

View File

@@ -0,0 +1,232 @@
package setGame;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.Timer;
import java.util.HashSet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.ByteBuffer;
import java.util.ArrayList;
public class SetGame {
private static final int SET_SIZE = 5;
public static void main(String[] args) {
SearchResult sr;
int size;
int record = 85;
do {
sr = tryRandom();
size = sr.cards.size();
if (size >= record && sr.sets.size() == 1) {
record = size;
try {
beep(3000, 200);
} catch (InterruptedException | LineUnavailableException e) {
e.printStackTrace();
}
System.out.println(size + " " + sr.sets.size());
for (Card card : sr.cards) {
System.out.println(card);
}
// System.out.println("Met " + sr.sets.size() + " sets.");
System.out.println(sr.sets);
}
} while (true);
}
private static SearchResult tryRandom() {
Set<Card> cards = new HashSet<>();
// int sets = 0;
do {
cards.add(Card.randomCard());
} while (cards.size() < SET_SIZE);
do {
cards.add(Card.randomCard());
List<Set<Card>> sets = sets(cards, false);
if (sets.size() > 0) {
return new SearchResult(cards, sets);
}
} while (true);
}
private static List<Set<Card>> sets(Set<Card> cards, boolean debug) {
List<Set<Card>> sets = new ArrayList<>();
for (int i = 0; i < cards.size() - 4; i++) {
for (int j = i + 1; j < cards.size() - 3; j++) {
for (int k = j + 1; k < cards.size() - 2; k++) {
for (int l = k + 1; l < cards.size() - 1; l++) {
for (int m = l + 1; m < cards.size(); m++) {
boolean result = false;
List<Card> cardsList = new ArrayList<>(cards);
Set<P1> p1s = new HashSet<P1>();
p1s.add(cardsList.get(i).getP1());
p1s.add(cardsList.get(j).getP1());
p1s.add(cardsList.get(k).getP1());
p1s.add(cardsList.get(l).getP1());
p1s.add(cardsList.get(m).getP1());
Set<P2> p2s = new HashSet<P2>();
p2s.add(cardsList.get(i).getP2());
p2s.add(cardsList.get(j).getP2());
p2s.add(cardsList.get(k).getP2());
p2s.add(cardsList.get(l).getP2());
p2s.add(cardsList.get(m).getP2());
Set<P3> p3s = new HashSet<P3>();
p3s.add(cardsList.get(i).getP3());
p3s.add(cardsList.get(j).getP3());
p3s.add(cardsList.get(k).getP3());
p3s.add(cardsList.get(l).getP3());
p3s.add(cardsList.get(m).getP3());
Set<P4> p4s = new HashSet<P4>();
p4s.add(cardsList.get(i).getP4());
p4s.add(cardsList.get(j).getP4());
p4s.add(cardsList.get(k).getP4());
p4s.add(cardsList.get(l).getP4());
p4s.add(cardsList.get(m).getP4());
Set<P5> p5s = new HashSet<P5>();
p5s.add(cardsList.get(i).getP5());
p5s.add(cardsList.get(j).getP5());
p5s.add(cardsList.get(k).getP5());
p5s.add(cardsList.get(l).getP5());
p5s.add(cardsList.get(m).getP5());
result |= (p1s.size() >= 2 && p1s.size() <= (SET_SIZE - 1));
result |= (p2s.size() >= 2 && p2s.size() <= (SET_SIZE - 1));
result |= (p3s.size() >= 2 && p3s.size() <= (SET_SIZE - 1));
result |= (p4s.size() >= 2 && p4s.size() <= (SET_SIZE - 1));
result |= (p5s.size() >= 2 && p5s.size() <= (SET_SIZE - 1));
/* System.out.println("Kaarten " + i+","+j+","+k+","+l+":");
System.out.println(cardsList.get(i));
System.out.println(cardsList.get(j));
System.out.println(cardsList.get(k));
System.out.println(cardsList.get(l));
System.out.println("Verschillende P1s: " + p1s.size());
System.out.println("Verschillende P2s: " + p2s.size());
System.out.println("Verschillende P3s: " + p3s.size());
System.out.println("Verschillende P4s: " + p4s.size());
*/
if (result == false) {
sets.add(Stream.of(cardsList.get(i), cardsList.get(j), cardsList.get(k), cardsList.get(l), cardsList.get(m)).collect(Collectors.toSet()));
if (debug) {
System.out.println(cardsList.get(i) + " " + i);
System.out.println(cardsList.get(j) + " " + j);
System.out.println(cardsList.get(k) + " " + k);
System.out.println(cardsList.get(l) + " " + l);
System.out.println(cardsList.get(m) + " " + m);
System.out.println();
}
}
}
}
}
}
}
return sets;
}
public static void beep(double freq, final double millis) throws InterruptedException, LineUnavailableException {
final Clip clip = AudioSystem.getClip();
/**
* AudioFormat of the reclieved clip. Probably you can alter it
* someway choosing proper Line.
*/
AudioFormat af = clip.getFormat();
/**
* We assume that encoding uses signed shorts. Probably we could
* make this code more generic but who cares.
*/
if (af.getEncoding() != AudioFormat.Encoding.PCM_SIGNED){
throw new UnsupportedOperationException("Unknown encoding");
}
if (af.getSampleSizeInBits() != 16) {
System.err.println("Weird sample size. Dunno what to do with it.");
return;
}
/**
* Number of bytes in a single frame
*/
int bytesPerFrame = af.getFrameSize();
/**
* Number of frames per second
*/
double fps = af.getFrameRate();
/**
* Number of frames during the clip .
*/
int frames = (int)(fps * (millis / 1000));
/**
* Data
*/
ByteBuffer data = ByteBuffer.allocate(frames * bytesPerFrame);
/**
* We will emit sinus, which needs to be scaled so it has proper
* frequency --- here is the scaling factor.
*/
double freqFactor = (Math.PI / 2) * freq / fps;
/**
* This sinus must also be scaled so it fills short.
*/
double ampFactor = Short.MAX_VALUE;
short sample;
for (int frame = 0; frame < frames; frame++) {
sample = (short) (ampFactor * Math.sin(frame * freqFactor));
data.putShort(sample);
}
clip.open(af, data.array(), 0, data.position());
// This is so Clip releases its data line when done. Otherwise at 32 clips it breaks.
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.START) {
Timer t = new Timer((int)millis + 1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clip.close();
}
});
t.setRepeats(false);
t.start();
}
}
});
clip.start();
Thread.sleep((long)millis);
}
}

View File

@@ -0,0 +1,81 @@
package stamps;
import org.apache.commons.lang3.RandomUtils;
import com.google.common.collect.Sets;
import java.util.*;
public class Stamps {
private static final int SUM = 100;
private static final int CHOOSE = 5;
private static final int UPPER_STAMP = 36;
private static final int LOWER_STAMP = 4;
private static final int TOTAL_STAMPS = 5;
public static void main(String[] args) {
for (int j = 0; j < 1000; j++) {
TreeSet<Integer> stamps = null;
for (int i = 0; i < 1000; i++) {
stamps = poging();
if (stamps != null) break;
}
SortedMap<Integer, Integer> sums = new TreeMap<>();
int minSum = 1000;
int maxSum = 0;
for (Set<Integer> set : Sets.combinations(stamps, CHOOSE)) {
int sumSet = set.stream().mapToInt(Integer::intValue).sum();
int sum = sums.containsKey(sumSet) ? sums.get(sumSet) : 0;
sums.put(sumSet, sum + 1);
}
int sumsBeforeGoal = 0;
int sumsAfterGoal = 0;
for (int s : sums.keySet()) {
if (s < SUM) sumsBeforeGoal += sums.get(s);
if (s > SUM) sumsAfterGoal += sums.get(s);
}
if (sumsBeforeGoal > 100 && sumsAfterGoal > 100) {
System.out.println(stamps);
System.out.println(sumsBeforeGoal + " << " + SUM + " >> " + sumsAfterGoal);
}
}
}
private static TreeSet<Integer> poging() {
var stamps = Sets.newHashSet(8, 12, 22, 23, 35);
var triedStamps = new HashSet<Integer>();
for (int i = 0; i < TOTAL_STAMPS; i++) {
int newStamp;
do {
if (triedStamps.size() == (UPPER_STAMP - LOWER_STAMP + 1)) {
// System.out.println("Mislukt");
return null;
}
newStamp = RandomUtils.nextInt(LOWER_STAMP, UPPER_STAMP + 1);
triedStamps.add(newStamp);
} while (stamps.contains(newStamp) || !testNewStamp(stamps, newStamp));
stamps.add(newStamp);
// System.out.println(newStamp + " toegevoegd.");
}
TreeSet<Integer> sortStamps = new TreeSet<>(stamps);
return sortStamps;
}
private static boolean testNewStamp(Set<Integer> stamps, int newStamp) {
for (Set<Integer> set : Sets.combinations(stamps, CHOOSE - 1)) {
if (set.stream().mapToInt(Integer::intValue).sum() + newStamp == SUM) {
// System.out.println(newStamp + " valt af.");
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,99 @@
package stamps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.math3.util.CombinatoricsUtils;
import java.util.*;
public class Stamps2 {
private static final int SUM = 100;
private static final int CHOOSE = 6;
private static final int UPPER_STAMP = 40;
private static final int LOWER_STAMP = 2;
private static final int TOTAL_STAMPS = 11;
private static final int THRESHOLD = (int) ((CombinatoricsUtils.binomialCoefficient(TOTAL_STAMPS, CHOOSE) / 2) * 0.5);
public static void main(String[] args) {
outerloop:
for (int j = 0; j < 50000000; j++) {
TreeSet<Integer> stamps = null;
stamps = poging();
SortedMap<Integer, Integer> sums = new TreeMap<>();
int minSum = 1000;
int maxSum = 0;
Set<Integer> solutionSet = null;
for (Set<Integer> set : Sets.combinations(stamps, CHOOSE)) {
int sumSet = set.stream().mapToInt(Integer::intValue).sum();
int sum = sums.containsKey(sumSet) ? sums.get(sumSet) : 0;
sums.put(sumSet, sum + 1);
if (sumSet == SUM) {
solutionSet = new TreeSet<Integer>(set);
}
}
int sumsBeforeGoal = 0;
int sumsAfterGoal = 0;
for (int s : sums.keySet()) {
if (s < SUM) sumsBeforeGoal += sums.get(s);
if (s > SUM) sumsAfterGoal += sums.get(s);
}
boolean success = true;
if (success && sumsBeforeGoal > THRESHOLD && sumsAfterGoal > THRESHOLD && sums.containsKey(SUM) && sums.get(SUM) == 1) {
for (int choose = 1; choose <= TOTAL_STAMPS; choose++) {
if (choose == CHOOSE) {
continue;
}
for (Set<Integer> set : Sets.combinations(stamps, choose)) {
int sumSet = set.stream().mapToInt(Integer::intValue).sum();
if (sumSet == SUM) {
success = false;
// System.out.println(set + " spoils the party.");
continue outerloop;
}
}
}
System.out.println(stamps);
System.out.println(sumsBeforeGoal + " << " + SUM + " >> " + sumsAfterGoal);
System.out.println("Solution: " + solutionSet);
System.out.println();
}
}
}
//private static int threshold()
private static TreeSet<Integer> poging() {
var stamps = new HashSet<Integer>();
var triedStamps = new HashSet<Integer>();
for (int i = 0; i < TOTAL_STAMPS; i++) {
int newStamp;
do {
newStamp = RandomUtils.nextInt(LOWER_STAMP, UPPER_STAMP + 1);
triedStamps.add(newStamp);
} while (stamps.contains(newStamp));
stamps.add(newStamp);
}
TreeSet<Integer> sortStamps = new TreeSet<>(stamps);
return sortStamps;
}
}

View File

@@ -0,0 +1,47 @@
/*
* City.java
* Models a city
*/
package tsp;
public class City {
int x;
int y;
// Constructs a randomly placed city
public City(){
this.x = (int)(Math.random()*200);
this.y = (int)(Math.random()*200);
}
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
// Gets city's x coordinate
public int getX(){
return this.x;
}
// Gets city's y coordinate
public int getY(){
return this.y;
}
// Gets the distance to given city
public double distanceTo(City city){
int xDistance = Math.abs(getX() - city.getX());
int yDistance = Math.abs(getY() - city.getY());
double distance = Math.sqrt( (xDistance*xDistance) + (yDistance*yDistance) );
return distance;
}
@Override
public String toString(){
return getX()+", "+getY();
}
}

120
src/main/java/tsp/GA.java Normal file
View File

@@ -0,0 +1,120 @@
/*
* GA.java
* Manages algorithms for evolving population
*/
package tsp;
public class GA {
/* GA parameters */
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
// Evolves a population over one generation
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.populationSize(), false);
// Keep our best individual if elitism is enabled
int elitismOffset = 0;
if (elitism) {
newPopulation.saveTour(0, pop.getFittest());
elitismOffset = 1;
}
// Crossover population
// Loop over the new population's size and create individuals from
// Current population
for (int i = elitismOffset; i < newPopulation.populationSize(); i++) {
// Select parents
Tour parent1 = tournamentSelection(pop);
Tour parent2 = tournamentSelection(pop);
// Crossover parents
Tour child = crossover(parent1, parent2);
// Add child to new population
newPopulation.saveTour(i, child);
}
// Mutate the new population a bit to add some new genetic material
for (int i = elitismOffset; i < newPopulation.populationSize(); i++) {
mutate(newPopulation.getTour(i));
}
return newPopulation;
}
// Applies crossover to a set of parents and creates offspring
public static Tour crossover(Tour parent1, Tour parent2) {
// Create new child tour
Tour child = new Tour();
// Get start and end sub tour positions for parent1's tour
int startPos = (int) (Math.random() * parent1.tourSize());
int endPos = (int) (Math.random() * parent1.tourSize());
// Loop and add the sub tour from parent1 to our child
for (int i = 0; i < child.tourSize(); i++) {
// If our start position is less than the end position
if (startPos < endPos && i > startPos && i < endPos) {
child.setCity(i, parent1.getCity(i));
} // If our start position is larger
else if (startPos > endPos) {
if (!(i < startPos && i > endPos)) {
child.setCity(i, parent1.getCity(i));
}
}
}
// Loop through parent2's city tour
for (int i = 0; i < parent2.tourSize(); i++) {
// If child doesn't have the city add it
if (!child.containsCity(parent2.getCity(i))) {
// Loop to find a spare position in the child's tour
for (int ii = 0; ii < child.tourSize(); ii++) {
// Spare position found, add city
if (child.getCity(ii) == null) {
child.setCity(ii, parent2.getCity(i));
break;
}
}
}
}
return child;
}
// Mutate a tour using swap mutation
private static void mutate(Tour tour) {
// Loop through tour cities
for(int tourPos1=0; tourPos1 < tour.tourSize(); tourPos1++){
// Apply mutation rate
if(Math.random() < mutationRate){
// Get a second random position in the tour
int tourPos2 = (int) (tour.tourSize() * Math.random());
// Get the cities at target position in tour
City city1 = tour.getCity(tourPos1);
City city2 = tour.getCity(tourPos2);
// Swap them around
tour.setCity(tourPos2, city1);
tour.setCity(tourPos1, city2);
}
}
}
// Selects candidate tour for crossover
private static Tour tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random candidate tour and
// add it
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.populationSize());
tournament.saveTour(i, pop.getTour(randomId));
}
// Get the fittest tour
Tour fittest = tournament.getFittest();
return fittest;
}
}

View File

@@ -0,0 +1,53 @@
/*
* Population.java
* Manages a population of candidate tours
*/
package tsp;
public class Population {
// Holds population of tours
Tour[] tours;
// Construct a population
public Population(int populationSize, boolean initialise) {
tours = new Tour[populationSize];
// If we need to initialise a population of tours do so
if (initialise) {
// Loop and create individuals
for (int i = 0; i < populationSize(); i++) {
Tour newTour = new Tour();
newTour.generateIndividual();
saveTour(i, newTour);
}
}
}
// Saves a tour
public void saveTour(int index, Tour tour) {
tours[index] = tour;
}
// Gets a tour from population
public Tour getTour(int index) {
return tours[index];
}
// Gets the best tour in the population
public Tour getFittest() {
Tour fittest = tours[0];
// Loop through individuals to find fittest
for (int i = 1; i < populationSize(); i++) {
if (fittest.getFitness() <= getTour(i).getFitness()) {
fittest = getTour(i);
}
}
return fittest;
}
// Gets population size
public int populationSize() {
return tours.length;
}
}

View File

@@ -0,0 +1,71 @@
/*
* TSP_GA.java
* Create a tour and evolve a solution
*/
package tsp;
public class TSP_GA {
public static void main(String[] args) {
// Create and add our cities
City city = new City(60, 200);
TourManager.addCity(city);
City city2 = new City(180, 200);
TourManager.addCity(city2);
City city3 = new City(80, 180);
TourManager.addCity(city3);
City city4 = new City(140, 180);
TourManager.addCity(city4);
City city5 = new City(20, 160);
TourManager.addCity(city5);
City city6 = new City(100, 160);
TourManager.addCity(city6);
City city7 = new City(200, 160);
TourManager.addCity(city7);
City city8 = new City(140, 140);
TourManager.addCity(city8);
City city9 = new City(40, 120);
TourManager.addCity(city9);
City city10 = new City(100, 120);
TourManager.addCity(city10);
City city11 = new City(180, 100);
TourManager.addCity(city11);
City city12 = new City(60, 80);
TourManager.addCity(city12);
City city13 = new City(120, 80);
TourManager.addCity(city13);
City city14 = new City(180, 60);
TourManager.addCity(city14);
City city15 = new City(20, 40);
TourManager.addCity(city15);
City city16 = new City(100, 40);
TourManager.addCity(city16);
City city17 = new City(200, 40);
TourManager.addCity(city17);
City city18 = new City(20, 20);
TourManager.addCity(city18);
City city19 = new City(60, 20);
TourManager.addCity(city19);
City city20 = new City(160, 20);
TourManager.addCity(city20);
// Initialize population
Population pop = new Population(50, true);
System.out.println("Initial distance: " + pop.getFittest().getDistance());
// Evolve population for 100 generations
pop = GA.evolvePopulation(pop);
for (int i = 0; i < 10000; i++) {
pop = GA.evolvePopulation(pop);
}
// Print final results
System.out.println("Finished");
System.out.println("Final distance: " + pop.getFittest().getDistance());
System.out.println("Solution:");
System.out.println(pop.getFittest());
}
}

105
src/main/java/tsp/Tour.java Normal file
View File

@@ -0,0 +1,105 @@
/*
* Tour.java
* Stores a candidate tour
*/
package tsp;
import java.util.ArrayList;
import java.util.Collections;
public class Tour{
// Holds our tour of cities
private ArrayList tour = new ArrayList<City>();
// Cache
private double fitness = 0;
private int distance = 0;
// Constructs a blank tour
public Tour(){
for (int i = 0; i < TourManager.numberOfCities(); i++) {
tour.add(null);
}
}
public Tour(ArrayList tour){
this.tour = tour;
}
// Creates a random individual
public void generateIndividual() {
// Loop through all our destination cities and add them to our tour
for (int cityIndex = 0; cityIndex < TourManager.numberOfCities(); cityIndex++) {
setCity(cityIndex, TourManager.getCity(cityIndex));
}
// Randomly reorder the tour
Collections.shuffle(tour);
}
// Gets a city from the tour
public City getCity(int tourPosition) {
return (City)tour.get(tourPosition);
}
// Sets a city in a certain position within a tour
public void setCity(int tourPosition, City city) {
tour.set(tourPosition, city);
// If the tours been altered we need to reset the fitness and distance
fitness = 0;
distance = 0;
}
// Gets the tours fitness
public double getFitness() {
if (fitness == 0) {
fitness = 1/(double)getDistance();
}
return fitness;
}
// Gets the total distance of the tour
public int getDistance(){
if (distance == 0) {
int tourDistance = 0;
// Loop through our tour's cities
for (int cityIndex=0; cityIndex < tourSize(); cityIndex++) {
// Get city we're travelling from
City fromCity = getCity(cityIndex);
// City we're travelling to
City destinationCity;
// Check we're not on our tour's last city, if we are set our
// tour's final destination city to our starting city
if(cityIndex+1 < tourSize()){
destinationCity = getCity(cityIndex+1);
}
else{
destinationCity = getCity(0);
}
// Get the distance between the two cities
tourDistance += fromCity.distanceTo(destinationCity);
}
distance = tourDistance;
}
return distance;
}
// Get number of cities on our tour
public int tourSize() {
return tour.size();
}
// Check if the tour contains a city
public boolean containsCity(City city){
return tour.contains(city);
}
@Override
public String toString() {
String geneString = "|";
for (int i = 0; i < tourSize(); i++) {
geneString += getCity(i)+"|";
}
return geneString;
}
}

View File

@@ -0,0 +1,29 @@
/*
* TourManager.java
* Holds the cities of a tour
*/
package tsp;
import java.util.ArrayList;
public class TourManager {
// Holds our cities
private static ArrayList destinationCities = new ArrayList<City>();
// Adds a destination city
public static void addCity(City city) {
destinationCities.add(city);
}
// Get a city
public static City getCity(int index){
return (City)destinationCities.get(index);
}
// Get the number of destination cities
public static int numberOfCities(){
return destinationCities.size();
}
}