我想帮助一个随机函数为我的代码工作。我正在为一个学校项目研究爬山算法。该算法只有我不知道如何让它添加随机产品(它需要访问的位置)。
这是主要课程。如果我必须提供,那么随时可以问我。
package hillclimbing;
import java.util.ArrayList;
import java.util.Arrays;
public class Driver {
private ArrayList<Product> initialProducts = new ArrayList<Product>(Arrays.asList(
new Product("Tandpasta", 42.3601, -71.0589),
new Product("Banaan", 29.7064, -95.3698),
new Product("Kaas", 30.2672, -97.7431),
new Product("Laptop", 37.7749, -122.4194),
new Product("Vliegtuig", 39.0000, -104.0000),
new Product("Robot", 34.0000, -118.0000),
new Product("Magazijn", 41.0000, -87.0000),
new Product("Kubus", 40.0000, -74.0000),
new Product("Doos", 32.0000, -96.0000),
new Product("Lego", 47.0000, -122.0000)
));
public static void main(String[] args) {
Driver driver = new Driver();
Route route = new Route(driver.initialProducts);
printHeading(route);
System.out.print(route + " | " + route.getTotalDistance());
new HillClimbing().findShortestRoute(route);
}
public static void printHeading(Route route){
String headingColumn1 = "Route";
String remainingHeadingColumns = "Distance (in miles) | Compare adjacent to current route";
int productNamesLength = 0;
for(int x = 0; x < route.getProducts().size(); x++) productNamesLength += route.getProducts().get(x).getName().length();
int arrayLength = productNamesLength + route.getProducts().size()*2;
int partialLength = (arrayLength - headingColumn1.length()/2);
for(int x = 0; x < partialLength; x++)System.out.print(" ");
System.out.print(headingColumn1);
for(int x = 0; x < partialLength; x++)System.out.print(" ");
if((arrayLength % 2) == 0)System.out.print(" ");
System.out.println(" | " + remainingHeadingColumns);
productNamesLength += remainingHeadingColumns.length() + 3;
for(int x = 0; x < productNamesLength + route.getProducts().size()*2; x++)System.out.print("-");
System.out.println("");
}
}
这是应该能够填充/替换ArrayList
的随机数发生器package hillclimbing;
import java.util.*;
public class RandomProducten {
public HashMap<Integer, Product> producten;
public RandomProducten(int aantal){
Random rand = new Random();
producten = new HashMap<Integer, Product>();
for(int i = 1; i <= aantal;i++){
boolean geaccepteerd = false;
int randx = rand.nextInt(5) + 1;
int randy = rand.nextInt(5) + 1;
while (! geaccepteerd){
if (hasDuplicates(randx, randy)){
randx = rand.nextInt(5) + 1;
randy = rand.nextInt(5) + 1;
} else {
geaccepteerd = true;
}
}
Product p = new Product("Product " + i, randx, randy);
producten.put(i, p);
}
}
public boolean hasDuplicates(int x, int y) {
boolean antwoord = false;
for (Map.Entry<Integer, Product> entry : producten.entrySet()) {
if (entry.getValue().getX() == x && entry.getValue().getY() == y){
antwoord = true;
}
}
return antwoord;
}
public String toString(){
String antwoord = "";
for (Map.Entry<Integer, Product> entry : producten.entrySet()) {
antwoord += entry.getValue();
}
return antwoord;
}
}