class.getMethod() is not working in my context - java

I cannot figure out how this part of code always throws NoSuchMethodException. Can anyone help? The Method M... line is probably where the code is erring. Either the method getMethod is broken or I am using it wrong. If you need more of the file just ask. Thanks!
floorName = "Base";
try {
Class[] cArg = new Class[5];
cArg[0] = World.class;
cArg[1] = Integer.class;
cArg[2] = Integer.class;
cArg[3] = Integer.class;
cArg[4] = String.class;
Method m = TowerFloors.class.getMethod("genFloor_" + floorName.toLowerCase(), cArg); //Probable Origin of Throwable Error
try {
done = (Boolean) m.invoke(m, x, y, z, color);
success = done;
} catch (Exception e) {
DungeonMod.logger.log(Level.ERROR, "Error in generating tower floor \"" + floorName + "\"(" + e + "), generating \"Base\" floor instead.");
done = genFloor_base(worldA, x, y, z, color);
}
} catch (Exception e) {
DungeonMod.logger.log(Level.ERROR, "Error in generating tower floor \"" + floorName + "\"(" + e + "), generating \"Base\" floor instead.");
done = genFloor_base(worldA, x, y, z, color);
}
and here is the method:
public static boolean genFloor_base(World world, int i, int j, int k, String color) {
if (color.toLowerCase().equals("blue")) {
//Floor
BlockFill.fillRectangle(world, i - 10, j, k - 10, i + 10, j, k + 10, TowerDungeonBuildingBlocks.towerDungeonWallBlue);
//Roof
BlockFill.fillRectangle(world, i - 10, j + 5, k - 10, i + 10, j + 5, k + 10, TowerDungeonBuildingBlocks.towerDungeonWallBlue);
//++Wall
BlockFill.fillRectangle(world, i + 10, j + 1, k + 10, i + 10, j + 4, k - 10, TowerDungeonBuildingBlocks.towerDungeonWallBlue);
//--Wall
BlockFill.fillRectangle(world, i - 10, j + 1, k - 10, i - 10, j + 4, k + 10, TowerDungeonBuildingBlocks.towerDungeonWallBlue);
//+-Wall
BlockFill.fillRectangle(world, i + 10, j + 1, k - 10, i - 10, j + 4, k - 10, TowerDungeonBuildingBlocks.towerDungeonWallBlue);
//-+Wall
BlockFill.fillRectangle(world, i - 10, j + 1, k + 10, i + 10, j + 4, k + 10, TowerDungeonBuildingBlocks.towerDungeonWallBlue);
return true;
}
return false;
}
(And yes this is a Minecraft mod)

Your method
public static boolean genFloor_base(World world, int i, int j, int k, String color) {
has 5 parameters, where i, j, and k, are of type int.
You'll want to use
int.class
instead of
Integer.class
to identify the parameter type.

Related

Recursive image painter

I am trying to make a recursive function that serves as a paint bucket that fills a certain area. This one paints a square where the user clicks:
public void drawSquare(int x, int y, Color paintColor) {
int paintColorRGB = clearAlphaChannel(paintColor.getRGB());
image.setRGB(x - 1, y - 1, paintColorRGB);
image.setRGB(x + 0, y - 1, paintColorRGB);
image.setRGB(x + 1, y - 1, paintColorRGB);
image.setRGB(x - 1, y + 0, paintColorRGB);
image.setRGB(x + 0, y + 0, paintColorRGB);
image.setRGB(x + 1, y + 0, paintColorRGB);
image.setRGB(x - 1, y + 1, paintColorRGB);
image.setRGB(x + 0, y + 1, paintColorRGB);
image.setRGB(x + 1, y + 1, paintColorRGB);
}
The recursive function is called here:
public void transformImage(int x, int y, Color paintColor) {
int paintColorRGB = clearAlphaChannel(paintColor.getRGB());
transformPoint(x, y, getPixelColor(x, y), paintColorRGB);
}
getPixelColor calculates the average colour on a 3x3 pixel square, the treshold is defined by the user in this case, treshold = 4:
private int getPixelColor(int x, int y) {
int pixelColor = clearAlphaChannel(image.getRGB(x, y));
int i= 9;
int cor0 = clearAlphaChannel(image.getRGB(x,y));
int cor1 = clearAlphaChannel(image.getRGB(x+1,y));
int cor2 = clearAlphaChannel(image.getRGB(x,y+1));
int cor3 = clearAlphaChannel(image.getRGB(x-1,y));
int cor4 = clearAlphaChannel(image.getRGB(x,y-1));
int cor5 = clearAlphaChannel(image.getRGB(x+1,y+1));
int cor6 = clearAlphaChannel(image.getRGB(x-1,y-1));
int cor7 = clearAlphaChannel(image.getRGB(x+1,y-1));
int cor8 = clearAlphaChannel(image.getRGB(x-1,y+1));
if(cor0<threshold){
i = i-1;
cor0 = 0;
}
if(cor1<threshold){
i = i-1;
cor1 = 0;
}
if(cor2<threshold){
i = i-1;
cor2 = 0;
}
if(cor3<threshold){
i = i-1;
cor3 = 0;
}
if(cor4<threshold){
i = i-1;
cor4 = 0;
}
if(cor5<threshold){
i = i-1;
cor5 = 0;
}
if(cor6<threshold){
i = i-1;
cor6 = 0;
}
if(cor7<threshold){
i = i-1;
cor7 = 0;
}
if(cor8<threshold){
i = i-1;
cor8 = 0;
}
pixelColor= (cor1+cor2+cor3+cor4+cor5+cor6+cor7+cor8+cor0)/i;
System.out.println(pixelColor);
return pixelColor;
}
This recursive function should paint the area inside the black, but it's giving me a stack overflow:
private void transformPoint(int x, int y, int refColorRGB, int paintColorRGB) {
int pixelRGB = clearAlphaChannel(image.getRGB(x, y));
if(refColorRGB!=pixelRGB){
return; }
// Image width: 0 to imageWidth -1
// Image height: 0 to imageHeight -1
// Threshold defined in GUI: threshold
transformPoint(x+1, y, refColorRGB, paintColorRGB);//1
transformPoint(x, y-1, refColorRGB, paintColorRGB);//2
transformPoint(x, y+1, refColorRGB, paintColorRGB);//3
transformPoint(x-1, y, refColorRGB, paintColorRGB);//4
drawSquare(x, y, new Color(paintColorRGB));
}
Right now only calling the first transformPoint works, but when I try adding the others it doesn't work.
butterfly

how to find the shortest path in a matrix

I have a question in JAVA I can't solve no matter how long I try to think about the solution:
There's a matrix and I need to find the shortest path possible to get from Mat[0][0] to the bottom right of the matrix and I can only proceed to the adjacent square (no diagonals) if the number in it is bigger than the one I'm on right now.
For example:
0 1 2 3 4
0 { 5 13 2 5 2
1 58 24 32 3 24
2 2 7 33 1 7
3 45 40 37 24 70
4 47 34 12 25 2
5 52 56 68 76 100}
So a valid solution would be:
(0,0)->(0,1)->(1,1)->(2,1)->(2,2)->(2,3)->(3,1)->(3,0)->(0,4)->(0,5)->(5,1)->(5,2)->(5,3)->(5,4)
And the method will return 14 because that's the shortest possible path.
I have to use a recursive method only (no loops).
This is what I came up with so far but I don't know how to figure out which is the shortest one.
Public static int shortestPath(int[][]mat)
{
int length=0;
int i=0;
int j=0;
shortestPath(mat, length, i, j);
}
Private static int shortestPath(int[][]math, int length, int i, int j)
{
if((i==mat.length)||(j==mat[i].length))
return length;
if(shortestPath(mat, length, i+1, j) > shortestPath(mat, length, i, j))
return length +1;
if(shortestPath(mat, length, i, j+1) > shortestPath(mat, length, i, j))
return length +1;
if shortestPath(mat, length, i-1, j) > shortestPath(mat, length, i, j))
return length +1;
if shortestPath(mat, length, i, j-1) > shortestPath(mat, length, i, j))
return length +1;
}
I'm not sure if that's the way to do it, and if it is: how do I know which is the shortest way, because right now it would return all possible ways and will add them together (I think).
Also, I think I should add something about reaching the bottom right of the matrix.
The code shouldn't be too complicated.
im not sure if the approach of going to the next smallest value is the shortest, but anyway:
public class Pathfinder {
private int[][] matrix;
private int matrixLenghtI;
private int matrixLenghtJ;
public Pathfinder(int[][] matrix, int matrixLenghtI, int matrixLenghtJ) {
this.matrix = matrix;
this.matrixLenghtI = matrixLenghtI;
this.matrixLenghtJ = matrixLenghtJ;
}
public static void main(String[] args) {
int matrixLenghtI = 6;
int matrixLenghtJ = 5;
int[][] matrix1 = { { 3, 13, 15, 28, 30 }, { 40, 51, 52, 29, 30 }, { 28, 10, 53, 54, 54 },
{ 53, 12, 55, 53, 60 }, { 70, 62, 56, 20, 80 }, { 80, 81, 90, 95, 100 } };
int[][] matrix2 = { { 5, 13, 2, 5, 2 }, { 58, 24, 32, 3, 24 }, { 2, 7, 33, 1, 7 }, { 45, 40, 37, 24, 70 },
{ 47, 34, 12, 25, 2 }, { 52, 56, 68, 76, 100 } };
Pathfinder finder1 = new Pathfinder(matrix1, matrixLenghtI, matrixLenghtJ);
finder1.run();
Pathfinder finder2 = new Pathfinder(matrix2, matrixLenghtI, matrixLenghtJ);
finder2.run();
}
private void run() {
int i = 0;
int j = 0;
System.out.print("(" + i + "," + j + ")");
System.out.println("\nLength: " + find(i, j));
}
private int find(int i, int j) {
int value = matrix[i][j];
int[] next = { i, j };
int smallestNeighbour = 101;
if (i > 0 && matrix[i - 1][j] > value) {
smallestNeighbour = matrix[i - 1][j];
next[0] = i - 1;
next[1] = j;
}
if (j > 0 && matrix[i][j - 1] < smallestNeighbour && matrix[i][j - 1] > value) {
smallestNeighbour = matrix[i][j - 1];
next[0] = i;
next[1] = j - 1;
}
if (i < matrixLenghtI - 1 && matrix[i + 1][j] < smallestNeighbour && matrix[i + 1][j] > value) {
smallestNeighbour = matrix[i + 1][j];
next[0] = i + 1;
next[1] = j;
}
if (j < matrixLenghtJ - 1 && matrix[i][j + 1] < smallestNeighbour && matrix[i][j + 1] > value) {
smallestNeighbour = matrix[i][j + 1];
next[0] = i;
next[1] = j + 1;
}
System.out.print("->(" + next[0] + "," + next[1] + ")");
if (i == matrixLenghtI - 1 && j == matrixLenghtJ - 1)
return 1;
return find(next[0], next[1]) + 1;
}
}
Output:
(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(1,4)->(2,4)->(3,4)->(4,4)->(5,4)->(5,4)
Length: 10
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,1)->(3,0)->(4,0)->(5,0)->(5,1)->(5,2)->(5,3)->(5,4)->(5,4)
Length: 14
Position class:
/**
* Represents a position in the matrix.
*/
public class Position {
final private int x;
final private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public String toString() {
return "(" + x + ", " + y + ')';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
if (x != position.x) return false;
return y == position.y;
}
#Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
Board class:
/**
* A board represents all of the locations in the matrix. It provides a simple interface to getting
* the value in a position, and tracking the height and width of the matrix.
*/
public class Board {
final int [][] board;
public Board(int[][] board) {
this.board = board;
}
final int positionValue(Position position) {
return this.board[position.getY()][position.getX()];
}
final int getWidth() {
return board[0].length;
}
final int getHeight() {
return board.length;
}
}
PathFinder class:
import java.util.ArrayList;
import java.util.List;
/**
* Find the shortest path from a starting point to ending point in a matrix, assuming you can
* only move to a position with a greater value than your current position.
*/
public class PathFinder {
final private Board board;
final private Position start;
final private Position end;
public PathFinder(Board board, int startX, int startY, int endX, int endY) {
this.board = board;
this.start = new Position(startX, startY);
this.end = new Position(endX, endY);
}
/**
* Gets the shortest path from the start to end positions. This method
* takes all of the paths, then determines which one is shortest and returns that.
*
* #return the shortest path from the start to end positions.
*/
public List<Position> shortestPath() {
List<List<Position>> allPaths = this.getAllPaths();
System.out.println("Paths found: " + allPaths.size());
List<Position> shortestPath = null;
for (List<Position> path : allPaths) {
if (shortestPath == null) {
shortestPath = path;
}
else if (shortestPath.size() > path.size()) {
shortestPath = path;
}
}
return shortestPath;
}
/**
* Convenience method for starting the getAllPaths process.
*
* #return all of the paths from the start to end positions
*/
private List<List<Position>> getAllPaths() {
List<List<Position>> paths = new ArrayList<List<Position>>();
return this.getAllPaths(paths, new ArrayList<Position>(), start);
}
/**
* Gets all of the paths from the start to end position. This is done recursively by visiting every
* position, while following the rules that you can only move to a position with a value greater
* than the position you're currently on. When reaching the end position, the path is added to
* the list of all found paths, which is returned.
*
* #param paths the current list of all found paths.
* #param path the current path
* #param position the current position
* #return all paths from the start to end positions
*/
private List<List<Position>> getAllPaths(List<List<Position>> paths, List<Position> path, Position position) {
path.add(position);
if (position.equals(end)) {
paths.add(path);
return paths;
}
//x+
if (position.getX() + 1 < board.getWidth()) {
Position xp = new Position(position.getX() + 1, position.getY());
if (board.positionValue(position) < board.positionValue(xp)) {
getAllPaths(paths, new ArrayList<Position>(path), xp);
}
}
//x-
if (position.getX() - 1 >= 0) {
Position xm = new Position(position.getX() - 1, position.getY());
if (board.positionValue(position) < board.positionValue(xm)) {
getAllPaths(paths, new ArrayList<Position>(path), xm);
}
}
//y+
if (position.getY() + 1 < board.getHeight()) {
Position yp = new Position(position.getX(), position.getY() + 1);
if (board.positionValue(position) < board.positionValue(yp)) {
getAllPaths(paths, new ArrayList<Position>(path), yp);
}
}
//y-
if (position.getY() - 1 >= 0) {
Position ym = new Position(position.getX(), position.getY() - 1);
if (board.positionValue(position) < board.positionValue(ym)) {
getAllPaths(paths, new ArrayList<Position>(path), ym);
}
}
return paths;
}
/**
* Run the example then print the results.
*
* #param args na
*/
public static void main(String[] args) {
int [][] array = {{5, 13, 2, 5, 2},
{14, 24, 32, 3, 24},
{15, 7, 33, 1, 7},
{45, 40, 37, 24, 70},
{47, 34, 12, 25, 2},
{52, 56, 68, 76, 100}
};
final Board board = new Board(array);
final Position end = new Position(board.getWidth()-1, board.getHeight() - 1);
final PathFinder pathFinder = new PathFinder(board, 0, 0, board.getWidth()-1, board.getHeight()-1);
final List<Position> path = pathFinder.shortestPath();
System.out.println("Shortest Path: ");
for (Position position : path) {
if (!position.equals(end)) {
System.out.print(position + " -> ");
}
else {
System.out.println(position);
}
}
System.out.println();
}
}
I really like this problem. Unfortunately I haven't worked in Java for many years, so this answer is pseudo-Java and you'll have to fix some of the syntax. Probably some of the function params should be references and not copies; you'll figure it out (update: I've added a TESTED version in python below).
// just a little thing to hold a set of coordinates
class Position
{
// not bothering with private / getters
public int x ;
public int y ;
public constructor (int x, int y)
{
this.x = x ;
this.y = y ;
}
}
class PathFinder
{
public void main (void)
{
// create a path with just the start position
start = new Position(0, 0) ;
path = new Vector() ;
path.add(start) ;
// create an empty path to contain the final shortest path
finalPath = new Vector() ;
findPath(path, finalPath) ;
print ("Shortest Path: ") ;
showPath (finalPath) ;
}
private void showPath (Vector path) {
// print out each position in the path
iter = path.iterator() ;
while (pos = iter.next()) {
print ("(%, %) ", pos.x, pos.y);
}
// print out the length of the path
print (" Length: %\n", path.size()) ;
}
// recursive function to find shortest path
private void findPath (Vector path, Vector finalPath)
{
// always display the current path (it should never be the same path twice)
showPath(path) ;
// where are we now?
here = path.lastElement() ;
// does the current path find the exit (position 4,5)?
if (here.x == 4 && here.y == 5) {
if (finalPath.size() == 0) {
//finalPath is empty, put the current path in finalPath
finalPath = path ;
} else {
// some other path found the exit already. Which path is shorter?
if (finalPath.size() > path.size()) {
finalPath = path ;
}
}
// either way, we're at the exit and this path goes no further
return ;
}
// path is not at exit; grope in all directions
// note the code duplication in this section is unavoidable
// because it may be necessary to start new paths in three
// directions from any given position
// If no new paths are available from the current position,
// no new calls to findPath() will happen and
// the recursion will collapse.
if (here.x > 0 && matrix[here.x-1][here.y] > matrix[here.x][here.y]) {
// we can move left
newPos = new Position(here.x-1, here.y) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
if (here.x < 4 && matrix[here.x+1][here.y] > matrix[here.x][here.y]) {
// we can move right
newPos = new Position(here.x+1, here.y) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
if (here.y > 0 && matrix[here.x][here.y-1] > matrix[here.x][here.y]) {
// we can move up
newPos = new Position(here.x, here.y-1) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
if (here.y < 5 && matrix[here.x][here.y+1] > matrix[here.x][here.y]) {
// we can move down
newPos = new Position(here.x, here.y+1) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
}
}
Here's a tested version of the same algorithm in python. (I noticed that using x, y as coordinates is kind of misleading. x is actually "vertical" and y is "horizontal" with the array indexed the way it is. I've set up a matrix with four paths to the exit and a couple of dead ends.)
import copy, sys
matrix = [
[5, 13, 17, 58, 2],
[17, 24, 32, 3, 24],
[23, 7, 33, 1, 7],
[45, 40, 37, 38, 70],
[47, 34, 12, 25, 2],
[52, 56, 68, 76, 100]]
def showPath(path):
for position in path:
sys.stdout.write("(" + str(position[0]) + ", " + str(position[1]) + "), ")
sys.stdout.write("\n\n")
sys.stdout.flush()
def findPath(path):
#showPath(path)
global finalPath
x = path[-1][0]
y = path[-1][1]
if x == 5 and y == 4:
showPath(path)
if len(finalPath) == 0 or len(finalPath) > len (path):
finalPath[:] = copy.deepcopy(path)
return
if x > 0 and matrix[x-1][y] > matrix[x][y]:
# we can move up
newPath = copy.deepcopy(path)
newPath.append([x-1, y])
findPath(newPath)
if x < 5 and matrix[x+1][y] > matrix[x][y]:
# we can move down
newPath = copy.deepcopy(path)
newPath.append([x+1, y])
findPath(newPath)
if y > 0 and matrix[x][y-1] > matrix[x][y]:
# we can move left
newPath = copy.deepcopy(path)
newPath.append([x, y-1])
findPath(newPath)
if y < 4 and matrix[x][y+1] > matrix[x][y]:
# we can move right
newPath = copy.deepcopy(path)
newPath.append([x, y+1])
findPath(newPath)
path = []
path.append([0, 0])
finalPath = []
findPath(path)
print "Shortest Path: " + str(len(finalPath)) + " steps.\n"
showPath(finalPath)
If you uncomment the first showPath() call in findPath() you can see every step and see where the dead ends get abandoned. If you only show paths that reach the exit, the output looks like:
(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
(0, 0), (1, 0), (1, 1), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
Shortest Path: 10 steps.
(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
here you can build a tree to all possibilities and take then the shortest. There is a loop inside for tracing the result, but you can also get around that with some ugly ifs...
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class BetterPathfinder {
public class Comperator implements Comparator<Path> {
#Override
public int compare(Path o1, Path o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
public class Path {
private Integer lenght;
TreeMap<Integer, String> trace = new TreeMap<>();
public Path(int lenght) {
this.lenght = lenght;
}
public Path(Path find, int i, int j) {
this.lenght = find.getValue() + 1;
this.trace.putAll(find.getTrace());
this.trace.put(lenght, "(" + i + "," + j + ")");
}
private Map<Integer, String> getTrace() {
return trace;
}
public Integer getValue() {
return lenght;
}
#Override
public String toString() {
String res = "end";
for (Entry<Integer, String> is : trace.entrySet()) {
res = is.getValue() + "->" + res;
}
return res;
}
}
private int[][] matrix;
private int matrixLenghtI;
private int matrixLenghtJ;
public BetterPathfinder(int[][] matrix, int matrixLenghtI, int matrixLenghtJ) {
this.matrix = matrix;
this.matrixLenghtI = matrixLenghtI;
this.matrixLenghtJ = matrixLenghtJ;
}
public static void main(String[] args) {
int matrixLenghtI = 6;
int matrixLenghtJ = 5;
int[][] matrix1 = { { 3, 13, 15, 28, 30 }, { 40, 51, 52, 29, 30 }, { 28, 10, 53, 54, 54 },
{ 53, 12, 55, 53, 60 }, { 70, 62, 56, 20, 80 }, { 80, 81, 90, 95, 100 } };
int[][] matrix2 = { { 5, 13, 2, 5, 2 }, { 58, 24, 32, 3, 24 }, { 2, 7, 33, 1, 7 }, { 45, 40, 37, 24, 70 },
{ 47, 34, 12, 25, 2 }, { 52, 56, 68, 76, 100 } };
BetterPathfinder finder1 = new BetterPathfinder(matrix1, matrixLenghtI, matrixLenghtJ);
finder1.run();
BetterPathfinder finder2 = new BetterPathfinder(matrix2, matrixLenghtI, matrixLenghtJ);
finder2.run();
}
private void run() {
int i = 0;
int j = 0;
System.out.println(new Path(find(i, j), i, j));
}
private Path find(int i, int j) {
int value = matrix[i][j];
int[] next = { i, j };
ArrayList<Path> test = new ArrayList<>();
if (i == matrixLenghtI - 1 && j == matrixLenghtJ - 1)
return new Path(1);
if (i > 0 && matrix[i - 1][j] > value) {
next[0] = i - 1;
next[1] = j;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (j > 0 && matrix[i][j - 1] > value) {
next[0] = i;
next[1] = j - 1;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (i < matrixLenghtI - 1 && matrix[i + 1][j] > value) {
next[0] = i + 1;
next[1] = j;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (j < matrixLenghtJ - 1 && matrix[i][j + 1] > value) {
next[0] = i;
next[1] = j + 1;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (test.isEmpty()) {
return new Path(100);
}
return Collections.min(test, new Comperator());
}
}
result:
(0,0)->(1,0)->(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)->end
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,1)->(3,0)->(4,0)->(5,0)->(5,1)->(5,2)->(5,3)->(5,4)->end
You want a recursive strategy. A pretty easy, though expensive method, is to simply flood the board. Something like "Try every possible path and compute the distance".
You can do this recursively by imagining moving a pebble around.
public int shortestPath(Point src, Point dest) {
if (src.equals(dest)) {
return 0;
}
// You need to do some bound checks here
int left = shortestPath(new Point(src.x - 1, src.y), dest);
int right = shortestPath(new Point(src.x + 1, src.y), dest);
int up = shortestPath(new Point(src.x, src.y + 1), dest);
int down = shortestPath(new Point(src.x, src.y - 1), dest);
// Decide for the direction that has the shortest path
return min(left, right, up, down) + 1;
}
If you are interested in the path represented by the solution, you may trace the path while creating. For this you simply need to save for which direction min decided.
I needed to solve a similar task ages ago in my computer science studies. We needed to compute the shortest amount of moves a knight on a chess board needs for reaching a given destination. Maybe this also helps you: http://pastebin.com/0xwMcQgj
public class shortestPath{
public static int shortestPath(int[][] mat){
if(mat == null || mat.length == 0 || mat[0].length == 0)
return 0;
else {
int n = shortestPath(mat, 0, 0, 0);
return (n == mat.length*mat.length+1 ) ? 0 : n;
}
}
private static int shortestPath(int[][]mat, int row, int col,int prev){
if (!valid(mat,row,col) || !(mat[row][col] > prev)){
return mat.length*mat.length+1;
} else if(row == mat.length - 1 && col == mat[row].length - 1) {
return 1;
} else {
return minimum(shortestPath(mat,row-1,col, mat[row][col]),
shortestPath(mat,row+1,col, mat[row][col]),
shortestPath(mat,row,col-1, mat[row][col]),
shortestPath(mat,row,col+1, mat[row][col])) + 1;
}
}
private static boolean valid(int[][]mat,int row, int col){
if(row < 0 || col < 0 || col > mat[0].length-1 || row > mat.length-1)
return false;
else
return true;
}
private static int minimum(int x, int y, int t, int z){
int min1 = (x > y)? y : x;
int min2 = (t > z)? z : t;
return (min1 > min2)? min2 : min1;
}
public static void main(String[] args){
int maze[][] = {
{ 3, 13, 15, 28, 30},
{ 40, 51, 52, 29, 30},
{ 28, 10, 53, 54, 53},
{ 53, 12, 55, 53, 60},
{ 70, 62, 56, 20, 80},
{ 81, 81, 90, 95, 100}};
System.out.println(shortestPath(maze));
}
}
Here is how I solved it, note that in your example we should get 16
public static void main(String[] args)
{
int[][] mat =
{
{ 3, 13, 15, 28, 30 },
{ 40, 51, 52, 29, 30 },
{ 28, 10, 53, 54, 53 },
{ 53, 12, 55, 53, 60 },
{ 70, 62, 56, 20, 80 },
{ 80, 81, 90, 95, 100 }
};
System.out.println(shortestPath(mat)); // 10
int[][] mat1 =
{
{0, 1, 2, 3, 4 },
{0, 5, 13, 2, 5, 2},
{1, 58, 24, 32, 3, 24} ,
{2, 2 , 7, 33, 1, 7} ,
{3, 45, 40, 37, 24, 70},
{4, 47, 34, 12, 25, 2},
{5, 52, 56, 68, 76, 100}
};
System.out.println(shortestPath(mat1)); // 16
}
public static int shortestPath(int[][] mat)
{
return shortestPath(mat, 0, 0, mat[0][0] - 1, 0);
}
private static int shortestPath(int[][] mat, int row, int col, int prev, int counter)
{
if (row < 0 || row == mat.length || col < 0 || col == mat[row].length) // boundaries
return Integer.MAX_VALUE;
if (mat[row][col] <= prev || mat[row][col] == -999) // if the sequence is not ascending or if we have been in this cell before
return Integer.MAX_VALUE;
if (row == mat.length - 1 && col == mat[row].length - 1)
return counter + 1;
int temp = mat[row][col];
mat[row][col] = -999;
int up = shortestPath(mat, row - 1, col, temp, counter + 1); // go up and count
int down = shortestPath(mat, row + 1, col, temp, counter + 1);
int left = shortestPath(mat, row, col - 1, temp, counter + 1);
int right = shortestPath(mat, row, col + 1, temp, counter + 1);
mat[row][col] = temp;
return Math.min(Math.min(up, down), Math.min(left, right)); // get the min
}

find average of a matrix in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to find average of each 8 element in a 2D-matrix(5×5) and replace it in element number(9) ?
in java programming (OOP)
in frist code should be like this
and For example :
(source: 0zz0.com)
So I just did it for fun, here's my code. It would work for any size matrix.
public class Matrixer
{
final double[][] matrix, computedMatrix;
final int rows, cols;
public Matrixer(int N, int M, final double[][] imatrix)
{
rows = N;
cols = M;
matrix = imatrix;
computedMatrix = new double[N][M];
}
public void computeAverages()
{
for (int i = 1; i < rows - 1; i++)
{
for (int j = 1; j < cols - 1; j++)
{
computedMatrix[i][j] = cellNeighborsAverage(i, j);
}
}
}
private double cellNeighborsAverage(int row, int col)
{
// Ignore center cell
double sum = matrix[row - 1][col - 1] + matrix[row - 1][col]
+ matrix[row - 1][col + 1] + matrix[row][col - 1]
+ matrix[row][col + 1] + matrix[row + 1][col - 1]
+ matrix[row + 1][col] + matrix[row + 1][col + 1];
return sum / 8;
}
public void printComputedMatrix()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.printf("%.2f", computedMatrix[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
public static void main(String[] args)
{
final double[][] matrix =
{
{1, 2, 3, 4, 5},
{5, 4, 3, 5, 1},
{3, 2, 2, 3, 4},
{2, 3, 4, 5, 3},
{3, 2, 4, 5, 6},
};
Matrixer mx = new Matrixer(5, 5, matrix);
mx.computeAverages();
mx.printComputedMatrix();
}
}
Test Output:
0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 2.63, 3.13, 3.13, 0.00,
0.00, 3.25, 3.63, 3.38, 0.00,
0.00, 2.75, 3.25, 3.88, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00
Pseudocode, as this is not really a Java-specific question:
var myMatrix = [
[ x, x, x, x, x],
[ x, x, x, x, x],
[ x, x, x, x, x],
[ x, x, x, x, x],
[ x, x, x, x, x] ];
function neighborAverage(row, col) {
return (( myMatrix[row-1][col-1] +
myMatrix[row-1][col] +
myMatrix[row-1][col+1] +
myMatrix[row][col-1] +
// skip the center element
myMatrix[row][col+1] +
myMatrix[row+1][col-1] +
myMatrix[row+1][col] +
myMatrix[row+1][col+1]) / 8));
}
function matrixAverage() {
return ([
[ neighborAverage(1, 1), neighborAverage(1, 2), neighborAverage(1, 3) ],
[ neighborAverage(2, 1), neighborAverage(2, 2), neighborAverage(2, 3) ],
[ neighborAverage(3, 1), neighborAverage(3, 2), neighborAverage(3, 3) ] ]);
}
Two notes:
hardcoded indices in matrixAverage() means this pseudocode will only work with a matrix of size 5x5. But it shouldn't be too hard to generalize that function to work with matrices of any size.
this pseudocode calculates all the averages but does not overwrite any values in the original matrix. That might or might not be what you want, as you didn't specify if each new value should be used to calculate subsequent values (and if so, in what order the values should be calculated).

How to improve Javafx 3d performance?

I am doing a javafx visualisation application for 3d points. As I am new to javafx, I started from the tutorial provided in the oracle website:
http://docs.oracle.com/javase/8/javafx/graphics-tutorial/javafx-3d-graphics.htm#JFXGR256
The example above runs perfect on my Mac, But after adding more points, the mouse drag, which causes the camera to rotate and thus people can view the objects from different angle, became very slow and simply not applicable any more.
I currently have a data for a rabbit with about 40000 points:
The code I used to rotate camera:
cameraXform.ry.setAngle(cameraXform.ry.getAngle() - mouseDeltaX * MOUSE_SPEED * modifier * ROTATION_SPEED);
cameraXform.rx.setAngle(cameraXform.rx.getAngle() + mouseDeltaY * MOUSE_SPEED * modifier * ROTATION_SPEED);
which is the same as in the oracle example.
What I have tried:
set JVM flag -Djavafx.animation.fullspeed=true, this helped a bit, but not significant.
set JVM flag -Djavafx.autoproxy.disable=true, this did not help.
set Cache to true and CacheHint to Cache.SPEED, this did not make much difference.
create another thread to do the rotation, and sync back after calculation, this did not help neither.
Any help is appreciated.Thanks in advance!
Here is how I made a point cloud using tetrahedrons in a triangle mesh. seems to run faster than using spheres or squares. this code helped me scalafx google code
import java.util.ArrayList;
import javafx.scene.shape.TriangleMesh;
public class TetrahedronMesh extends TriangleMesh {
private ArrayList<Point3i> vertices;
private int[] facesLink;
public TetrahedronMesh(double length, ArrayList<Point3i> v) {
this.vertices = v;
if (length > 0.0) {
float[] points = new float[vertices.size() * 12];
int[] faces = new int[vertices.size() * 24];
facesLink = new int[vertices.size() * 4];
float[] texCoords = new float[vertices.size() * 12];
int vertexCounter = 0;
int primitiveCounter = 0;
int pointCounter = 0;
int facesCounter = 0;
int texCounter = 0;
for (Point3i vertex : vertices) {
vertex.scale(100);
points[primitiveCounter] = vertex.x;
points[primitiveCounter + 1] = (float) (vertex.y - (length
* Math.sqrt(3.0) / 3.0));
points[primitiveCounter + 2] = -vertex.z;
points[primitiveCounter + 3] = (float) (vertex.x + (length / 2.0));
points[primitiveCounter + 4] = (float) (vertex.y + (length
* Math.sqrt(3.0) / 6.0));
points[primitiveCounter + 5] = -vertex.z;
points[primitiveCounter + 6] = (float) (vertex.x - (length / 2.0));
points[primitiveCounter + 7] = (float) (vertex.y + (length
* Math.sqrt(3.0) / 6.0));
points[primitiveCounter + 8] = -vertex.z;
points[primitiveCounter + 9] = vertex.x;
points[primitiveCounter + 10] = vertex.y;
points[primitiveCounter + 11] = (float) -(vertex.z - (length * Math
.sqrt(2.0 / 3.0)));
faces[facesCounter] = pointCounter + 0;
faces[facesCounter + 1] = pointCounter + 0;
faces[facesCounter + 2] = pointCounter + 1;
faces[facesCounter + 3] = pointCounter + 1;
faces[facesCounter + 4] = pointCounter + 2;
faces[facesCounter + 5] = pointCounter + 2;
faces[facesCounter + 6] = pointCounter + 1;
faces[facesCounter + 7] = pointCounter + 1;
faces[facesCounter + 8] = pointCounter + 0;
faces[facesCounter + 9] = pointCounter + 0;
faces[facesCounter + 10] = pointCounter + 3;
faces[facesCounter + 11] = pointCounter + 3;
faces[facesCounter + 12] = pointCounter + 2;
faces[facesCounter + 13] = pointCounter + 2;
faces[facesCounter + 14] = pointCounter + 1;
faces[facesCounter + 15] = pointCounter + 1;
faces[facesCounter + 16] = pointCounter + 3;
faces[facesCounter + 17] = pointCounter + 4;
faces[facesCounter + 18] = pointCounter + 0;
faces[facesCounter + 19] = pointCounter + 0;
faces[facesCounter + 20] = pointCounter + 2;
faces[facesCounter + 21] = pointCounter + 2;
faces[facesCounter + 22] = pointCounter + 3;
faces[facesCounter + 23] = pointCounter + 5;
facesLink[pointCounter] = vertexCounter;
facesLink[pointCounter + 1] = vertexCounter;
facesLink[pointCounter + 2] = vertexCounter;
facesLink[pointCounter + 3] = vertexCounter;
texCoords[texCounter] = 0.5f;
texCoords[texCounter + 1] = 1.0f;
texCoords[texCounter + 2] = 0.75f;
texCoords[texCounter + 3] = (float) (1.0 - Math.sqrt(3.0) / 4.0);
texCoords[texCounter + 4] = 0.25f;
texCoords[texCounter + 5] = (float) (1.0 - Math.sqrt(3.0) / 4.0);
texCoords[texCounter + 6] = 1.0f;
texCoords[texCounter + 7] = 1.0f;
texCoords[texCounter + 8] = 0.5f;
texCoords[texCounter + 9] = (float) (1.0 - Math.sqrt(3.0) / 2.0);
texCoords[texCounter + 10] = 0.0f;
texCoords[texCounter + 11] = 1.0f;
vertexCounter++;
primitiveCounter += 12;
pointCounter += 4;
facesCounter += 24;
texCounter += 12;
}
getPoints().setAll(points);
getFaces().setAll(faces);
getTexCoords().setAll(texCoords);
// getFaceSmoothingGroups().setAll(0, 1, 2, 3);
}
}
public Point3i getPointFromFace(int faceId) {
return vertices.get(facesLink[faceId]);
}
}
Point3i code as follows
public class Point3i {
public int x;
public int y;
public int z;
public Point3i() {
x = 0;
y = 0;
z = 0;
}
}
Picking the point using the scene
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
PickResult pr = me.getPickResult();
int faceId = pr.getIntersectedFace();
if (faceId != -1) {
Point3i p = tetrahedronMesh.getPointFromFace(faceId);
}
}
});
I know this is old, But for others ..
Instead of creating a new shape all together, each of the predefined shapes
Sphere, Box, Cylinder, allow you to set the number of divisions in the constructor.
Sphere for example defaults to 64 divisions, 32 for longitude, 32 for latitude.
you can easily do ... = new Sphere(radius, divisions); (4 is the minimum I believe for Sphere).
Something that helps a lot is to set the mouse transparent on the root with:
root3D.setMouseTransparent(true);
This obviously disables clicking or hovering on objects of the view (i.e PickResult is null). The solution for that is to temporarily enable it when there is a click for example and simulate another identical click with impl_processMouseEvent.
#Override
public void handle(MouseEvent event) {
try {
if (event.getEventType() == MouseEvent.MOUSE_CLICKED
&& event.isStillSincePress()
&& (event.getTarget() == scene3d || event.getTarget() instanceof Shape3D)) {
Parent root3D = scene3d.getRoot();
// if the 3D scene has been set to mouse transparent,
// then we send another event and we disable the transparency temporarily
if (root3D.isMouseTransparent()) {
root3D.setMouseTransparent(false);
try {
scene3d.impl_processMouseEvent(event);
}
finally {
root3D.setMouseTransparent(true);
}
}
else {
// here you get the pick result you need :)
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}

Recursive function StackOverflowError

I am coding Zombies infect people in a city whereas:
2: There is no person
1: Uninfected people
0: Zombies
Zombies will infect all normal people that are around Zombies.
Below is my Java program but I am getting the error: StackOverflowError.
public class InfectGame {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[][] = { { 1, 1, 1, 1, 2, 2, 2, 1, 1, 0 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 2, 1, 1, 2, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 2, 1 },
{ 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 2, 2, 2, 1, 1, 1, 1, 1, 1, 2 }, };
int i = 0;
int j = 0;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
if (a[i][j] == 0) {
run_test(i, j, a, 0, 10);
}
}
}
i = 0;
j = 0;
for (i = 0; i < 10; i++) {
System.out.print("\n");
for (j = 0; j < 10; j++) {
System.out.print(a[i][j] + " ");
}
}
}
public static void run_test(int x, int y, int a[][], int v, int size) {
if ((x < 0) || (x >= size))
return;
if ((y < 0) || (y >= size))
return;
// System.out.print(a[x][y] + " ");
// a[x][y] = v;
if (a[x][y] != 2) {
a[x][y] = v;
if (x + 1 < size) {
run_test(x + 1, y, a, v, size);
}
if (x > 0) {
run_test(x - 1, y, a, v, size);
}
if (y + 1 < size) {
run_test(x, y + 1, a, v, size);
}
if (y > 0) {
run_test(x, y - 1, a, v, size);
}
}
}
}
Exception in thread "main" java.lang.StackOverflowError
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
........................................................
Recursion only works if you have terminating conditions.
You don't have them. Look at this part of your code:
if (x + 1 < size) {
run_test(x + 1, y, a, v, size);
}
if (x > 0) {
run_test(x - 1, y, a, v, size);
}
The first if statement will recurse until you've hit the end of the grid on the current line. At that point, it will go to the second if statement and recurse again, but one step back to the left. But on the next recursion, it will go one step to the right again, ad infinitum.
That's why you get the error - you never terminate your recursion.
Now that you explained that you are trying to do a flood fill, I can see which terminating condition you need:
if (a[x][y] != 2) {
Should be:
if (a[x][y] != 2 && a[x][y] != v) {
Otherwise you keep filling the same squares with zombies over and over again.
But thinking more about your problem of zombies, it is a bit different from an ordinary fill. In a fill, if a pixel already has the colour your want, you can stop the recursion.
For zombies that is not true for the first zombie - from this zombie it spreads out. So the first iteration should not check whether it is already a zombie, but any further iteration of the recursion should check, or else it doesn't terminate.
You can do it like this:
public static void run_test(int x, int y, int a[][], int v, int size, boolean first) {
if ((x < 0) || (x >= size))
return;
if ((y < 0) || (y >= size))
return;
if (a[x][y] != 2 && (first || a[x][y] != v)) {
a[x][y] = v;
if (x + 1 < size) {
run_test(x + 1, y, a, v, size, false);
}
if (x > 0) {
run_test(x - 1, y, a, v, size, false);
}
if (y + 1 < size) {
run_test(x, y + 1, a, v, size, false);
}
if (y > 0) {
run_test(x, y - 1, a, v, size, false);
}
}
}
And the invocation from the main method should read:
run_test(i, j, a, 0, 10, true);
You stuck here:
if (x + 1 < size) {
run_test(x + 1, y, a, v, size);
}
if (x > 0) {
run_test(x - 1, y, a, v, size);
}
Because x is always the first or second if- condition.
You should use better variable names. Use something that describes the variable instead of x, y, z.

Categories

Resources