I want to consist of graph function my problem for genetic algorithm. How can I do ? My chart consists of 2 independent axes, lets say X is number of iterations and Y represents corresponding best chromosome minimum value of fitness function. I am doing replacement after mutation, and then I am selecting the best chromosome. You can see below my cycle. How I can implement a graph library? I don't know anything about how to draw graphs.
for(int i=0; i
for(int j=0;j<parameters.getMaxSelection();j++){
select.binaryTournamentSelection(pop.chromosome);
for(int k=0;k<parameters.getMaxCrossover();k++){
crossing.onePointCrossover();
for(int m=0;m<parameters.getMaxMutation();m++){
mut.bitFlip();
mut.steadyStateSorting(pop);
}
}
}
}
This may not be what you are looking for but this code might give you some ideas about the XY Graph : https://github.com/najikadri/ONSA
Related
I would like to start to parallelize my Java code. This is my toy-problem. I have two vectors (double []) containing respectively the height and the base of several triangles. I have a class, Triangle, containing a method, computeArea, that computes the area of a triangle (height*base/2). For each triangle I have I want to store the area in a third vector (double []). Currently I have a for loop like this
for(int i=0; i<height.length; i++){
area[i] = triangle.computeArea(height[i], base[i]);
}
Some suggestion on how to parallelize the code? Could you kindly provide me a simple example? I am using jdk 1.8.
Please note that the values in the vector area must correspond to values in vectors height and base.
Thanks in advance
I am building a simulation in Java w/JavaFX UI.
The idea is that I can create many Person objects (in an array) which will contain (x,y) co-ordinates to denote positioning for rendering on the screen. At each step in time I will iterate through the array and apply some to the Person objects to calculate their next position (based on current velocity etc). So far so good...
However, I also want to model interactions between Person objects (make sure that they can't overlap for instance and would just bounce off each other). The only way that I can see to do this is by iterating over the array for each Person to compare their x,y values against every other person e.g.
Person [] population = initialisePopulationArray(); //Helper function to just set initial values
//A step in time occurs just before I render the new positions on screen
void step(){
//Do basic initial calculation on positions O(n)
for(Person person: population){
updatePosition(person); //Based on trajectory etc
}
//Determine if new positions mean that people are overlapping and resolve O(n ^ 2)
for(int i=0; i<population.length; i++){ //For every person
Person person = population[i];
for(int x=i+1; i<population.length-(i+1); i++){ //Compare against every other person
compareAndResolve(person, population[x]; // Some function to compare and resolve any issues
}
}
}
As you can see this gives exponential complexity - is this just the way it has to be in a simulation like this or is there a better way that I have missed?
Any help would be greatly appreciated!!!
If two people don't interact as long as they are farther apart than some distance d, then you can divide your world into squares of size d x d. Then you only have check each person against other people in the same or adjacent squares.
In Java you could use, for example, a Hashmap<java.awt.Point, List<Person>> to keep track of which people are in each square.
I was solving tsp using simulated annealing and I want to plot the optimum distance versus temperature of the optimum distance and join those points to see the nature of the graph.
I've got the distances and temperatures in two different arrays now I need to plot this as a scatter. If putting the values in one array is required for plotting even that can be done but how do I plot such a graph. I tried using libre office to plot the graph but that isn't working at all, the app is crashing.
while (temp > 1) {
//some code giving distance
// Cool system
temp *= 1-coolingRate;
System.out.println(""+ best.getDistance());
System.out.println(""+ temp );
//Outputs to be put in an array and plotted
}
Edit 1:
Both the arrays are single dimensional and the graph I want to plot has points whose X and y co ordinates are taken from these arrays consecutively.
I can't figure out a way to do it.
Search your code to see if 'temp' is defined in multiple ways in your code. temp is a common variable that is also often used as a temporary holding place while you crunch the numbers. Has it been previously defined?
I've recently started learning Java and though doing a "Conway's Game of Life" style program would be a good thing to start out with. Everything works fine but I'm having some serious performance issues with this part:
static List<Point> coordList = new ArrayList<Point>();
public int neighbors(int x, int y){
int n = 0;
Point[] tempArray = { new Point(x-1, y-1), new Point(x, y-1), new Point(x+1, y-1),
new Point(x-1, y ), new Point(x+1, y ),
new Point(x-1, y+1), new Point(x, y+1), new Point(x+1, y+1)};
for (Point p : tempArray) {
if (coordList.contains(p))
n++;
}
return n;
}
The method is used when iterating the ArrayList coordList filled with Points and checking every element how many neighbors they have. When the list size gets to about 10000 Points every cycle takes about 1 seconds and for 20000 Points it takes 7 seconds.
My question is, what would be a more effective way to do this? I know there are several other programs of this kind with source code available too look at, but I wan't do do as much as I can by my self since the point of the project is me learning Java. Also, I don't want to use a regular array because of the limitations.
If your points are unique, you could store them in a HashSet instead of an ArrayList. The contains method will then become an O(1) operation vs. O(n) in your current setup. That should speed up that section significantly.
Apart from the declaration, your code should remain mostly unchanged as both implement the Collection interface, unless you call List-specific method such as get(i) for example.
Performance-wise, I think your best bet is to have a plain numeric (effectively Boolean) array representing the grid. Since this is a learning exercise, I'd start with a simple one-element-per-cell array, and then perhaps progress to packing eight adjacent cells into a single byte.
It is not entirely clear what you mean by "the limitations".
The following has some interesting pointers: Optimizing Conway's 'Game of Life'
Your current code scales in a quadratic manner O(n^2). You have only given part of the program. If you look at your whole program there will be a loop that calls neighbors() and you will see that neighbors() is called n times. Also the operation contains() is linear in n, so the time is proportional to their product n*n.
Quadratic scaling is a common problem but can often be reduced to linear by using indexed data structures such as HashSet.
I mainly focused on the Graphics aspects to create a little 2DGame. I've watched/looked at several tutorials but none of them were that pleasing. I already have a player(a square) moving and colliding with other squares on the screen. Gravity etc. Are also done.
If there are only that much objects as seen on the screen (30*20), everything works perfectly fine. But if I increase it to let's say 300*300 the program starts to run very slow since it has to check for so many objects.
I really don't get how games like Minecraft can work with ALL THOSE blocks and my program already gives up on 300*300 blocks.
I already tried to ONLY check for collisions when the objects are visible, but that leads to the program checking every single object for it's visibility leading to the same problem.
What am I doing wrong? Help appreciated.
I'll post some code on how I handle the collisions.
player.collision(player, wall);
public void collision(Tile object1, Tile[] object2){
collisionCheckUp(object1, object2);
collisionCheckDown(object1, object2);
collisionCheckLeft(object1, object2);
collisionCheckRight(object1, object2);
}
public void collisionCheckDown(Tile object1, Tile[] object2){
for (int i = 0; i < Map.tileAmount; i++){
if(object2[i] != null && object2[i].visible)
{
if(object1.isCollidingDown(object2[i])){
object1.collisionDown = true;
return;
}
}
}
object1.collisionDown = false;
}
public void compileHullDown(){
collisionHull = new Rectangle((int)x+3, (int)y+3, width-6, height);
}
int wallCount = 0;
for (int x=0;x<Map.WIDTH;x++) {
for (int y=0;y<Map.HEIGHT;y++) {
if (Map.data[x][y] == Map.BLOCKED) {
wall[wallCount] = new Tile(x * Map.TILE_SIZE, y * Map.TILE_SIZE);
wallCount++;
}
}
}
The usual approach to optimize collision detection is to use a space partition to classify/manage your objects.
The general idea of the approach is that you build a tree representing the space and put your objects into that tree, according to their positions. When you calculate the collisions, you traverse the tree. This way, you will have to perform significantly less calculations than using the brute force approach, because you will be ignoring all objects in branches other than the one you're traversing. Minecraft and similar probably use octrees for collision (and maybe for rendering too).
The most common space partition structures are BSP-Trees, kd-Trees (a special type of BSP-trees). The simpler approach would be to use a uniform space partition for the start - split your space in axis-aligned halves.
The best resource on collision that I have discovered is this book. It should clarify all your questions on the topic.
That's if you wanted to do it right. If you want to do it quick, you could just sample the color buffer around your character, or only in the movement direction to determine if an obstacle is close.
As Kostja mentioned, it will be useful for you to partition your space. However, you will need to use QuadTrees instead of Octrees as you are only in 2D not 3D.
Here are is a nice article to get you started on QuadTrees.
You can cut your overhead by a factor of 4 by, instead of calculating collisions for up/down/left/right, calculating collisions once and using the relative positions of the two objects to find out if you hit a floor, wall, or ceiling. Another good idea is to only pay attention to the objects that are nearby - maybe once every 0.25 seconds make a list of all objects that are probably close enough to collide with in the next 0.25 seconds?