How to represent double values as circles in a 2d matrix in java
Here's an example of a custom renderer that implements the Icon
interface to do the drawing. This approach permits easier control over the relative positioning of the text and icon. Note that the renderer scales based on the assumption of normalized values in the interval [0, 1)
; you may want to query your data model for the minimum and maximum values instead.
class DecRenderer extends DefaultTableCellRenderer implements Icon {
private static final int SIZE = 32;
private static final int HALF = SIZE / 2;
DecimalFormat df;
public DecRenderer(DecimalFormat df) {
this.df = df;
this.setIcon(this);
this.setHorizontalAlignment(JLabel.RIGHT);
this.setBackground(Color.lightGray);
}
@Override
protected void setValue(Object value) {
setText((value == null) ? "" : df.format(value));
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.blue);
double v = Double.valueOf(this.getText());
int d = (int)(v * SIZE);
int r = d / 2;
g2d.fillOval(x + HALF - r, y + HALF - r, d, d);
}
@Override
public int getIconWidth() {
return SIZE;
}
@Override
public int getIconHeight() {
return SIZE;
}
}
Find and search for a double in an array and return its indices? Is this an array element swap method?)
A few things to fix in your first example:
Right now,
j < circles[0].length
means that only one column is being searched: column0
. You'll wantj < circles[i].length
to search every column by row.if (temp == r)
means you're comparing aCircle
and adouble
. I'm not familiar with the circle class, but I believe you'll want to replace instead ofCircle temp = circles[i][j]
withdouble temp = circles[i][j].getRadius();
.You want to return as soon as you find the matching
Circle
, so you have some things a little backwards. With my new revisions,if (temp == r)
will now activate the code if you have found the correct radius. That means below thatif
statement, you'll wantreturn {i, j};
. That will return the current circle's (which has the correct radius) indicies.The last statement will be called if none of the radius tests return true, so where you have
return circles.indexOf(r);
, you'll wantreturn {-1, -1};
.Since arrays are 0-based, and less than already means one minus the value, you do not need
- 1
ini < circles.length - 1
On your second example:
Your findCircleWithRadius
method has two paramaters: a Circle[][]
and a double
. That means you'll need to give it those. The method you created is not called from a double, as well, so you can't say r1.findCircleWithRadius();
Additionally, you need to use the int[]
that the findCircleWithRadius
passes you to get those Circle
's.
Therefore, your first lines in swapCircles
should be:
int[] rad1 = this.findCircleWithRadius(circles, r1); // Get the coordinates of the first circle by passing the 2D array, and the radius you're looking for.
int[] rad2 = this.findCircleWithRadius(circles, r2); // Get the coordinates of the second circle by passing the 2D array, and the radius you're looking for.
Circle radius1 = circles[rad1[0]][rad1[1]]; // Circle 1 is equal to the Circle in the array that has coordinates of the first index in the coordinates, and the second index of the coordinates. (circles[x, y])
Circle radius2 = circles[rad2[0]][rad2[1]]; // Circle 2 is equal to the Circle in the array that has coordinates of the first index in the coordinates, and the second index of the coordinates. (circles[x, y])
In conclusion, the completed code with my revisions will be as follows:
public int[] void findCircleWithRadius(Circle[][] circles, double r) {
for(int i = 0; i < circles.length; i++) { //search the row
for(int j = 0; j < circles[i].length; j++) { //search each column
double temp = circles[i][j].getRadius();
if(temp == r)
return {i, j};
}
}
return {-1, -1};
}
public static void swapCircles(Circles[][] circles, double r1, double r2) {
int[] rad1 = this.findCircleWithRadius(circles, r1);
int[] rad2 = this.findCircleWithRadius(circles, r2);
Circle radius1 = circles[rad1[0]][rad1[1]];
Circle radius2 = circles[rad2[0]][rad2[1]];
Circle temp2 = radius2;
radius2 = radius1;
radius1 = temp2;
}
Otherwise, everything else is looking pretty good! I hope you did well on your quiz! Please let me know if you have any further questions about anything I have said so I can make sure you understand this fully.
Drawing circles in 2d grid array in java
My suggestion is:
Pass the
Game
class as a parameter to the constructor ofGame2
and store it as a local variable in theGame2
class as illustrated below:Game game;
public Game2(Game game){
this.game = game;
//Rest of your constructor.
}Next you declare a getter method in the
Game
class to retrieve the array which stores the position grid like as below:public int[][] getPositions(){
return this.a;
}Create a method that will return the colour to paint based on the
int
value stored as the element of the grid like this:private Color getColor(int col){
switch(col){
case 0:
return Color.red;
case 1:
.
.
.
.
}
}Now instead of overriding the
paint
method of yourGame2
class override thepaintComponent
and draw the circles in thepaintComponent
method as illustrated(Here I have considered the circles to be of 30px diameter with a gap of 20px between them):public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int[][] pos = this.game.getPositions();
for(int i = 0; i < pos.length; i++){
for(int j = 0; j < pos[i].length; j++){
g2d.setColor(getColor(pos[i][j]));
g2d.fillOval(i*50, j*50, 30, 30);
}
}
}
I hope this will solve your problem of accessing the Game
representing the model from the Game2
class representing the view.
Filled circle in matrix(2D array)
You get the equation of a circle:
where a & b are the center point coordinates. All x & y points that satisfy this equation are part of the circle. To see if a certain point (x1, y1) is, check if
((x1 - start_X) * (x1 - start_X) + (y1 - start_Y) * (y1 - start_Y)) <= r * r
The <= sign is to include the points that lie inside the circle, too. You can safely limit the point ranges in the intervals [start_X - r; startX + r] and [start_Y - r; startY + r].
Compare graph values or structure
I have used a Java implementation of Dynamic Time Wrapping
algorithm. The library is called fastDTW.
Unfortunately from what I undersood they don't support it anymore, though I found a use for it.
https://code.google.com/p/fastdtw/
I can't recall now, but I think I used this one and compiled it myself:
https://github.com/cscotta/fastdtw/tree/master/src/main/java/com/fastdtw/dtw
Java draw pixel circle in 2D array
cos
and sin
functions produce double
values from -1
to +1
, and when you cast double
to int
like this: int ElX = (int) (x + x1)
, some data will be inevitably lost, because such cast just chops the decimal part away. Instead, I suggest rounding double with Math.round
, check example below:
System.out.println((int) 0.99); // 0
System.out.println((int) -0.99); // 0
System.out.println(Math.round(0.99)); // 1
System.out.println(Math.round(-0.99)); // -1
Note that Math.round
returns long
, so it still must be casted to int
:
int ElX = (int) Math.round(x + x1);
int ElY = (int) Math.round(y + y1);
Output
Before After
****** *****
* * *** ***
* * * *
* * ** **
* * * *
* ** * *
* * * *
* * ** **
* * * *
****** *** ***
* *****
How do you loop through a circle of values in a 2d array?
The way I've done this is to do a double for-loop like you would for looping through the 2d array normally. Inside this loop, however, do a check to see if the array element in question is within a circle of radius r using the distance formula.
For example, given a 10x10 array, and a chosen "center" of the array at (x,y):
for i from 0 to 9 {
for j from 0 to 9 {
a = i - x
b = j - y
if a*a + b*b <= r*r {
// Do something here
}
}
}
(Code is just pseudocode, not any particular language).
How to draw a decent looking Circle in Java
As it turns out, Java2D (which I'm assuming is what you're using) is already pretty good at this! There's a decent tutorial here: http://www.javaworld.com/javaworld/jw-08-1998/jw-08-media.html
The important line is:
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Successive circle in 2D array in C with Bresenham's circle algorithm
An inelegant way would be to draw 2 (or if needed 3) different circles for every possible radius, but a slightly different center point (one for x,y an other for x+1, y). - In this case your array must be big enough to handle the shifted circles (have an additional column).
A much nicer solution would be not to draw circles at all. Just iterate through the pixels, get their distance from center (using the Pythagorean theorem, which is already utilized in your code), then calculate the color based on the distance. - You can optimize this to do only one quarter of the area. And further optimize to do only one eighth.
Getting the array length of a 2D array in Java
Consider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
Related Topics
Try with Resources VS Try-Catch
How to Use "." as the Delimiter with String.Split() in Java
Map Enum in JPA with Fixed Values
Using a Custom Truststore in Java as Well as the Default One
How to Write an Rss Feed with Java
What Happens When a Duplicate Key Is Put into a Hashmap
Most Efficient Way to Increment a Map Value in Java
How to Inject Authenticationmanager Using Java Configuration in a Custom Filter
Is It Bad to Explicitly Compare Against Boolean Constants E.G. If (B == False) in Java
How Do Synchronized Static Methods Work in Java and How to Use It for Loading Hibernate Entities