Sorting 3D Grid Points into 3D Grid Cells - java

I'm kind of at a roadblock while trying to assign 3D grid points as vertices to Cells.
The Cells should just contain 8 points as corner vertices.
I have created the grid without any issues, but cant seem to figure out how to sort the points to their according cells.
This sketch illustrates how the points are indexed:
One cube with 8 corner points would correspond to a Cell (ex. Cell0 would include points 0,1,3,4,6,7,9,10 as corner points).
The code should be something like this:
public class Cell
{
public int[] Index =new int[8];
}
public void makeCells()
{
numCells = (xSize - 1) * (zSize - 1) * (ySize - 1);
Cells = new Cell[numCells];
for ( int i = 0, j = 0; i < numCells; i++)
{
Cells[i] = new Cell();
for ( int k = 0; k <8; k++, j ++)
{
Cells[i].Index[k] = j;
}
}
}
I can't seem to get how to increment the indices properly so that they coordinate with the correct points.
Any form of help would be appreciated!

I managed to index all of my vertices using the algorithm above. If anyone needs any further explanation please feel free to ask.

Related

Reversing a 2D array of objects; Java

I need to reverse the objects in a 2D Array
It starts with:
{triangle, circle, square}, {star, pentagon, donut}
And should end with:
{square, circle, triangle}, {donut, pentagon, star}
Currently it outputs:
triangle, circle, square, star, pentagon, donut
I have looked at this question but even copying and pasting working code from that question doesn't work.
Here is the current code I have:
Shape[][] myShapes = {{triangle, circle, square}, {star, pentagon, donut}};
public static void reverseShapes(Shape[][] myShapes) {
// TO DO #1: Implement your algorithm to reverse myShapes.
for(int row = 0; row < myShapes.length; row++){
for(int col = 0; col < myShapes[row].length / 2; col++) {
Shape temp = myShapes[row][col];
myShapes[row][col] = myShapes[row][myShapes[row].length - col - 1];
myShapes[row][myShapes[row].length - col - 1] = temp;
}
}
}//end of reverseShapes
This is how I'd write it:
public static void reverseShapes(Shape[][] shapes) {
for(Shape[] row : shapes) {
for(int left=0, right=row.length-1; left<right; left++, right--) {
Shape tmp = row[left];
row[left] = row[right];
row[right] = tmp;
}
}
}
I think it's much easier to understand with the enhanced for loop syntax pulling a row out at a time, and then the indexed for loop using two different variables, "left" and "right" moving inwards from the ends towards the middle without needing to calculate any indices.

How to do dijkstra's algorithm on a grid matrix

So I have a gird that can be any given size (i.e. matrix or 2d array). Each element contains a value and simply I need to find the shortest path. However, the problem I am having is trying to represent this grid as a graph or adj matrix or what ever you are meant to do. For example this is my code:
public int shortestPath (int[][] matrix, int sr, int sc, int dr, int dc)
{
int p = matrix.length * matrix[0].length;
int[] distances = new int[p];
boolean[] visited = new boolean[p]; //I think all are set to false by default
for (int i = 0; i < p; i++)
{
distances[i] = Integer.MAX_VALUE;
}
PriorityQueue<Node> pq = new Priority<>(); // a Node holds the int row, int col and the distance from source cell. It also orders by distances, so therefore a comparable was created to change natural order.
pq.add(new Node(sr,sc,0);
distances[(sr * matrix[0].length) + sc] = 0;
visited[(sr * matrix[0].length) + sc] = true;
while(!pq.isEmpty())
{
Node n = pq.poll();
int row = n.getRow();
int col = n.getColumn();
int dist = n.getDistance();
//Now here with a normal graph I would search neighbours via a for loop and find in the adj list where an element = 1 and is not visited. This is where I am stuck
}
}
So obviously with a grid, I will need to find neighbours of left/right/up/down (not doing diagonals). Thus, I need to take into account boundaries. How can a create an Adj matrix or what is the correct way to start searching neighbours for a grid like this?
I am having bad luck with this today because most examples show in graph form to adj matrix and not from grid form to adj matrix.
There's a trick for grid graphs:
lets say {x,y} denotes difference between 2 neighbour cells
You know neighbours will be in {0,-1}, {0,1}, {1,0} or {-1,0} (assuming no diagonal moves), or those cells will be out of bounds
Save arrays of those differences:
int differenceX[] = {0,0,1,-1};
int differenceY[] = {-1,1,0,0};
Now you can use for loop for neighbours:
for(int i=0; i<4; i++)
{
int neighRow = row + differenceY[i];
int neighCol = col + differenceX[i];
if(min(neighRow, neighCol) >= 0 && neighRow < matrix.length && neighCol < matrix[0].length){
//process node
}
}

Creating multiple objects "x" distance away from each other

I am trying to finish my code for an assignment I have, but I'm stuck on the last component. I need to create "stars" (small yellow square objects) in the "sky"... a grid of 5 rows of 10 stars. I am in a beginner java class, and I am supposed to being using methods such as star.moveHorizontal() or star.moveVertical(). All of the relevant posts I've searched for have been too complex or out of my comprehension.
I think that I would need to create an array? We haven't even covered that in class... And then have each "star" be x distance (the first star) + 30 units to the right. Then t continue that trend until there are 10 stars in a row. And then get four more rows of 10 stars.
Here is the code I've create for just one star (in the upper left of my window):
Square s1 = new Square();
s1.makeVisible();
s1.changeColor("yellow");
s1.changeSize(5);
s1.moveVertical(-100);
s1.moveHorizontal(-270);
Then I tried to create an array for a square class... I honestly have no idea if that's even legal.
Square[] starArray = new Square[10];
for ( int i=0; i<starArray.length; i++) {
starArray[i] = new Square();
But then I don't understand how I can call each star and make them appear... Please help. I feel so out of my depth. I've tried to research this and try new things for over 2.5 hours now. I will answer any questions you have to the best of my ability. Thank you
If you can make a single star appear and haven't learned about arrays yet, I don't think that is the answer your teacher is looking for. The point of an array is to be a container so you can reference the objects again. If you don't need to go back to the stars in the future, just create them and set their values in a loop.
// Set defaults for spacing and start positions
int horizontalStartPosition = 10;
int horizontalSpacing = 30;
int verticalStartPosition = 10;
int verticalSpacing = 30;
// Outer loop creates the 4 rows
for (int i = 0; i < 4; i++) {
// Inner loop creates each row
for (int j = 0; j < 10; j++) {
// Create the next star in the row
Square s = new Square();
s.makeVisible();
s.changeColor("yellow");
s.changeSize(5);
// Move the star to the correct vertical position for the current row
s.moveVertical(verticalStartPosition + i * verticalSpacing);
// Move the star to the correct horizontal spacing for the next star
s.moveHorizontal(horizontalStartPosition + j * horizontalSpacing);
}
}
You're on the right track. You can use a 2D array with 5 rows and 10 columns. Try something like this:
int numColumns = 10; //the number of columns in the array
int numRows = 5; // the number of rows in the array
Square[][] starArray = new Square[numRows][numColumns]; // the array itself
final int DIST_X = 10; //the distance between columns (use final because this value should not change)
final int DIST_Y = 10; // the distance between rows (use final because this value should not change)
int y = 0; // the initial row's vertical displacement
for ( int i=0; i<numRows; i++) {
int x = 0; // the initial columns horizontal displacement
for ( int j=0; j<numColumns; j++) {
starArray[i][j] = new Square(); //define the square
starArray[i][j].moveHorizontal(x); // move it x units horizontally
starArray[i][j].moveVertical(y); // move it y units vertically
starArray[i][j].makeVisible(); //show the square
x += DIST_X; //update your horizontal displacement so the next column shows up in the correct position
}
y += DIST_Y; //update your vertical displacement so the next row shows up in the correct position
}
Based on what I understand, you would want to call a method which would basically place a star in the grid for you.
I am not fully sure of what you mean, but here is what I can offer you:
You'll want to create a method for placing a star.
private static int X_SPACING = 30;
private static int Y_SPACING = 20;
public Square placeStar(int x, int y){
// This is the same code that you had before.
Square sq = new Square();
sq.changeColor("yellow");
sq.changeSize(5);
sq.moveVertical(-y); // Where Y is the distance from the TOP LEFT.
sq.moveHorizontal(-x);
return sq;
}
public ArrayList<Square> makeRow(int columnsAmount, int y, int startX){
ArrayList<Square> squares = new ArrayList<>();
for(int i = 0; i < columnsAmount; i++)
squares.add(placeStar(startX + (X_SPACING * i), y));
return squares;
}
public ArrayList<Square> makeGrid(int rowsAmount, int columnsAmount){
ArrayList<Square> rslt = new ArrayList<>();
for(int i = 0; i < rowsAmount; i++)
rslt.addAll(makeRow(columnsAmount, (i * Y_SPACING), 0);
return rslt;
}
Basically, calling "makeRow" should create a row of [rowsAmount] stars, which are all separated by [X_SPACING] pixels.
Then, makeGrid will call makeRow multiple times adjusting [y], and this will make you a grid. Feel free to adjust any value in the code.
EDIT: I've added a makeGrid function, and changed a few variables in the makeRow as I mistyped them. I made the functions return an ArrayList, but you shouldn't need them, only if your teachers later ask to modify them later, or something.
I hope this helps, don't hesitate to ask more questions.
Sneling.

Converting Vertex[] to graph

I am making a Pac-Man game and I am currently working on the ghosts AI. I am planning on using Dijkstra's algorithm for the pathfinding. My problem is that when my game is loaded the vertices for the graph are stored in a matrix. I am trying to assign each vertex all of its edges like this
for(int x = 0; x<40; x++)
{
for(int y = 0; y<40; y++)
{
Vertex vertex = map[x][y];
vertex.adjacencies = new Edge[]{new Edge(map[x-1][y], 1), new Edge(map[x+1][y], 1), new Edge(map[x][y-1], 1), new Edge(map[x][y+1], 1)};
}
}
the problem is that it sometimes throws an array out of bounds exception. How would I fix this without putting in tons of if statements to check if the current vertex is on the edge of the graph?
One easy way is to include a non-traversable border around the edges.
For example, if your actual map is 40x40, you can declare a 42x42 array. Rows 0 and n would be non-traversable, as would be columns 0 and n.
You'd still need to handle cylindrical travel of the pacman between left and right sides.
You should start your loop with a "border" of 1, like this:
for(int x = 1; x < 39; x++)
because, when you create your edges with map[x-1][y] with a x started to 0, it take -1 as array index, so it throw an Array Out of Bounds exception.

Formula to draw pyramid of circles

I'm trying to create a pyramid of circles to my game, looking similar to this :
alt text http://img266.imageshack.us/img266/3094/lab1213c.jpg
But I can't make it print properly. Constantly I'm getting really strange spirals but nothing close to this. Can anyone give me some tip on proper formula ? My window is 600x600, base of pyramid is 8 .
fields = new Field[BASE*(BASE/2)+4];
int line_count = BASE;
int line_tmp = line_count;
for(int i=0; i< fields.length; i++){
for( int j=line_tmp; j <= line_count; j++){
fields[i] = new Field(0, (150+(line_tmp*5)),(600+line_tmp*5));
}
line_count--;
line_tmp = line_count;
}
The mistakes I see are:
Incorrect array size formula.
Including line_tmp (which seems to be your column counter) in your y expression.
Having two variables, line_count and line_temp that are always equal.
Having your outer loop count by node rather than counting by row.
Having generally meaningless variable names and magic numbers strewn about.
// I use java.util.ArrayList because using its add(..) method is convenient here.
// The proper forumula for anticipated number of nodes is: base×(base+1)÷2
final List<Field> fields = new ArrayList<Field>(BASE*(BASE+1)/2);
// I use a java.awt.Point to store the (x,y) value of the first node of the row.
// This clarifies the meaning, rather than using ints or long inline expressions.
final Point rowStart = new Point(PANEL_WIDTH/2, DIAMETER);
// The number of rows equals the number of nodes on the final row.
for (int row = 1; row <= BASE; row++) {
// The nth row has n nodes.
for (int circle = 0; circle < row; circle++) {
// Each row starts at rowStart and each subsequent circle is offset to
// the right by two times the circle diameter.
fields.add(new Field(0, rowStart.x + circle*DIAMETER*2, rowStart.y));
}
// Each subsequent row starts a little down and to the left of the previous.
rowStart.x -= DIAMETER;
rowStart.y += DIAMETER;
}
Remember to only use this as reference for fixing your own code if this is homework.

Categories

Resources