I'm using a bidimensional array in Java for a checkers game that is like Tile[8][8] to represent my board.
That bidimensioanal array (the board) can be divided diagonally by its major diagonal like this:
The positions that correspond to this are: (0,0); (1,1); (2,2); (3,3); (4,4); (5,5); (6,6); (7,7).
Given two pairs of coordinates (row_start, col_start) and (row_final, col_final), I need to understand if each other are in opposite sides (or right on the diagonal itself) of that diagonal line.
Thank you in advance.
This will help you see the pattern between x and y:
To check whether given x,y coordinates fall on the diagonal line from North-West to South-East:
public boolean isOnDiagonalLineNW_SE(int x1, int y1){
return x1 == y1;
}
To check whether it is above the diagonal line:
public boolean isAboveDiagonalLine(int x1, int y1){
return y1 > x1;
}
To check whether it is below the diagonal line:
public boolean isBelowDiagonalLine(int x1, int y1){
return x1 > y1;
}
For a point (x, y), test if x > y.
When coordinate x is equals to y, the point is over the diagonal. If x > Y, he is on the top triangle, else, he is in the low one...
If you test it for both points (start and final), you can check the situation (if they are in opposite side or in the same, for instance)...
It appears that there is a simple repeating pattern in this concept, that is, all integer numbers that repeat in both the column as well as the row are "on the diagonal"... because it's a square. The minute this is no longer a square, this calculation becomes useless and so it is absolutely not the "best" solution for this problem.
You could just do really simple checks like...
if(row_start == col_start || row_final == col_final). This shows you numbers that are ON the diagonal line. Once you know this information then you could say if(row_start > col_start) (then you know it's to the right of the diagonal) or if(row_start < col_start) (then you know it's to the left of the diagonal line)
If the board isn't a square or "could" be a rectangle, but cannot change after run-time, then a more dynamic approach could also be taken. First you could "discover" the diagonal you want to be remembered as a token placement on the board and store it in an array to remember it. You would use a loop to start at 0,0 and quickly iterate the length and width of the board to find the places you want to be the new diagonal. As you discover each position you would record the values into your array (a 2D array would work but I would suggest an array of objects maybe even enums so that the row/col of each can easily be stored). Now that you know your new diagonal line and have it stored in memory its incredibly easy to verify now if the line is on, above, below or beside the diagonal line. This variable should last the length of the view with this board on it and become a core application state variable in order to maintain a focus on this diagonal line for future rules and whatnot.
Related
i'm searching for a algorithm that take a matrix (in fact, a double entry array) and return an array of matrix that:
is square (WIDTH = HEIGHT)
all of the element in the matrix has the same value.
I don't know if that is clear, so imagine that you have a image made of pixels that is red, blue or green and i want to get an array that contained the least possible squares. Like the pictures shows
EDIT:
Ok, maybe it's not clear: I've a grid of element that can have some values like that:
0011121
0111122
2211122
0010221
0012221
That was my input, and i want in output somethings like that:
|0|0|111|2|1|
|0|1|111|22|
|2|2|111|22|
|00|1|0|22|1|
|00|1|2|22|1|
When each |X| is an array that is a piece of the input array.
My goal is to minimize the number of output array
This problem does not seem to have an efficient solution.
Consider a subset of instances of your problem defined as follows:
There are only 2 values of matrix elements, say 0 and 1.
Consider only matrix elements with value 0.
Identify each matrix element m_ij with a unit square in a rectangular 2D grid whose lower left corner has the coordinates (i, n-j).
The set of unit squares SU chosen this way must be 'connected' and must not have 'holes'; formally, for each pair of units squares (m_ij, m_kl) \in SU^2: (i, j) != (k, l) there is a sequence <m_ij = m_i(0)j(0), m_i(1)j(1), ..., m_i(q)j(q) = m_kl> of q+1 unit squares such that (|i(r)-i(r+1)| = 1 _and_ j(r)=j(r+1)) _or_ (i(r)=i(r+1) _and_ |j(r)-j(r+1)| = 1 ); r=0...q (unit squares adjacent in the sequence share one side), and the set SUALL of all unit squares with lower left corner coordinates from the integers minus SU is also 'connected'.
Slicing matrices that admit for this construction into a minimal number of square submatrices is equivalent to tiling the smallest orthogonal polygon enclosing SU ( which is the union of all elements of SU ) into the minimum number of squares.
This SE.CS post gives the references (and one proof) that show that this problem is NP-complete for integer side lengths of the squares of the tiling set.
Note that according to the same post, a tiling into rectangles runs in polynomial time.
Some hints may be useful.
For representation of reduced matrix, maybe a vector is better because it's needed to be stored (start_x,start_y,value ... not sure if another matrix very useful).
Step 1: loop on x for n occurrences (start with y=0)
Step 2: loop on y for/untill n occurrences. Most of cases here will be m lees then n.
(case m greater then n excluded since cannot do a square) Fine, just keep the min value[m]
Step 3: mark on vector (start_x,start_y, value)
Repeat Step 1-3 from x=m until end x
Step 4: End x, adjust y starting from most left_x found(m-in vector, reiterate vector).
...
keep going till end matrix.
Need to be very careful of how boundary are made(squares) in order to include in result full cover of initial matrix.
Reformulate full-initial matrix can be recomposed exactly from result vector.
(need to find gaps and place it on vector derived from step_4)
Note ! This is not a full solution, maybe it's how to start and figure out on each steps what is to be adjusted.
I'm trying to make a program that draws a Koch fractal. Is there any way I can draw a line in Java by length instead of coordinates?
A koch fractal looks kind of like a snowflake. The repeating pattern is equilateral triangles inserted 1/3 of the way into each line (with the triangle's sides being 1/3 the length of the line).
Originally I was trying to draw triangles recursively, but I couldn't figure out how to calculate the coordinates. Then I thought it would be way easier if I could just draw lines of a certain length and rotate them, and reduce the length of the lines each time. Except that I don't know if I even can draw lines by length in Java. I have tried searching the internet for this and have not found an answer, which makes me think it's not possible, but I thought I would ask here just to make sure.
I realize this is way beyond my technical college level. I also realize I could probably find a complete program that someone else has already written, but I want to see if I can figure it out (mostly) on my own.
First of all, I am assuming that you have some sort of function drawLine(int x1, int y1, int x2, int y2) in whatever API you are using for Java. If this is true, and you want to draw a line by length I would believe you could just do it using the standard trigonometry functions (Math.sin(...), Math.cos(...) and Math.tan(...)).
Example
What you would want to draw using a given length is at least the following data:
A starting coordinate
The angle of the line with the line y = c (where c is any number)
The length of the line
Your code could then use something like this:
public void drawLineByLength(int xStart, int yStart, double angle, double length) {
int xEnd = (int) (xStart + (Math.cos(angle) * length));
int yEnd = (int) (yStart + (Math.sin(angle) * length));
drawLine(xStart, yStart, xEnd, yEnd);
}
Note that you will have to import the Math class for this method. In addition, it will only work if you were to have a drawLine(...) function available to you that takes the coordinates of two points.
Implementation
If I understand your intentions, you would want to keep track of the current coordinate the "pen" is at; the angle it is drawing at; and the length of the next line it is going to draw. You could add something at the end of the drawLineByLength(...) method that updates these variables.
I have a dynamic rectangle in which 4 subtriangles (t0-t3) are created (by adding the diagonals from the vertices). When given a certain x|y coordinate what is the fastest way to find the corresponding triangle?. The rectangle has a specific position and dimension. I only need the right "id" so not the vertices of the triangle, so for example in the graphic when p1 is given as position 0 should be returned, 3 at p2 and 2 at p3, ...
One possible solution of course would be to create the triangles and query if the point is contained in one of them, but it feels like a very complicated solution for something that simple.
I also thought about creating a vector from the center and measuring the angle but it also seems complicated in a rectangle with varying dimensions.
Example Rectangle
Consider the following:
Let the bottom left corner of the rectangle be (0,0) and the top right corner be (1,1). Now, the two lines that form the triangles are defined as:
y = x and y = 1-x
For every point except (.5,.5) we have a ternary conditional for a given x or y. For example, given that x = .2, we know that:
if y < .2, we're in the bottom triangle (t2),
elif .2 < y < .8, we're in the left triangle (t3),
else, we're in the top triangle (t0).
Hopefully this helps without explicitly giving you the code.
What I am trying to convey in the title, is that there is a player on the screen and, using the direction variable and trigonometry, he is "looking" in a direction. I need to spawn an object right in front of him. And by spawn, I mean create an object with the x and y coordinates matching the location of the spot in "front" of the player.
The code for this is something difficult. I'm unable to understand, without more information or learning more trig, what I need to do to get this to work.
Basically this is what I have, it creates a bullet and another line of code adds it to a list to be drawn to the screen. What I need to know is how to spawn the "bullet" object in the correct x & y coordinates. This is what I have so far. I can assume there is something more I need to add to the x and y variables, but I don't know what that is.
Bullet b = new Bullet((int)x/2+(Math.cos(Math.toRadians(direction))), (int)y/2 + (Math.sin(Math.toRadians(direction))), "/img/bullet.png", direction, weapon);
Create a vector pointing in a direction where you want the object spawned.
x = radius * Math.cos(angle) + startX
y = radius * Math.sin(angle) + startY
Normalize it, and then scale it to your liking.
Here's a simple demo to illustrate.
p.s
radius here is just an initial uniform displacement from the spawn point.
It would help if you understood Proportionality, but it is basically this: if you multiply x and y for the same number, you will get farther away from the current position. Of course that depends on the signals, but the simplest way is this: supposing that x and y are two positive numbers, let's say x=1 and y=1, then, if you multiply both by a positive number, let's say 3, then the final numbers (x=3 and y=3) you will have a "bullet" in the coordinates 3,3 that is right in front of the actor, which is in the position 1,1. Again, I am assuming a lot of things and ignoring a bunch of other ones, such as position of camera, perspective, etc.
Essentially I need to return a boolean if a line and a line segment intersect. For the line the information I have is the slope, xy coords for a random point, and xy for a y intercept. For the line segment I have the line segment and the two end point xy coordinates. Any ideas?
The line through (Xr, Yr) with slope S has equation D(X, Y):= (Y - Yr) - S (X - Xr) = 0.
Just check that D(Xa, Ya) and D(Xb, Yb) have opposite signs.
Implementing this is not terribly difficult, it's the conceptual part that seems the most difficult. I might code something up for this for fun later but this should be enough to get you started. Also, note that this is might be a really bad way to solve it (time/space wise) but it will definitely work.
If you want to find a good solution, use convert the line to vectors and use the implementation in the answer in the link below all my text.
Calculate the slope of the second line. If it's equal to the first, they're parallel and never intersect.
Calculate where the two lines would intersect if they do intersect. They can only intersect at one point. This is how you would check if they will intersect:
Find 2 distinct coordinates for each line at some arbitrary point.
Determine the distance between the two lines at each point.
Whichever point results in a smaller distance between the lines represents the direction you need to travel in to move closer to the intersection.
Keep checking the distance between the two lines until they start increasing (which means you need to reverse the direction again) or until the distance is 0. The xy coord at distance = 0 is the intersection.
If the x-value of the point where the two lines intersect is in between the two x-values for your line segment, the line and line fragment intersect.
This should be easier for you because you already have two xy coords for the first line and two end point coordinates for the line segment.
Check this answer out for a really nice solution with some examples in the comments: https://stackoverflow.com/a/565282/2142219