What am I missing in my solution? Convex Hull Finding Algorithm - java

I have been racking my brain around this problem for days now... I can't see what my algorithm could possibly be missing. This is the problem here.
From what I gather I am getting the points in a somewhat circular ccw order. So I've implemented a version of the graham scan that goes through looking to find the convex hull by ensuring it is using points that always give right-hand turns.
My algorithm works for all given test input and all input I can come up for it but it just won't get accepted by the online judge which is what is required for the assignment to be 'complete'.
Anyways, here is my code I would be forever in your debt if someone can find what I'm missing.
import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public Main() {}
public void handlePoints(Point[] points) throws Exception {
int m = 1;
Vector<Point> convexHull = new Vector<Point>();
// This is THE ONLY gaurunteed point to be in the hull - and it is the lowest left point so that's ok.
convexHull.add(points[0]);
// Can be removed if ill-suited.
convexHull.add(points[1]);
for (int i = 2; i < points.length; i++) {
// Find the next valid point on the hull.
while (counterClockWise(convexHull.elementAt(m-1), convexHull.elementAt(m), points[i]) <= 0) {
convexHull.removeElementAt(m);
if (m > 1) {
m -= 1;
}
// All points are colinear
else if (i == points.length - 1) {
break;
}
else {
convexHull.add(points[i]);
i++;
}
}
convexHull.add(points[i]);
m++;
}
if (convexHull.size() <= 3) {
throw new Exception();
}
String test = "" + convexHull.size() + '\n';
for (Point p : convexHull) {
test += p.x + " " + p.y + '\n';
}
System.out.print(test);
}
// Simply calculated whether or not the 3 points form a countedClockWise turn.
public int counterClockWise(Point p1, Point p2, Point p3) {
return ((p2.x - p1.x) * (p3.y - p1.y)) - ((p2.y - p1.y) * (p3.x - p1.x));
}
// Rearranges the array to maintain its order but be started and ended by the point with the lowest y value
private static Point[] moveLowestToFront(Point[] array) {
// Rearrange for y:
int lowestY = 99999;
int lowestIndex = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].y < lowestY) {
lowestY = array[i].y;
lowestIndex = i;
}
}
// Scan through again to see if there are any competing low-y values.
int lowestX = 99999;
for (int i = 0; i < array.length; i++) {
if (array[i].y == lowestY) {
if (array[i].x < lowestX) {
lowestX = array[i].x;
lowestIndex = i;
}
}
}
Point[] rearrangedPoints = new Point[array.length];
int j = 0;
// Take from low to end cutting off repeated start point.
for (int i = lowestIndex; i < array.length - 1; i++) {
rearrangedPoints[j] = array[i];
j++;
}
// Throw the remaining and put them at the end.
for (int i = 0; i < lowestIndex; i++) {
rearrangedPoints[j] = array[i];
j++;
}
// End the array with the repeated first point.
rearrangedPoints[array.length - 1] = array[lowestIndex];
return rearrangedPoints;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
Main convexHullFinder = new Main();
int numDataSets = sc.nextInt();
System.out.println(numDataSets);
for (int z = 0; z < numDataSets; z++) {
int numPoints = sc.nextInt();
Vector<Point> points = new Vector<Point>();
// Read in all the points for this set.
points.add(new Point(sc.nextInt(), sc.nextInt()));
int j = 1;
for (int i = 1; i < numPoints; i++) {
Point p = new Point(sc.nextInt(), sc.nextInt());
// Remove repeated points.
if (p.x < 0 || p.y < 0) {
throw new Exception();
}
if ( (p.x == points.elementAt(j-1).x) && (p.y == points.elementAt(j-1).y) ) {}
else {
points.add(p);
j++;
}
}
Point[] reducedPoints = points.toArray(new Point[points.size()]);
// Rearrange the set to start and end on the lowest Y point.
reducedPoints = moveLowestToFront(reducedPoints);
if (numPoints >= 3) {
convexHullFinder.handlePoints(reducedPoints);
}
else {
throw new Exception();
}
try {
System.out.println(sc.nextInt());
}
catch (Exception e) {
}
}
}
}
class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

From the sounds of it, the points are sorted such that Graham Scan applies. Therefore, I think your stack operation (handlePoints) is probably not right.
I'm more used to Andrew's algorithm (a modification of Graham Scan), but I'm fairly sure you shouldn't be adding points to the convex hull both inside and outside of the while loop. The reason being I'm fairly sure the purpose of the while loop remains the same regardless of which algorithm is used. It's to remove invalid points from the convex hull. However, there's a chance that you're adding points during the while loop.
I'm not sure that's all that needs fixed though, but I don't have anything set up to run Java at the moment.

Related

Transferring code from notepad ++ to command prompt

I'm relatively new to java, so I wouldn't be surprised if I'm missing something obvious here. Anyways, I made a code that finds the roots of a polynomial using the Bisection method. I thought the program was all well and dandy until I pasted it from notepad++ to command prompt, where I ended up getting a bunch of "class, interface, or enum expected" errors after compiling it using javac. Everything seems fine in the code itself, so I've deduced that I've made one of the following two errors: either something wrong occurred while I was copying and pasting into command prompt, or I actually did create an error in my code that I didn't catch. Could someone tell me just what I did wrong? It may be a minor fix, but I just don't know how to change it to get my code to work. Here's the code:
import java.util.*;
class Roots {
public static int degree;
public static double[] coArrayC;
public static double[] coArrayD;
public static int coeffVal;
public static void main( String[] args ){
double resolution = 0.01;
double tolerance = 0.0000001;
double threshold = 0.001;
double rightEndPt;
double leftEndPt;
int polyRootPointer = 0;
int diffRootPointer = 0;
boolean rootAns = false;
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter the degree: "); //prompts user to enter the correct degree of the polynomial
degree = sc.nextInt();
coeffVal = degree + 1; //the coefficient is one more than the number of degrees
System.out.print("Enter " + coeffVal + " coefficients: "); //adds in the value of the polynomial coefficient in to the line that prompts the user to specify which coefficients are in the function
double[] coefficients = new double[coeffVal]; //initialization of array, a bunch of doubles that represent the coefficients of the user's polynomial
coArrayC = new double[coeffVal]; //naming the array
double[] rootArray = new double[degree];//another array for the degrees of the polynomial
coArrayD = new double[coeffVal]; //and assigning it a name
for(int i = 0; i < coeffVal; i++) {
coefficients[i] = sc.nextDouble();
}
System.out.print("Enter the right and left endpoints, in that order: "); //prompts user to enter the interval limits
rightEndPt = sc.nextDouble();
leftEndPt = sc.nextDouble();
diff(coefficients); //calculates coefficients of derivative polynomial
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){ //
if (isPositive(coArrayD, i) != isPositive(coArrayD, i+resolution) || isPositive(coArrayD, i) == 0) {
rootArrayDeriv[diffRootPointer] = findRoot(coArrayD, i, i+resolution, tolerance);
diffRootPointer++;
}
}
for (int i = 0; i < rootArrayDeriv.length; i++) {
double tempValue;
tempValue = poly(coefficients, rootArrayDeriv[i]);
tempValue = Math.abs(tempValue);
if (tempValue < threshold) {
rootArray[polyRootPointer] = rootArrayDeriv[i];
polyRootPointer++;
rootAns = true;
}
}
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coefficients, i) != isPositive(coefficients, i+resolution) || isPositive(coefficients, i) == 0) {
rootArray[polyRootPointer] = findRoot(coefficients, i, i+resolution, tolerance);
polyRootPointer++;
rootAns = true;
}
}
//Arrays.sort(rootArray); //sorts array from lowest to highest
if (rootAns == true) {
System.out.println("Sorry - no roots were found in the specified interval.");
}
}
} else {
for (int i = 0; i < rootArray.length; i++) {
if (rootArray[i] != 0.0) {
System.out.printf("Root found at %.5f\n :" Arrays.sort(rootArray[i])); //if roots are found, list them as an output, with five decimal places of accuracy
}
}
static double poly(double[] C, double x){
double polySum = 0;
coArrayC[0] = C[0];
for (int i = 1; i < coArrayC.length; i++){
coArrayC[i] = C[i]*(Math.pow(x, i)); //multiplies each coefficient by the designated power of X
}
for (int i = 0; i < coArrayC.length; i++){
polySum = polySum + coArrayC[i]; //accumulates the sum of of all the terms, after the coeff. were multiplied to their respective powers.
}
return(polySum);
}
static double[] diff(double[] C){
for (int i = 0; i < degree; i++){
coArrayD[i] = (i+1)*C[i+1]; //newly allocated array D containing coeff. of the polynomial that is the derivative of the polynomial with coeff. array C.
}
return(coArrayD);
}
static double findRoot(double[] C, double a, double b, double tolerance){ //using bisection method; similar to findRoot.java in cmps webpage.
double root = 0.0 , residual;
while ( Math.abs(b - a) > tolerance ) {
root = (a + b) / 2.0;
residual = poly(C, root);
if (poly(C, a) < 0 && poly(C, b) < 0) {
if (residual > 0)
b = root;
else
a = root;
} else if (poly(C, a) > 0 && poly(C, b) > 0) {
if (residual > 0)
a = root; //replace left endpoint
else
b = root; //replace right endpoint
}
}
return(root);
}
static int isPositive(double[] C, double a){
double endpointTempA;
endpointTempA = poly(C, a);
if (endpointTempA < 0) {
return(1);
} else if (endpointTempA > 0) {
return(2);
} else {
return(0);
}
}
}
You have two } too many here:
if (rootAns == true) {
System.out.println("Sorry - no roots were found in the specified interval.");
}
}
} else {
If you indent your code properly, it's easier to see these kinds of errors. Remove the two } that don't belong there:
if (rootAns == true) {
System.out.println("Sorry - no roots were found in the specified interval.");
} else {
There's also a missing , here, and you shouldn't pass a single double to Arrays.sort, but the whole array
System.out.printf("Root found at %.5f\n :"Arrays.sort(rootArray[i]));
Should be:
System.out.printf("Root found at %.5f\n :", Arrays.sort(rootArray));
And a missing }.
Instead of writing a whole program at once and then trying to compile it, write it little by little, and compile it each time you have for example a complete method. That way you avoid getting a mountain of little errors that confuse you.

Calculating next frame in conways game of life using java

trying to create a Conways Game of life, but apparently the shapes are not like they have to be. Perhaps someone can help me find the issue.
For example the glider :
- X - - - -
- - X X - -
- X X - - -
- - - - - -
becomes this
- - X X - -
- X - - - -
X X X - - -
- X X X - -
but should be like this :
- - X - - -
- - - X - -
- X X X - -
- - - - - -
And my code looks like this
public Frame(int x, int y) {
setWidth(x);
setHeight(y);
if (x<1)
frame = null;
else if (y<1)
frame = null;
else {
frame = new String [x][y];
for (int i=0; i<frame.length; i++) {
for (int j=0; j<frame[i].length; j++) {
frame [i][j] = DEAD;
}
}
} // else
} // construktor
public Integer getNeighbourCount(int x, int y) {
Frame cell = new Frame(getHeight(), getWidth());
int counter = 0;
if(frame[x][y].equals(ALIVE))
{
counter = counter - 1;
}
for(int i=x-1; i<=x+1;i++){
if(i<frame.length && i>0){
for(int j=y-1; j<=y+1;j++){
if(j<frame[i].length && j>0){
if (frame[i][j]==ALIVE) {
counter++;
}
}
}
}
}
return counter;
}
public Frame nextFrame() {
// Returns next frame
Frame cell = new Frame(getWidth(), getHeight());
//cell.frame = new String[getWidth()][getHeight()];
for(int i = 0; i < frame.length; i++){
for(int j =0; j <frame[i].length;j++){
int n = getNeighbourCount(i,j);
if(cell.frame[i][j]==null) {
cell.frame[i][j] = DEAD;
}
if (isAlive(i, j) && n < 2 || n > 3) {
cell.frame[i][j] = DEAD;
}
if (isAlive(i, j) && n == 3 || n == 2){
cell.frame[i][j] = ALIVE;
}
if(!isAlive(i, j) && n == 3) {
cell.frame[i][j] = ALIVE;
}
if(isAlive(i, j) && n > 3){
cell.frame[i][j] = DEAD;
}
frame[i][j] = cell.frame[i][j];
}
}
cell.toString();
return cell;
}
`
Full code http://pastebin.com/LMwz724H
Here's a solution that works - using an enum for each cell and getting the i/j and x/y stuff right (I think). It certainly generates the correct first iteration:
static class GameOfLife {
final int w;
final int h;
State[][] frame;
enum State {
Dead, Alive;
}
public GameOfLife(int w, int h) {
this.w = w;
this.h = h;
frame = new State[h][w];
}
public void alive(int x, int y) {
frame[y][x] = State.Alive;
}
public void tick() {
frame = nextGeneration();
}
private int surroundingPopulation(int x, int y) {
int pop = 0;
for (int i = y - 1; i <= y + 1; i++) {
for (int j = x - 1; j <= x + 1; j++) {
// On frame - vertically.
if ((i >= 0 && i < h)
// On frame horizontally.
&& (j >= 0 && j < w)
// Alive
&& (frame[i][j] == State.Alive)
// Not the center.
&& (i != y || j != x)) {
pop += 1;
}
}
}
return pop;
}
private State[][] nextGeneration() {
State[][] next = new State[h][w];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int pop = surroundingPopulation(x, y);
// Any live cell
if (frame[y][x] == State.Alive) {
if (pop < 2) {
// ... with fewer than two live neighbours dies, as if caused by under-population.
next[y][x] = State.Dead;
} else if (pop > 3) {
// ... with more than three live neighbours dies, as if by overcrowding.
next[y][x] = State.Dead;
} else {
// ... with two or three live neighbours lives on to the next generation.
next[y][x] = State.Alive;
}
} else {
// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
if (pop == 3) {
next[y][x] = State.Alive;
}
}
}
}
return next;
}
#Override
public String toString() {
StringBuilder s = new StringBuilder();
for (State[] row : frame) {
for (State c : row) {
s.append(c == State.Alive ? "X" : " ");
}
s.append("\r\n");
}
return s.toString();
}
}
public void test() {
GameOfLife g = new GameOfLife(6, 6);
g.alive(1, 0);
g.alive(2, 1);
g.alive(3, 1);
g.alive(1, 2);
g.alive(2, 2);
System.out.println("Before:\r\n" + g);
g.tick();
System.out.println("After:\r\n" + g);
}
I believe the problem is that you are copying the new value as you iterate through the loop. This means neighbours are using the value from the next tick rather than the current one.
You can fix this by waiting until you calculated all new values in your new frame: cell.frame and then iterate through the frame again and copy from cell.frame to frame.
An alternative (better in my view) is to have away of cloning a frame during construction. Then you could change your nextFrame method to create a clone of frame and use the clone to set the new values in frame.
You are changing the DEAD and ALIVE frames while you iterate through the grid. You need to store the coordinates which should die or become alive and perform that afterwards.
Store the coordinates in two ArrayLists (dead, alive). The first and second position is the x and y axis, and change those coordinates according to whether they should become alive or not.
Here's a snippet from a simple test I wrote a while back. As others have mentioned, don't change values on an active board while still reading them. Instead, clone the board and make changes to the copy while reading the current board.
Another problem I bumped into a few times was iterating over y, then x for each y, but referring to x,y when accessing a point. It feels back to front :)
// Rules:
// 1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.
// 2) Any live cell with two or three live neighbours lives on to the next generation.
// 3) Any live cell with more than three live neighbours dies, as if by overcrowding.
// 4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
void mutateGrid() {
// Copy existing grid into the next generation's grid
boolean[][] mutatedGrid = new boolean[gridXWidth][gridYHeight];
for (int i = 0; i < gridXWidth; i++) {
System.arraycopy(grid[i], 0, mutatedGrid[i], 0, gridYHeight);
}
// Start mutation rules
for (int y = 0; y < gridYHeight; y++) {
for (int x = 0; x < gridXWidth; x++) {
int liveNeighbours = countLiveNeighbours(x,y);
if (liveNeighbours < 2 || liveNeighbours > 3) {
mutatedGrid[x][y] = false;
}
else if (liveNeighbours == 3) {
mutatedGrid[x][y] = true;
}
}
}
grid = mutatedGrid;
}
int countLiveNeighbours(int x, int y) {
int count = 0;
for (int j = y-1; j <= y+1; j++) {
for (int i = x-1; i <= x+1; i++) {
if (i < 0 || j < 0 || i >= gridXWidth || j >= gridYHeight){
continue;
}
if (grid[i][j]) {
count++;
}
}
}
count -= grid[x][y]?1:0; // remove self from count
return count;
}

Java finding full routes in NxN grid [duplicate]

This question already has answers here:
How do I do a deep copy of a 2d array in Java?
(7 answers)
Closed 8 years ago.
So I am trying to make an algorithm for finding full paths in NxN grid. For example in 1x1 grid there is 1 possible path, in 2x2 grid there is 1, in 3x3 there is 2 and in 4x4 there is 8. The idea is to find scenarios where we can fill every spot of the grid by moving.
I have made a recursive function for the job and here is the code:
public static int getRoutesHelp(int[][] table, int x, int y)
{
if(x > table.length-1 || x < 0 || y < 0 || y > table.length-1)
return 0;
if(table[x][y] == 1)
return 0;
table[x][y] = 1;
if(isDeadEnd(table, x, y))
{
if(isTableFull(table))
return 1;
}
else
{
int a = getRoutesHelp(table, x-1, y);
int d = getRoutesHelp(table, x, y+1);
int b = getRoutesHelp(table, x+1, y);
int c = getRoutesHelp(table, x, y-1);
return a+b+c+d;
}
return 0;
}
public static int getRoutes(int size)
{
int[][] table = new int[size][size];
// init table
for(int i = 0; i < size; i++)
{
for(int a = 0; a < size; a++)
{
table[i][a] = 0;
}
}
return getRoutesHelp(table, 0 ,0);
}
So basically I start from 0.0 and start moving to all possible directions and by repeating this I get the amount of successful routes. The problem is that after the assignment of int d the original table is somehow filled with 1 but it should be empty as far as I understand because java passes a copy of the table right? I've been fighting with this for like 4 hours and can't really find the problem so any help is appreciated. Empty slots in table are marked with 0 and filled slots with 1.
EDIT: I managed to fix the issue I had with the copying and now my other problem is that with 5x5 grid my algorithm returns 52 routes and it should be 86. So it works with 4x4 grid okay, but once I move further it breaks.
Added the isDeadEnd function here
public static boolean isDeadEnd(int[][] table, int x, int y)
{
int toCheck[] = new int[4];
toCheck[0] = x-1; // left
toCheck[1] = y-1; // top
toCheck[2] = x+1; // right
toCheck[3] = y+1; // bottom
int valuesOfDirections[] = new int[4]; // left, top, right, bottom
for(int i = 0; i < 4; i++)
{
int tarkastettava = toCheck[i];
if(tarkastettava > table.length-1 || tarkastettava < 0)
{
valuesOfDirections[i] = 1;
}
else
{
if(i == 0 || i == 2)
{
valuesOfDirections[i] = table[tarkastettava][y];
}
else
{
valuesOfDirections[i] = table[x][tarkastettava];
}
}
}
for(int i = 0; i < 4; i++)
{
if(valuesOfDirections[i] == 0)
{
return false;
}
}
return true;
}
Come to think of it, you probably can do a simple backtrack here:
table[x][y] = 1;
if(isDeadEnd(table, x, y)) {
if(isTableFull(table))
return 1;
}
table[x][y] = 0;
}
And later:
int res = a + b + c + d;
if (res == 0) {
// backtrack here too
table[x][y] = 0;
}
return res;

Maze not working?

code:
Array is a predefined boolean array that I made, and val is the length of the array (it is a square). I use it as a starting point, rather than using a random value
import java.util.*;
import javax.swing.*;
public class Main
{
public void main()
{
String Val = JOptionPane.showInputDialog("Enter the number of rows/columns");
int x = Integer.parseInt(Val);
boolean mazeArch[][] = new boolean [x][x];
BoundariesDeclared(mazeArch, x);
generateMaze(mazeArch, x);
convertArray(mazeArch, x);
}
public void printArray(String Array[][]) // Prints out the array
{
for (int i =0; i < Array.length; i++) {
for (int j = 0; j < Array.length; j++) {
System.out.print(" " + Array[i][j]);
}
System.out.println("");
}
}
public void convertArray(boolean Array[][], int z)
{
String RealArray[][] = new String [z][z];
for(int x = 0; x < Array.length; x++)
{
for(int y = 0; y < Array.length; y++)
{
if(Array[x][y] == true)
{
RealArray[x][y] = "*";
}
if(Array[x][y] == false)
{
RealArray[x][y] = " ";
}
}
}
printArray(RealArray);
}
public void BoundariesDeclared(boolean Array[][], int y)
{
for(int x = 0; x < Array.length; x++)
Array[0][x] = true;
for (int x = 0; x < Array.length; x++)
Array[x][0] = true;
for (int x = 0; x < Array.length; x++)
Array[x][Array.length-1] = true;
for (int x = 0; x < Array.length; x++)
Array[Array.length-1][x] = true;
}
public void generateMaze(boolean Array[][], int val)
{
Stack<Integer> StackX = new Stack<Integer>();
Stack<Integer> StackY = new Stack<Integer>();
int x = val / 2; // Start in the middle
int y = val / 2; // Start in the middle
StackX.push(x);
StackY.push(y);
while(!StackX.isEmpty())
{
Array[x][y] = true; // is Visited
x = StackX.peek();
y = StackY.peek();
if(Array[x][y+1] == false)
{
StackX.push(x);
StackY.push(y+1);
y = y + 1;
}
else if(Array[x][y-1] == false)
{
StackX.push(x);
StackY.push(y-1);
y = y - 1;
}
else if(Array[x+1][y] == false)
{
StackX.push(x+1);
StackY.push(y);
x = x+1;
}
else if(Array[x-1][y] == false)
{
StackX.push(x-1);
StackY.push(y);
x = x-1;
}
else
{
StackX.pop();
StackY.pop();
}
}
}
}
Whenever I print the results, I only get stars, which mean that every single boolean is set to true. I understand my error, because I am visiting every spot the result will be that they are all set to true. But what can i do to fix this? I think I have the concept correct, just not the application. I previously asked the question and was told that I need to make two Arrays (1 for walls, another for visiting) but how would I apply this as well?
You didn't mention what are you trying to do. So not much we can help.
What is this maze doing?
What's your input?
What's your expected result?
Add this line and debug yourself.
public void generateMaze(boolean Array[][], int val) {
Stack<Integer> StackX = new Stack<Integer>();
Stack<Integer> StackY = new Stack<Integer>();
int x = val / 2; // Start in the middle
int y = val / 2; // Start in the middle
StackX.push(x);
StackY.push(y);
while (!StackX.isEmpty()) {
Array[x][y] = true; // is Visited
x = StackX.peek();
y = StackY.peek();
if (Array[x][y + 1] == false) {
StackX.push(x);
StackY.push(y + 1);
y = y + 1;
} else if (Array[x][y - 1] == false) {
StackX.push(x);
StackY.push(y - 1);
y = y - 1;
} else if (Array[x + 1][y] == false) {
StackX.push(x + 1);
StackY.push(y);
x = x + 1;
} else if (Array[x - 1][y] == false) {
StackX.push(x - 1);
StackY.push(y);
x = x - 1;
} else {
StackX.pop();
StackY.pop();
}
convertArray(Array, val); // add this line
}
}
The solution is still the same as when you last posted this question - you need to have two arrays
-one that is true for every place in the maze that is a wall - the maze's tiles
-one that starts all false - the solver's tiles
The solver can move onto a tile only if both arrays are false at that point, and sets the second array (the solver's tiles) to true while leaving the first array (the maze's tiles) alone.
This is not a 'coding' bug, per say. You simply don't know what behavior you want. Try commenting out the line where you generate the maze. Run your program with 6 as a parameter. You get:
* * * * * *
* *
* *
* *
* *
* * * * * *
What kind of maze is this? Where is the exit? Again, this is not a coding issue, this is a design flaw. Of course if you start within the bounds of this maze, you will visit all of the squares!
I'm not clear what do you expect in your output exactly, but I can see where the issue is. In your generateMaze() method you are travelling like in spiral mode which ends up touching each and every node in the end. Like suppose you have 5x5 array, you travel and make true like (boundaries are already true) [2,2]->[2,3]->[3,3]->[3,2]->[3,1]->[2,1]->[1,1]->[1,2]->[1,3]
you start from middle, you start visiting and take turns just before you find already true (boundary or visited), and it covers all the nodes

Java - minimax algorithm issue

I'm working on a tictactoe board for practice making classes and i have ran into a problem with my algorithm. it seems to be returning the best move offensive, but it doesn't play defense. i dont know where i have messed up and cant seem to find it. i have looked over a lot of things on here about it and ive compared it to simular projects, but still can't seem to get it. here is my code.
package TicTacToe;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Solution {
private static GameBoard currentBoard;
private static Player botPlayer;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String player;
System.out.println("ENTER bot: ");
player = in.next();
if(player.equalsIgnoreCase("X")) {
botPlayer = Player.X;}
else {botPlayer = Player.O;}
String board[] = new String[3];
for(int i = 0; i < 3; i++) {
System.out.println("ENTER board: ");
board[i] = in.next();
}
currentBoard = new GameBoard(3,3, board);
List<Space> OpenSpaces = getOpenSquares(currentBoard);
MakeMove(OpenSpaces);
System.exit(-1);
}
public static List<Space> getOpenSquares(GameBoard GB) {
List<Space> OpenSpaces = new ArrayList<Space>();
for(int r = 0; r < 3; r++) {
for(int c = 0; c < 3; c++) {
if(GB.squares[r][c] == Player.Open) {
OpenSpaces.add(new Space(r,c));
}
}
}
return OpenSpaces;
}
private static Space bestMove;
private static Space currentMove;
private static Space previousMove;
private static void MakeMove(List<Space> OpenSpaces) {
if(OpenSpaces.size() == currentBoard.Size) {
Random random = new Random();
bestMove = new Space(random.nextInt(2),2);
} else {
for(Space child: OpenSpaces) {
currentMove = GetBestMove(currentBoard,botPlayer);
if (currentMove != null){
}else{
continue;}
if(previousMove != null && previousMove.Rank < currentMove.Rank ||
previousMove == null && currentMove != null) {
bestMove = currentMove;
}
previousMove = currentMove;
}
}
if (bestMove != null) {
currentBoard.squares[bestMove.X][bestMove.Y] = botPlayer;
System.out.println("the best move is: " + currentMove.X + " " + currentMove.Y);
}
}
private static Space GetBestMove(GameBoard gb, Player p) {
Space bestSpace = null;
List<Space> cloneOpenSpaces = getOpenSquares(gb);
GameBoard cloneBoard = null;
cloneBoard = gb.Clone();
for(Space Open: cloneOpenSpaces) {
cloneBoard = gb.Clone();
Space newSpace = Open;
cloneBoard.squares[newSpace.X][newSpace.Y] = p;
if(cloneBoard.Winner == Player.Open && cloneOpenSpaces.size() > 0) {
Player InP;
if(p == Player.X) {
InP = Player.O;
}else {
InP = Player.X;
}
Space tempMove = GetBestMove(cloneBoard, InP);
if(tempMove != null){
newSpace.Rank = tempMove.Rank;
}
} else {
if(cloneBoard.Winner == Player.Open) {
newSpace.Rank = 0;
}else if(cloneBoard.Winner == Player.O) {
newSpace.Rank = -1;
}else if(cloneBoard.Winner == Player.X) {
newSpace.Rank = 1;
}
}
System.out.println(newSpace.Rank);
if(bestSpace == null ||
(p == Player.X && newSpace.Rank < ((Space)bestSpace).Rank)||
(p == Player.O && newSpace.Rank > ((Space)bestSpace).Rank)) {
bestSpace = newSpace;
}
}
return (Space)bestSpace;
}
public static enum Player {
X (1),
O (-1),
Open (0);
private final double value;
Player(double value){
this.value = value;
}
}
public static class Space {
public int X;
public int Y;
public double Rank;
public Space(int x, int y) {
this.X = x;
this.Y = y;
Rank = 0;
}
public Space() {
}
}
public static class GameBoard {
public int Rows;
public int getRows() {
return this.Rows;
}
public void setRows(int rows) {
Rows = rows;
}
public int Columns;
public int getColumns() {
return this.Columns;
}
public void setColumns(int columns) {
Columns = columns;
}
public Player[][] squares;
//public Player[x][y]
public Player getPlayer(int x, int y) {
return this.squares[x][y];
}
public void setPlayer(int x, int y, Player player) {
squares[x][y] = player;
}
public boolean Full;
public boolean isFull() {
for(int r = 0; r < 2; r++) {
for(int c = 0; c < 2; c++) {
if (squares[r][c] != Player.Open) {return false;}
}
}
return true;
}
public int Size;
public int getSize() {
return this.Size;
}
public void setSize(int size) {
Size = size;
}
public List<Space> OpenSquares;
public List<Space> getOpenSquares() {
List<Space> OpenSquares = new ArrayList<Space>();
for(int r = 0; r < Rows; r++) {
for(int c = 0; c < Columns; c++) {
if(squares[r][c] == Player.Open) {
OpenSquares.add(new Space(r,c));
}
}
}
return this.OpenSquares;
}
public Player Winner;
public Player getWinner() {
int count = 0;
//columns
for (int x = 0; x < Rows; x++)
{
count = 0;
for (int y = 0; y < Columns; y++) {
count += squares[x][y].value;
}
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
}
//rows
for (int x = 0; x < Rows; x++) {
count = 0;
for (int y = 0; y < Columns; y++) {
count += squares[y][x].value;
}
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
}
// Diagonals right to left
count = 0;
count += squares[0][0].value;
count += squares[1][1].value;
count += squares[2][2].value;
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
// Diagonals left to right
count = 0;
count += squares[0][2].value;
count += squares[1][1].value;
count += squares[2][0].value;
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
return Player.Open;
}
public GameBoard Clone() {
GameBoard b = new GameBoard(Rows,Columns);
b.squares = (Player[][])this.squares.clone();
b.Winner = getWinner();
return b;
}
// Class initializer
public GameBoard(int boardRows, int boardColumns, String[] board) {
// Set the dimensions
Rows = boardRows;
Columns = boardColumns;
// Create game spaces
squares = new Player[Rows][Columns];
for(int r = 0; r < Rows; r++) {
for(int c = 0; c < Columns; c++) {
//squares[i][n] = Player.Open;
if(board[r].charAt(c) == 'X') {
squares[r][c] = Player.X;
}
if(board[r].charAt(c) == 'O') {
squares[r][c] = Player.O;
}
if(board[r].charAt(c) == '_') {
squares[r][c] = Player.Open;
}
}
}
this.Winner = getWinner();
this.OpenSquares = getOpenSquares();
//Size of the board
this.Size = Rows * Columns;
}
// clone Class initializer
public GameBoard(int boardRows, int boardColumns) {
// Set the dimensions
Rows = boardRows;
Columns = boardColumns;
// Create game spaces
squares = new Player[Rows][Columns];
for(int r = 0; r < Rows; r++) {
for(int c = 0; c < Columns; c++) {
squares[r][c] = Player.Open;
}
}
this.Winner = getWinner();
this.OpenSquares = getOpenSquares();
//Size of the board
Size = Rows * Columns;
}
}
}
all of the classes are at the bottom. Thanks in advance for any help and corrections. :)
i made it recursive in the following code, although i still cant figure out the scoring.. if the value is either 1, 0, or -1 then if there are multipule moves with the same value it will just take the 1st one which may not be the best move "blocking.
private static Space GetBestMove(GameBoard gb, Player p) {
Space bestSpace = null;
List<Space> cloneOpenSpaces = getOpenSquares(gb);
GameBoard cloneBoard = null;
cloneBoard = gb.Clone();
for(Space Open: cloneOpenSpaces) {
cloneBoard = gb.Clone();
Space newSpace = Open;
cloneBoard.squares[newSpace.X][newSpace.Y] = p;
if(cloneBoard.Winner == Player.Open && cloneOpenSpaces.size() > 0) {
Player InP;
if(p == Player.X) {
InP = Player.O;
}else {
InP = Player.X;
}
***Space tempMove = GetBestMove(cloneBoard, InP);***
if(tempMove != null){
newSpace.Rank = tempMove.Rank;
}
the results of the test are as follows
test 1
ENTER bot:
O
ENTER board:
[ ][O][ ]
ENTER board:
[ ][ ][ ]
ENTER board:
[ ][X][X]
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
the best move is: 0 2
test 2
ENTER bot:
O
ENTER board:
[ ][X][X]
ENTER board:
[ ][ ][ ]
ENTER board:
[ ][O][ ]
1.0
1.0
1.0
1.0
1.0
-1.0
1.0
-1.0
-1.0
1.0
-1.0
1.0
1.0
-1.0
-1.0
the best move is: 1 1
I haven't ran your code, but I think I may know why you are having issues. The minimax algorithm is recursive in nature. You look at each open space, and determine some sort of score for each one. I see this in your code. However, what I don't see is the recursion that equates to the logic "if I move here, then what options will my opponent have during his next turn". Notice that you can keep calling the same scoring function, but scoring both players' options. This is where the computation can get intensive, and where stuff like pruning comes into play. Say I want to look 3 moves ahead. Say there are initially 5 open spaces. For each of the 5 open spaces, I examine my options and give a score to each one. Then I pretend to move there, and send the new board through the scoring function, and assume my opponent will take the highest scoring move of the remaining 4 possible moves. Then I pretend he moves there, and I again run the board through the scoring function, now with 2 hypothetical moves on it. You continue this for a set "depth", or number of potential moves, and pick the move that results in the highest value, assuming the opponent will do what you calculated they would.
I realize this was long-winded, but I hope there was a little bit of value buried in there somewhere. Take a look at your code, figure out where you are scoring moves (if you see a win, take it; if you can block a win, take it; etc.). Then continue calling this function where you keep adding fake/potential moves (those with the highest value from your scoring function), and once you reach the depth, you can simply pick the move that is likely to give you the most valuable outcome.
Basically, in your code, you should call GetBestMove(...) once from MakeMove(...). However, GetBestMove(...) should repeatedly call itself, with a modified board each time; and each time, it will return the best move given a hypothetical (or real) board. What I don't see in your code is that recursive call to GetBestMove(...), and the necessary upkeep that goes along with it. This explains why you only get aggressive behavior; it only looks to see what the best immediate move is, without any regard to what your opponent might be able to do if you make that move!
If my assumptions are wrong, provide a test case where you expect some behavior, but are getting something different.

Categories