It's a simplified code snippet I need to use in a Conway's Game of Life implementation. I have a HashMap where the Coord Objects ( cells in Game of Life ) are stored. Coord objects are pairs of X, Y coordinates which I want to print on a simple 2D grid.
I have problems with the printGrid(HashMap<Coord, Integer> map) method, mainly:
Is there a simpler and more elegant way to print the Coord objects on a 2-dimensinal grid?
If not, is there a way to check if there is a Coord object with given X,Y parameters in the HashMap without creating an instance of the Coord object for every X,Y position on the grid like I'm doing here:
if (map.containsKey(new Coord(column,row))) {
grid += map.get(new Coord(column,row));
} else {
grid += "#";
}
The code:
public class Main {
static class Coord {
int x;
int y;
public boolean equals(Object o) {
Coord c = (Coord) o;
return c.x == x && c.y == y;
}
public Coord(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return x * 3 + y * 5;
}
}
public static String printGrid(HashMap<Coord, Integer> map) {
int grid_width = 10;
int grid_height = 10;
String grid = "";
for(int row =0; row < grid_height; row++) {
for(int column=0; column< grid_width; column++) {
if(map.containsKey(new Coord(column,row))) {
grid += map.get(new Coord(column,row));
} else {
grid += "#";
}
}
grid += "\n"; // next row
}
return grid;
}
public static void main(String args[]) {
HashMap<Coord, Integer> map = new HashMap<Coord, Integer>();
map.put(new Coord(0, 0), 1);
map.put(new Coord(1, 2), 5);
map.put(new Coord(3, 4), 1);
map.put(new Coord(4, 5), 3);
map.put(new Coord(4, 6), 2);
System.out.println(printGrid(map));
}
}
I think the following code match your requirements.Basically you can create a StringBuilder object and initialize it with all '#'. Then, based on Coord objects in the map replace the corresponding character in the builder with the value in the map.It is simple and you don't need to create a Coord object for each grid cell.
public static String printGrid(HashMap<Coord, Integer> map) {
int width = 10;
int height = 10;
int lenght = height * width ;
StringBuilder grid = new StringBuilder(lenght);
// Initialize the builder
int i = 0 ;
while(i<lenght){
if(i >= width && i%(width)==0){
grid.append('\n');
}
grid.append('#');
i++;
}
for(Coord c : map.keySet()){
int index = c.x *(width + 1) + c.y;
grid.setCharAt(index, map.get(c).toString().charAt(0));
}
return grid.toString();
}
output:
1#########
##5#######
##########
####1#####
#####32###
##########
##########
##########
##########
##########
hope this can help.
Your code is close to what you want, but:
Since the grid is very big, how would printGrid() know the size? You should pass the size in as parameters too.
Don't create the Coord object twice. Only create it once and assign to variable, so it can be used twice.
This point is negated by the next bullet, but point well made, right?
Don't call containsKey(), then get(). Since your map will not have null values (according to the way you used it), the null returned by get() is enough of an existence test.
Do not do string += string in a loop. Use a StringBuilder. Huge performance difference when string gets large.
So, your code becomes:
public static String printGrid(HashMap<Coord, Integer> map, int width, int height) {
StringBuilder grid = new StringBuilder(height * (width + 1)); // Pre-sizing is optional, but
// may improve performance a bit
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
Integer value = map.get(new Coord(column, row));
if (value != null) {
grid.append(value);
} else {
grid.append('#');
}
}
grid.append('\n'); // next row
}
return grid.toString();
}
Considering Andreas' suggestion, here is my proposition
Add int neighbours in the Coord class
static class Coord {
int x;
int y;
int neighbours;
public Coord(int x, int y) {
this(x, y, 0);
}
public Coord(int x, int y, int neighbours) {
this.x = x;
this.y = y;
this.neighbours = neighbours;
}
// getters and setters here
// Equals method here
}
Add a method to retrieve a Coord object from coordinates
Coord getCoord(HashSet<Coord> data, int x, int y) {
Coord coord = new Coord(x, y);
if (data.contains(coord)) {
for (Coord c : data) {
if (c.equals(coord)){
return c;
}
}
}
return null;
}
Your printGrid method will be like this
String printGrid(HashSet<Coord> data, int width, int height) {
StringBuilder grid = new StringBuilder(height * (width + 1));
Coord coord;
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
coord = getCoord(data, row, column);
if(coord != null) {
grid.append(coord.getNeighbours());
} else {
grid.append('#');
}
}
grid.append('\n'); // next row
}
return grid.toString();
}
And in your main method you will have this
HashSet<Coord> data = new HashSet<>();
data.add(new Coord(0, 0, 1));
data.add(new Coord(1, 2, 5));
data.add(new Coord(3, 4, 1));
data.add(new Coord(4, 5, 3));
data.add(new Coord(4, 6, 2));
System.out.println(printGrid(data, 10, 10));
You can also use ArrayList like this
Coord getCoordWithList(ArrayList<Coord> data, int x, int y) {
Coord coord = new Coord(x, y);
int index = data.indexOf(coord);
if (index > -1) {
return data.get(index);
}
return null;
}
Well instead of having a map with Coord object as key, you can use a String as key. Your String key will be the concatenation of x and y values of your Coord.
So you will have this
for (int row = 0; row < grid_height; row++) {
for (int column = 0; column < grid_width; column++) {
String key = column + "#" + row;
if(map.containsKey(key)) {
grid += map.get(key) + "";
} else {
grid += "#";
}
}
grid += "\n"; // next row
}
And for the initialisation of the map you will have this
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("0#0", 1);
map.put("1#2", 5);
map.put("3#4", 1);
map.put("4#5", 3);
map.put("4#6", 2);
System.out.println(printGrid(map));
Edit
Instead of using a HashMap to store your data, you can just use a HashSet for it. The Integer value of the map will be an attribute of your Coord class
Related
I started today to program Conways Game of Life. In a first step, I just want the user to input the length of the (squadratic) field which is then displayed on the screen. But I'm getting a NullPointerException in the printGrid() method. Here are the necessary code examples:
public class Grid {
private Cell[][]grid;
public Grid (int feldlänge) {
grid = new Cell[feldlänge][feldlänge];
int x, y;
for (y = 0; y < feldlänge; y = y + 1) {
for (x = 0; x < feldlänge; x = x + 1) {
Cell cell;
cell = new Cell(x,y);
cell.setLife(false);
} // for
} // for
} // Konstruktor Grid
public String printGrid () {
String ausgabe = "";
int x, y;
for (y = 0; y < grid.length; y = y + 1) {
for (x = 0; x < grid.length; x = x + 1) {
if (grid[x][y].isAlive()) { // Here's the NullPointerException
ausgabe = ausgabe + "■";
}
if (!grid[x][y].isAlive()) {
ausgabe = ausgabe + "□";
}
}
ausgabe = ausgabe + "\n";
}
return ausgabe;
}
public class Cell {
private int x, y;
private boolean isAlive;
public Cell (int pX, int pY) {
x = pX;
y = pY;
} // Konstruktor Cell
public void setLife (boolean pLife) {
isAlive = pLife;
} // Methode setLife
public int getX () {
return x;
} // Methode getX
public int getY () {
return y;
} // Methode getY
public boolean isAlive () {
return isAlive;
}
}
It's kind of embarrassing I can't find the mistake by myself. I guess I'm overlooking something simple.
Already thanks a lot for any help!
Update: Already solved!
I just didn't add the cell to the array. It works now.
You don't seem to add the cell into your grid array.
public Grid (int feldlänge) {
grid = new Cell[feldlänge][feldlänge];
int x, y;
for (y = 0; y < feldlänge; y = y + 1) {
for (x = 0; x < feldlänge; x = x + 1) {
Cell cell;
cell = new Cell(x,y);
cell.setLife(false);
grid[x][y] = cell; //put the cell in the grid.
} // for
} // for
} // Konstruktor Grid
You have to add cell to your array. (german field = english array)
Also: instead of
if( someBoolean){}
if( !someBoolean){}
you should use
if( someBoolean){}
else {}
This makes it more clear what the code does
I have a grid, grid is and 2-demension array of Cell object.
public class Cell
{
int x;
int y;
ArrayList<Cell> nighbors=new ArrayList<Cell>();
public void addNeighbor(Cell cell)
{
this.neighbors.add(cell);
}
}
Every cell have 8 neighbors:
And also, one more, field is looped, like on the picture below:
So the neighbors for Cell(0,1) are also cells (5,0), (5,1), (5,2).
Now I fill neigbors like that:
public void addNeigbors(int x, int y)
{
Cell curentCell=grid[x][y];
if(x==0)
{
if(y==0)
{
curentCell.addNiegbor(this.cells[this.width-1][this.height-1]);
curentCell.addNiegbor(this.cells[x][this.height-1]);
curentCell.addNiegbor(this.cells[x+1][this.height-1]);
curentCell.addNiegbor(this.cells[x+1][y]);
curentCell.addNiegbor(this.cells[x+1][y+1]);
curentCell.addNiegbor(this.cells[x][y+1]);
curentCell.addNiegbor(this.cells[this.width-1][y+1]);
curentCell.addNiegbor(this.cells[this.width-1][y]);
}
else if(y==this.height-1)
{
// similar code
}
else
{
// and so on
}
}
// and so on
}
This code make my cry but I have no idea to make it better.
What can you advise me?
Storing references to each neighbor in Cell is a waste. IF cells need to access their neighbors, then put a reference to the grid array in each cell, and let cell calculate its neighbor indexes on the fly when necessary.
You could add a method like this:
Cell getNeighbor(int dx, int dy)
{
int w = grid.length;
int h = grid[x].length;
return grid[(x+w+dx)%w][(y+h+dy)%h];
}
If a cell needs to iterate through all of its neighbors, you can do it like this:
for (int dy=-1;dy<=1;++dy) {
for(int dx=-1;dx<=1;++dx) {
if (dx!=0 || dy!=0) {
processNeighbor(getNeighbor(dx,dy));
}
}
}
Something like this :
public void addNeigbors(int x, int y)
{
Cell curentCell=grid[x][y];
int xp1 = (x+1)%width;
int xm1 = (x-1+width)%width;
int yp1 = (y+1)%height;
int ym1 = (y-1+height)%height;
curentCell.addNiegbor(this.cells[xp1][y]);
curentCell.addNiegbor(this.cells[xp1][yp1]);
curentCell.addNiegbor(this.cells[xp1][ym1]);
curentCell.addNiegbor(this.cells[x][yp1]);
curentCell.addNiegbor(this.cells[x][ym1]);
curentCell.addNiegbor(this.cells[xm1][y]);
curentCell.addNiegbor(this.cells[xm1][yp1]);
curentCell.addNiegbor(this.cells[xm1][ym1]);
}
Create an (static) array that conains the x/y delta for all 8 neighbors so you can loop through it an add the delta to your cells x/y coordinates to get the neighbor coordinates and use mod -> % to deal with the borders:
public class Cell {
int x;
int y;
private static int delta[][] = {{-1,0},{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1}};
ArrayList < Cell > neighbors = new ArrayList < Cell > ();
public void addNeighbors() {
for (int i = 0; i < delta.length; i++) {
this.neighbors.add(this.cells
[Math.floorMod(this.x + delta[i][0], width)]
[Math.floorMod(this.y + delta[i][1], height)]
);
}
}
}
Loop over possible variations on x (dx) and y (dy), avoid the special case dx = dy = 0 and use mod to wrap around the grid.
public void addNeigbors(int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
for(int dy = -1; dy <= 1; dy++) {
if(dx != 0 || dy != 0) {
int nx = Math.floorMod(x + dx, this.width);
int ny = Math.floorMod(y + dy, this.height);
this.cells[x][y].addNeighbors(this.cells[nx][ny]);
}
}
}
}
i have a problem regarding pixel analysis for an image.
I am trying to analyse every pixel that is white (R=255,G=255,B=255).
The problem is the storing/ reading of these data.
for (int i = 0; i <= Map.getHeight(); i++) {
for (int j = 0; j <= Map.getWidth(); j++) {
if (Map.getColor(j, i).getBlue() == 255 && Map.getColor(j, i).getRed() == 255
&& Map.getColor(j, i).getGreen() == 255)
{
// coordsX = new HashMap<>();
coordsX.put(j, new Rectangle(j, i, 5, 5));
}
}
coordsY.put(i, coordsX);
}
System.out.println();
}
The reading function is the following:
for (Entry<Integer, HashMap<Integer, Rectangle>> e : coordsY.entrySet()) {
// HashMap<Integer, Rectangle> coordsX = coordsY.get(y);
HashMap<Integer, Rectangle> coordsX = e.getValue();
if (coordsX != null) {
for (Entry<Integer, Rectangle> entry : coordsX.entrySet()) {
Rectangle rect = entry.getValue();
g.setColor(Color.red);
g.draw(rect);
if (this.car2.intersects(rect)) {
intersectsTrack = true;
}
}
}
}
The problem is that when i outline:
coordsX = new HashMap<>();
like done above, i only get all one x value for one y value
example.
If i dont outline this line it is the other way around.
example.
Can you help me fixing this problem?
Kind Regards
You're creating a new coordsX everytime you've discovered a new white pixel. That's probably not what you intended. So for each y there will be one map coordsX with only one entry, any previous entry is discarded.
Also, I like to suggest to create a class for representing a 2D coordinate, let's call it Coordinate, then your algorithm gets much easier to implement. (or maybe there's already such a thing, for instance Point?)
class Coordinate {
private int x, y; // plus getter, setter, etc.
public int hashCode() {
return Objects.hash(x, y);
}
public boolean equals(Object obj) {
if (obj == this)
return true;
else if (!(obj instanceof Coordinate))
return false;
Coordinate that = (Coordinate) obj;
return this.x == that.x && this.y == that.y;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}
// ...
Map<Coordinate, Rectangle> coords = new HashMap<>();
for (int y = 0; y <= Map.getHeight(); y++) {
for (int x = 0; x <= Map.getWidth(); x++) {
Color color = Map.getColor(x, y);
if (color.getBlue() == 255 && color.getRed() == 255 && color.getGreen() == 255) {
Coordinate coordinate = new Coordinate(x, y);
Rectangle rectangle = new Rectangle(x, y, 5, 5);
coords.put(coordinate, rectangle);
}
}
}
for (Rectangle rectangle : coords.values()) {
g.setColor(Color.red);
g.draw(rect);
}
What you're saying makes sense since your code coordsX.put(j, new Rectangle(j, i, 5, 5)); associates the x coordinate j with a Rectangle, while your code coordsY.put(i, coordsX); associates the final y coordinate i with the coordsX HashMap.
However, due to associating with only an x or y value, each put() call will overwrite if you put to the same coordinate, which you do with j i times. It might be better given your intention to have a single HashMap of an x/y pair class (such as a Point2D) that you map to a rectangle.
You can further optimize this by using some knowledge about a rectangle. If you want to store some x/y pairs for certain colors of an image, you can use a one Dimensional array, knowing you can index each coordinate as x + y * width, or in your case j + i * Map.getWidth(). I would design your array "hashmap" like so:
// put values in the array.
Rectangle[] coords = new Rectangle[Map.getWidth() * Map.getHeight()];
for (int i = 0; i <= Map.getHeight(); i++) {
for (int j = 0; j <= Map.getWidth(); j++) {
int index = j + i * map.getWidth();
if (/* i,j has the correct color */) {
coords[index] = new Rectangle(j, i, 5, 5);
}
}
}
// read values from the array
for (int i = 0; i <= Map.getHeight(); i++) {
for (int j = 0; j <= Map.getWidth(); j++) {
Rectangle rect = coords[j + i * Map.getWidth()];
if(rect == null) continue;
//Your read logic here
g.setColor(Color.red);
g.draw(rect);
if (this.car2.intersects(rect)) {
intersectsTrack = true;
}
}
}
I got a 3x3 matrix in OpenCV format (org.opencv.core.Mat) that I want to copy into android.graphics.Matrix. Any idea how?
[EDIT]
Here's the final version as inspired by #elmiguelao. The source matrix is from OpenCV and the destination matrix is from Android.
static void transformMatrix(Mat src, Matrix dst) {
int columns = src.cols();
int rows = src.rows();
float[] values = new float[columns * rows];
int index = 0;
for (int x = 0; x < columns; x++)
for (int y = 0; y < rows; y++) {
double[] value = src.get(x, y);
values[index] = (float) value[0];
index++;
}
dst.setValues(values);
}
Something along these lines:
cv.Mat opencv_matrix;
Matrix android_matrix;
if (opencv_matrix.isContiguous()) {
android_matrix.setValues(cv.MatOfFloat(opencv_matrix.ptr()).toArray());
} else {
float[] opencv_matrix_values = new float[9];
// Undocumented .get(row, col, float[]), but seems to be bulk-copy.
opencv_matrix.get(0, 0, opencv_matrix_values);
android_matrix.setValues(opencv_matrix_values);
}
This function also respects the Mat's data type (float or double):
static Matrix cvMat2Matrix(Mat source) {
if (source == null || source.empty()) {
return null;
}
float[] matrixValuesF = new float[source.cols()*source.rows()];
if (CvType.depth(source.type()) == CvType.CV_32F) {
source.get(0,0, matrixValuesF);
} else {
double[] matrixValuesD = new double[matrixValuesF.length];
source.get(0, 0, matrixValuesD);
//will throw an java.lang.UnsupportedOperationException if type is not CvType.CV_64F
for (int i=0; i<matrixValuesD.length; i++) {
matrixValuesF[i] = (float) matrixValuesD[i];
}
}
Matrix result = new Matrix();
result.setValues(matrixValuesF);
return result;
}
I am lookin for an algorithmn to get the fastest way to find all points 2D (x,y) that are in a box (a box is defined by 2 points: lowerLeft and upperRight).
Imagine we have 2 million points in a 2D space.
In that 2D space I create a box somewhere from 2 points, one is lower left and the other is upper right.
What is the fastest way to get all the points that are in the box?
Here is the java test with the worst scenario: loop each point (2 millions!) and determine if it's inside the box.
I am sure we can get really faster if the list of points is ordered first...
Do you have ideas?
public class FindPointsInBox {
public static void main(String[] args) throws Exception {
// List of 2,000,000 points (x,y)
List<Point> allPoints = new ArrayList<Point>();
for(int i=0; i<2000000; i++) {
allPoints.add(new Point(46 - (Math.random()), -74 - (Math.random())));
}
// Box defined by 2 points: lowerLeft and upperRight
List<Point> pointsInBox = new ArrayList<Point>();
Point lowerLeft = new Point(44.91293325430085, -74.25107363281245);
Point upperRight = new Point(45.3289676752705, -72.93820742187495);
Date t1 = new Date();
// TODO: What is the fastest way to find all points contained in box
for(int i=0; i<allPoints.size(); i++) {
if(isPointInBox(allPoints.get(i), lowerLeft, upperRight))
pointsInBox.add(allPoints.get(i));
}
Date t2 = new Date();
System.out.println(pointsInBox.size() + " points in box");
System.out.println(t2.getTime()-t1.getTime() + "ms");
}
private static boolean isPointInBox(Point p, Point lowerLeft, Point upperRight) {
return (
p.getX() >= lowerLeft.getX() &&
p.getX() <= upperRight.getX() &&
p.getY() >= lowerLeft.getY() &&
p.getY() <= upperRight.getY());
}
}
Improving on Mikhails answer (I can't comment yet) you could utilise quadtrees http://en.wikipedia.org/wiki/Quadtree. This is what Mikhail is talking about, I think, and works by partitioning space into a grid. If there are many points in a partition it is itself partitioned into a small grid.
When selecting points one can then compare the extents of the partitions to quickly exclude several points if their containing rectangle does not intersect with your selection rectangle.
The quadtree requires O(n log n) operations for creation on average while a selecting a bunch of points requires O(log n).
Split your space into square cells. For each cell store list of points that sit in the cell. For given rectangle first find all cells that intersect with it, then iterate through points in these cells and test which of them are in the rectangle. Here is code demonstrating this approach:
public class PointsIndex {
private final int width;
private final int height;
private final int rows;
private final int cols;
private final List<Point> [][] cells;
#SuppressWarnings("unchecked")
public PointsIndex (
int width, int height, int rows, int cols)
{
this.width = width;
this.height = height;
this.rows = rows;
this.cols = cols;
cells = (List<Point> [][])new List<?> [rows][];
for (int i = 0; i < rows; i++)
cells [i] = (List<Point> [])new List<?> [cols];
}
public void addPoint (int x, int y)
{
int r = x * rows / width;
int c = y * cols / height;
List <Point> cell = cells [r][c];
if (cell == null)
{
cell = new ArrayList<Point>();
cells [r][c] = cell;
}
cell.add (new Point (x, y));
}
public Point [] getPoints (int x, int y, int w, int h)
{
int r1 = x * rows / width;
int r2 = (x + w - 1) * rows / width;
int c1 = y * cols / height;
int c2 = (y + h - 1) * cols / height;
ArrayList<Point> result = new ArrayList<Point>();
for (int r = r1; r <= r2; r++)
for (int c = c1; c <= c2; c++)
{
List <Point> cell = cells [r][c];
if (cell != null)
{
if (r == r1 || r == r2 || c == c1 || c == c2)
{
for (Point p: cell)
if (p.x > x && p.x < x + w && p.y > y && p.y < y + h)
result.add (p);
}
else result.addAll (cell);
}
}
return result.toArray(new Point [result.size()]);
}
public static void main(String[] args) {
Random r = new Random ();
PointsIndex index = new PointsIndex(1000000, 1000000, 100, 100);
List <Point> points = new ArrayList<Point>(1000000);
for (int i = 0; i < 1000000; i++)
{
int x = r.nextInt(1000000);
int y = r.nextInt(1000000);
index.addPoint(x, y);
points.add (new Point (x, y));
}
long t;
t = System.currentTimeMillis();
Point [] choosen1 = index.getPoints(456789, 345678, 12345, 23456);
System.out.println (
"Fast method found " + choosen1.length + " points in " +
(System.currentTimeMillis() - t) + " ms");
Rectangle rect = new Rectangle (456789, 345678, 12345, 23456);
List <Point> choosen2 = new ArrayList<Point>();
t = System.currentTimeMillis();
for (Point p: points)
{
if (rect.contains(p))
choosen2.add (p);
}
System.out.println(
"Slow method found " + choosen2.size () + " points in " +
(System.currentTimeMillis() - t) + " ms");
}
}
Your solution is linear, and you have no way to do better, because you have at least to read the input data.