I'm solving this BFS homework problem, I believe the logic I'm following is right, but I got stuck in an implementation error I can't pinpoint. I'm looking for help debugging this solution, not proposing a new one.
Problem Statement:
A kids has two robots that he controls remotely, both robots are on a NxN checkerboard and should be placed on the positions A and B in the checkerboard.
Both robots are affected by the remote controller simultaneously, the same command affects both of their states.
The remote controller can only make both robots turn clockwise or counterclockwise 90 degreees at a time or order both robots to move forward.
Example:
The leftmost image shows the initial setting. The arrow pointing right is a robot facing east and the arraw pointing up is a robot facing north. Positions A and B are the robots destinies.
Center image shows the result of moving both robots one step forward.
Right image shows the result of making the robots rotate counterclockwise.
The kid desires to calculate the minimum number of movements necessary to take the robots from their initial positions to their destinies.
If a robot is commanded to run over a wall, it will remain on the same spot.
Both robots will remain on their original spot if they're commanded to move to the same spot.
Figure 2 shows this special cases.
Both robots should at arrive at a different destiny simultaneously.
Input:
Input consists of various test cases, the first line starts with an integer with the size N of the inputMatrix (the checkerboard), with 2<= N <=25.
The following N lines describe the checkerboard and have N characters each.
A '.' indicates an empty position.
N, E, S or O (Spanish for Oeste=West) indicates the original positiona and orientation of the robot.
D indicates a destiny for the robot in the checkerboard and '*' indicates an obstacle.
Input finishes with a case where N=0.
input.txt
5
D....
N...S
.....
*...*
....D
5
.....
S..S.
.....
.....
D..D.
3
SN.
***
.DD
0
correct output for input.txt:
8
3
-1
input2.txt:
5
.....
..D.S
.D...
.....
..N..
6
......
..S...
......
.ED...
......
.D....
11
....E......
....D......
...........
..S...D....
...........
...........
...........
...........
...........
...........
...........
13
.............
.............
.............
.............
.....N.......
.............
.........D...
..D..........
.............
...E.........
.............
.............
.............
25
...*.......*.*...........
........*..D...*.**....*.
*..*.*.........*..*..*..D
...*.**.*........*...*...
......**..*..***.***...**
.............*...........
....*...***.....*.**.....
......**.......**.*.*...*
.........*..*...*.*......
....**.*.*....**.*.*.*.*.
.......*............**...
..........*.*.....*......
...........**....*.**....
.....E.*.*..........**.*.
.........*.*.*.*..*..*...
*........**...*..........
................***..*...
........*....*....*...*..
......*...*.*...*.....**.
...*..........*.**.......
.**............*.*..*.*..
........*........*...*...
*......*..........*......
*...*......N*......*..*.*
. .....*..*.*..*...*......
0
"correct" (?) output for input2.txt:
-1
-1
9
-1
46
My solution:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class Position {
int i;
int j;
char orientation;
Position() {
}
void setIJ(int i, int j){
this.i=i;
this.j=j;
}
void setOrientation(char c){
orientation = c;
}
public boolean equals(Object o){
if(o instanceof Position){
Position p = (Position)o;
if((p.i==this.i)&&(p.j==this.j)&&(p.orientation==this.orientation))
{
return true;
}
else return false;
}
return false;
}
} //end class Position
class TransitionState {
Position positionA;
Position positionB;
int counter;
public boolean equals (Object o){
if (o instanceof TransitionState){
TransitionState transitionState= (TransitionState)o;
if ((this.positionA.equals(transitionState.positionA))
&&(this.positionB.equals(transitionState.positionB)))
{
return true;
}
}
return false;
}
}
public class Robots {
static Position moveForward(Position oldPosition, int matrixSize, char orientation, char [][] inputMatrix){
// add possible new Position
Position newPosition= new Position();
//first return oldPosition in border positions in which the robot shouldn't move
if ((orientation=='O')&&(oldPosition.j==0))
return oldPosition;
if ((orientation=='E')&&(oldPosition.j==(matrixSize-1)))
return oldPosition;
if ((orientation=='N')&&(oldPosition.i==0))
return oldPosition;
if ((orientation=='S')&&(oldPosition.i==(matrixSize-1)))
return oldPosition;
if ((orientation=='O'))
newPosition.setIJ(oldPosition.i, oldPosition.j-1);
if ((orientation=='E'))
newPosition.setIJ(oldPosition.i, oldPosition.j+1);
if ((orientation=='S'))
newPosition.setIJ(oldPosition.i-1, oldPosition.j);
if ((orientation=='N'))
newPosition.setIJ(oldPosition.i+1, oldPosition.j);
//return oldPosition for positions in which the robot is blocked by *
if (inputMatrix[newPosition.i][newPosition.j]=='*'){
return oldPosition;
}
return newPosition; // if it got here, all ok
}
static char turnCounter (char orientation){
if(orientation=='N')
return 'O';
if(orientation=='O')
return 'S';
if (orientation=='S')
return 'E';
else
return 'N';
}
static char turnClock(char orientation){
if(orientation=='N')
return 'E';
if(orientation=='E')
return 'S';
if (orientation=='S')
return 'O';
else
return 'N';
}
static Position[] robotInitialPositions(char [][]inputMatrix){
Position [] helperArray = new Position[2];
int aux=0;
for (int i=0; i<(inputMatrix[0].length); i++)
for (int j=0; j<(inputMatrix[0].length); j++)
{
if((inputMatrix[i][j]=='N')||(inputMatrix[i][j]=='S')||(inputMatrix[i][j]=='O')||(inputMatrix[i][j]=='E'))
{
helperArray[aux]= new Position();
helperArray[aux].setIJ(i, j);
if (inputMatrix[i][j]=='N'){helperArray[aux].orientation='N'; }
if (inputMatrix[i][j]=='S'){helperArray[aux].orientation='S'; }
if (inputMatrix[i][j]=='E'){helperArray[aux].orientation='E'; }
if (inputMatrix[i][j]=='O'){helperArray[aux].orientation='O'; }
aux= aux+1;
}
}
return helperArray;
}
static Position[] getDestinies(char [][]inputMatrix){
Position [] helperArray = new Position[2];
int aux=0;
for (int i=0; i<(inputMatrix[0].length); i++)
for (int j=0; j<(inputMatrix[0].length); j++)
{
if((inputMatrix[i][j]=='D'))
{
helperArray[aux]= new Position();
helperArray[aux].i=i; helperArray[aux].j=j;
helperArray[aux].orientation='D';
aux=aux+1;
}
}
return helperArray;
}
static boolean [][]getUnvisitedMatrix(int matrixLength){
boolean[][] unvisitedMatrix = new boolean [matrixLength][matrixLength];
for (int i=0; i<matrixLength;i++)
for (int j=0; j<matrixLength; j++)
unvisitedMatrix[i][j]=false;
return unvisitedMatrix;
}
static Position[]getNewRobotPositions (Position oldR1Pos,Position oldR2Pos, String movement, char [][]inputMatrix){
Position[]newPositions = new Position[2];
Position newR1Pos = new Position();
Position newR2Pos = new Position();
if(movement.equals("counter")){
if (oldR1Pos.orientation=='N'){
newR1Pos.orientation='O';
}
if (oldR1Pos.orientation=='S'){
newR1Pos.orientation='E';
}
if (oldR1Pos.orientation=='E'){
newR1Pos.orientation='N';
}
if (oldR1Pos.orientation=='O'){
newR1Pos.orientation='S';
}
if (oldR2Pos.orientation=='N'){
newR2Pos.orientation='O';
}
if (oldR2Pos.orientation=='S'){
newR2Pos.orientation='E';
}
if (oldR2Pos.orientation=='E'){
newR2Pos.orientation='N';
}
if (oldR2Pos.orientation=='O'){
newR2Pos.orientation='S';
}
newR1Pos.i=oldR1Pos.i;
newR1Pos.j=oldR1Pos.j;
newR2Pos.i=oldR2Pos.i;
newR2Pos.j=oldR2Pos.j;
newPositions[0]=newR1Pos;
newPositions[1]=newR2Pos;
// System.out.println("MOVED COUNTERCLOCKWISE");
// System.out.println("previous Robot 1 position was "+oldR1Pos.i + ","+oldR1Pos.j + " orientation was " + oldR1Pos.orientation +
// " new Robot 1 position is " + newR1Pos.i + "," + newR1Pos.j+ " orientation is "+newR1Pos.orientation);
//
// System.out.println("previous Robot 2 position was "+oldR2Pos.i + ","+oldR2Pos.j + " orientation was " + oldR2Pos.orientation +
// " new Robot 2 position is " + newR2Pos.i + "," + newR2Pos.j+ " orientation is "+newR2Pos.orientation);
return newPositions;
}
if(movement.equals("clock")){
newR1Pos.i = oldR1Pos.i;
newR1Pos.j = oldR1Pos.j;
newR2Pos.i = oldR2Pos.i;
newR2Pos.j = oldR2Pos.j;
if (oldR1Pos.orientation=='N'){
newR1Pos.orientation= 'E';
}
if (oldR1Pos.orientation=='S'){
newR1Pos.orientation= 'O';
}
if (oldR1Pos.orientation=='E'){
newR1Pos.orientation= 'S';
}
if (oldR1Pos.orientation=='O'){
newR1Pos.orientation= 'N';
}
if (oldR2Pos.orientation=='N'){
newR2Pos.orientation= 'E';
}
if (oldR2Pos.orientation=='S'){
newR2Pos.orientation= 'O';
}
if (oldR2Pos.orientation=='E'){
newR2Pos.orientation= 'O';
}
if (oldR2Pos.orientation=='O'){
newR2Pos.orientation= 'N';
}
// System.out.println("MOVED CLOCKWISE");
// System.out.println("previous Robot 1 position was "+oldR1Pos.i + ","+oldR1Pos.j + " orientation was " + oldR1Pos.orientation +
// " new Robot 1 position is " + newR1Pos.i + "," + newR1Pos.j+ " orientation is "+newR1Pos.orientation);
/ /
// System.out.println("previous Robot 2 position was "+oldR2Pos.i + ","+oldR2Pos.j + " orientation was " + oldR2Pos.orientation +
// " new Robot 2 position is " + newR2Pos.i + "," + newR2Pos.j+ " orientation is "+newR2Pos.orientation);
newPositions[0]=newR1Pos;
newPositions[1]=newR2Pos;
return newPositions;
}
if(movement.equals("forward")){
//default case, if conditions not satisfied
newR1Pos.i=oldR1Pos.i;
newR1Pos.j=oldR1Pos.j;
newR1Pos.orientation = oldR1Pos.orientation;
newR2Pos.i=oldR2Pos.i;
newR2Pos.j=oldR2Pos.j;
newR2Pos.orientation = oldR2Pos.orientation;
if(oldR1Pos.orientation=='N'){
if(oldR1Pos.i-1>=0){ //doesn't exceed the upper border
//doesn't collide with '*'
if (inputMatrix[oldR1Pos.i-1][oldR1Pos.j]!='*'){
newR1Pos.i=oldR1Pos.i-1;
newR1Pos.j=oldR1Pos.j;
newR1Pos.orientation = oldR1Pos.orientation;
}
}
}
if(oldR1Pos.orientation=='S'){
if(oldR1Pos.i+1<inputMatrix.length){ //doesn't exceed the lower border
//doesn't collide with '*'
if (inputMatrix[oldR1Pos.i+1][oldR1Pos.j]!='*'){
newR1Pos.i=oldR1Pos.i+1;
newR1Pos.j=oldR1Pos.j;
newR1Pos.orientation = oldR1Pos.orientation;
}
}
}
if(oldR1Pos.orientation=='E'){
if(oldR1Pos.j+1<inputMatrix.length){ //doesn't exceed the right border
//doesn't collide with '*'
if (inputMatrix[oldR1Pos.i][oldR1Pos.j+1]!='*'){
newR1Pos.i=oldR1Pos.i;
newR1Pos.j=oldR1Pos.j+1;
newR1Pos.orientation = oldR1Pos.orientation;
}
}
}
if(oldR1Pos.orientation=='O'){
if(oldR1Pos.j-1>=0){ //doesn't exceed the left border
//doesn't collide with '*'
if (inputMatrix[oldR1Pos.i][oldR1Pos.j-1]!='*'){
newR1Pos.i=oldR1Pos.i;
newR1Pos.j=oldR1Pos.j-1;
newR1Pos.orientation = oldR1Pos.orientation;
}
}
}
//same for robot 2
if(oldR2Pos.orientation=='N'){
if(oldR2Pos.i-1>=0){ //doesn't exceed the upper border
//doesn't collide with '*'
if (inputMatrix[oldR2Pos.i-1][oldR2Pos.j]!='*'){
newR2Pos.i=oldR2Pos.i-1;
newR2Pos.j=oldR2Pos.j;
newR2Pos.orientation=oldR2Pos.orientation;
}
}
}
if(oldR2Pos.orientation=='S'){
if(oldR2Pos.i+1<inputMatrix.length){ //doesn't exceed the lower border
//doesn't collide with '*'
if (inputMatrix[oldR2Pos.i+1][oldR2Pos.j]!='*'){
newR2Pos.i=oldR2Pos.i+1;
newR2Pos.j=oldR2Pos.j;
newR2Pos.orientation=oldR2Pos.orientation;
}
}
}
if(oldR2Pos.orientation=='E'){
if(oldR2Pos.j+1<inputMatrix.length){ //doesn't exceed the right border
//doesn't collide with '*'
if (inputMatrix[oldR2Pos.i][oldR2Pos.j+1]!='*'){
newR2Pos.i=oldR2Pos.i;
newR2Pos.j=oldR2Pos.j+1;
newR2Pos.orientation=oldR2Pos.orientation;
}
}
}
if(oldR2Pos.orientation=='O'){
if(oldR2Pos.j-1>=0){ //doesn't exceed the left border
//doesn't collide with '*'
if (inputMatrix[oldR2Pos.i][oldR2Pos.j-1]!='*'){
newR2Pos.i=oldR2Pos.i;
newR2Pos.j=oldR2Pos.j-1;
newR2Pos.orientation=oldR2Pos.orientation;
}
}
}
//if robots collide in new positions, revert to their original positions
if ((newR1Pos.i==newR2Pos.i) && (newR1Pos.j==newR2Pos.j)){
//revert robot 1 position
newR1Pos.i=oldR1Pos.i;
newR1Pos.j=oldR1Pos.j;
newR1Pos.orientation = oldR1Pos.orientation;
//revert robot 2 position
newR2Pos.i=oldR2Pos.i;
newR2Pos.j=oldR2Pos.j;
newR2Pos.orientation = oldR2Pos.orientation;
}
newPositions[0] = newR1Pos;
newPositions[1] = newR2Pos;
// System.out.println("MOVED FORWARD");
// System.out.println("previous Robot 1 position was "+oldR1Pos.i + ","+oldR1Pos.j + " orientation was " + oldR1Pos.orientation +
// " new Robot 1 position is " + newR1Pos.i + "," + newR1Pos.j+ " orientation is "+newR1Pos.orientation);
//
// System.out.println("previous Robot 2 position was "+oldR2Pos.i + ","+oldR2Pos.j + " orientation was " + oldR2Pos.orientation +
// " new Robot 2 position is " + newR2Pos.i + "," + newR2Pos.j+ " orientation is "+newR2Pos.orientation);
} //end movement.equals("forward")
return newPositions;
}
//1 procedure BFS(Graph,source):
//2 create a queue Q
//3 enqueue source onto Q
//4 mark source
//5 while Q is not empty:
//6 dequeue an item from Q into v
//7 for each edge e incident on v in Graph:
//8 let w be the other end of e
//9 if w is not marked:
//10 mark w
//11 enqueue w onto Q
static void BFS (char [][] inputMatrix){
ArrayList<TransitionState> transitionStatesArray = new ArrayList<TransitionState>();
int moveCounter=0; //turns and forward movements add here
int tempMoveCounterRobot1=0; int tempMoveCounterRobot2=0;
int maxMoveCounter=0;
PositionsAndCounter positionsAndCounter= new PositionsAndCounter();
Queue <PositionsAndCounter>queue = new LinkedList<PositionsAndCounter>();
Position robotInitial[] = robotInitialPositions(inputMatrix); //get source
positionsAndCounter.positionPair=robotInitial; //used to encapsulate the positions with a counter to output
positionsAndCounter.counter=0;//first initialize to 0
Position destinies[] = getDestinies(inputMatrix); //get destinies
TransitionState firstTransitionState = new TransitionState();
firstTransitionState.positionA=robotInitial[0];
firstTransitionState.positionB=robotInitial[1];
transitionStatesArray.add(firstTransitionState);
//mark transition used , if the transition is new, it should be queued
queue.add(positionsAndCounter);
String [] movement = {"forward", "counter", "clock"};
//possible movements inside inputMatrix
outer: while (!queue.isEmpty()){ //while queue is not empty
PositionsAndCounter v= queue.poll(); //dequeue an item from Q into V
for(int k = 0; k<3; k++){ //for each edge e incident on v in Graph:
Position[] newRobotPositions = getNewRobotPositions(v.positionPair[0], v.positionPair[1], movement[k], inputMatrix);
TransitionState newTransitionState = new TransitionState();
newTransitionState.positionA=newRobotPositions[0];
newTransitionState.positionB=newRobotPositions[1];
if(!transitionStatesArray.contains(newTransitionState)){ //if the transition state is new add and enqueue new robot positions
transitionStatesArray.add(newTransitionState);
//if transition is new then queue
PositionsAndCounter newPositionsAndCounter = new PositionsAndCounter();
newPositionsAndCounter.positionPair=newRobotPositions;
newPositionsAndCounter.counter = v.counter +1;
queue.add(newPositionsAndCounter);
}
inputMatrix[v.positionPair[0].i][v.positionPair[1].j]='.';
inputMatrix[v.positionPair[1].i][v.positionPair[1].j]='.';
//inputMatrix[v[0].i][v[0].j]='.'; // mark old position of robot 1 with .
//inputMatrix[v[1].i][v[1].j]='.'; // mark old position of robot 2 with .
//update new robot positions
inputMatrix[newRobotPositions[0].i][newRobotPositions[0].j]= newRobotPositions[0].orientation;
inputMatrix[newRobotPositions[1].i][newRobotPositions[1].j]= newRobotPositions[1].orientation;
//check if solution has been found
if
(
((destinies[0].i==newRobotPositions[0].i)&&(destinies[0].j==newRobotPositions[0].j) //robot in 0 arrived to destiny
|| (destinies[1].i==newRobotPositions[0].i)&&(destinies[1].j==newRobotPositions[0].j))// in 0 or 1
&& //and
((destinies[0].i==newRobotPositions[1].i)&&(destinies[0].j==newRobotPositions[1].j) //robot in 1 arrived to destiny
|| (destinies[1].i==newRobotPositions[0].i)&&(destinies[1].j==newRobotPositions[0].j))//in 0 or 1
) //end if
{
System.out.println("robots arrived at destinies");
System.out.println("robot 1, starting at " + robotInitial[0].i + "," + robotInitial[0].j
+ " is in " + newRobotPositions[0].i + ","+ newRobotPositions[0].j);
System.out.println("robot 2, starting at " + robotInitial[1].i + "," + robotInitial[1].j
+ " is in " + newRobotPositions[1].i + ","+ newRobotPositions[1].j);
System.out.println("movements: " + (v.counter));
return;
//break outer;
}
}
}
System.out.println("robots can never arrive at their destinies");
System.out.println(-1);
}
static void printInputMatrix(char [][] inputMatrix){
for (int i=0; i<inputMatrix[0].length;i++)
for(int j=0; j<inputMatrix[0].length;j++)
{
System.out.print(" "+inputMatrix[i][j]+" ");
if(j==inputMatrix[0].length-1){System.out.println("");}
}
}
public static void main(String[] args) throws IOException {
// System.out.println("Test transition checker");
// Position p1 = new Position();
// p1.i=1;
// p1.j=1;
// p1.orientation='N';
// Position p2 = new Position();
// p2.i=1;
// p2.j=2;
// p2.orientation='N';
// Position p3 = new Position();
// p3.i=1;
// p3.j=1;
// p3.orientation='N';
// Position p4 = new Position();
// p4.i=1;
// p4.j=1;
// p4.orientation='N';
//
// TransitionState transitionChecker1 = new TransitionState();
// transitionChecker1.positionA=p1;
// transitionChecker1.positionB=p2;
//
// TransitionState transitionChecker2 = new TransitionState();
// transitionChecker2.positionA=p1;
// transitionChecker2.positionB=p2;
//
//
// ArrayList<TransitionState> arrayTransitions = new ArrayList<TransitionState>();
// arrayTransitions.add(transitionChecker1);
// System.out.println("Test contains? " + arrayTransitions.contains(transitionChecker2));
BufferedReader br = new BufferedReader(new FileReader(new File("input.txt")));
char [][] inputMatrix;
String line;
char [] lineAsCharArray;
int matrixSize;
while(true){
line = br.readLine();
matrixSize=Integer.parseInt(line);
inputMatrix = new char [matrixSize][matrixSize];
if (matrixSize==0){ // end outer looping
break;
}
else { //begin inner looping
for (int i=0; i<matrixSize; i++){
line = br.readLine();
inputMatrix[i] =line.toCharArray();
}
//matrix loaded
BFS(inputMatrix);
}
}
}
}
class PositionsAndCounter {
Position[] positionPair;
int counter;
PositionsAndCounter() {
positionPair = new Position[2];
counter=0;
}
}
Problems:
1) On the first input.txt file, it finds 9 movements to find the solution of the first course (when they should be 8) and 6 to find the solution of the second course (when it should be 3) though it correctly prints out -1 for the last (impossible) course configuration.
2) On the second input.txt file, professor says it should print -1 and -1 for the to first courses, though my program finds a plaussible solution for the second case and a bizarre one for the first (this is where I think a more experienced debugger could help, I'm at a loss tracking the reason for the displaced destiny output on the first case). Are the outputs proposed by my professor right? My algorithm is also getting stuck on that case where 46 should be printed.
The are 2 careless copy and paste problems causes the code not working,
1, in the clockwise turning part:
if (oldR2Pos.orientation == 'E') {
newR2Pos.orientation = 'O';
}
This is wrong... it should be a direct copy and paste from the above block
if (oldR2Pos.orientation == 'E') {
newR2Pos.orientation = 'S';
}
Yet you missed it.
Another problem is actually in the end condition testing block
//check if solution has been found
if
(
((destinies[0].i==newRobotPositions[0].i)&&(destinies[0].j==newRobotPositions[0].j) //robot in 0 arrived to destiny
|| (destinies[1].i==newRobotPositions[0].i)&&(destinies[1].j==newRobotPositions[0].j))// in 0 or 1
&& //and
((destinies[0].i==newRobotPositions[1].i)&&(destinies[0].j==newRobotPositions[1].j) //robot in 1 arrived to destiny
|| **(destinies[1].i==newRobotPositions[0].i)&&(destinies[1].j==newRobotPositions[0].j)**)//in 0 or 1
) //end if
The last part (code highlighted) should be
(destinies[1].i==newRobotPositions[1].i)&&(destinies[1].j==newRobotPositions[1].j)
It is obviously an copy and paste but forget to change error. The logic is a little bit hard to understand, but works,
(A in X or B in Y) and (A in Y or B in X)
Although it is the same (logically not exactly the same but it some how works for your case as A and B cannot occupy the same location), it is much clearer if you use
(A in X and B in Y) or (A in Y and B in X)
Apart from the fatal errors stated above, your program has a few other issues need to addressed.It looks like you are a university student taking Computer science, please, read the given source code before coding: TransistionState class is not used at all but you created your own PositionsAndCounter, turning logic is implemented twice, if you didn't rewrite the turning code, and use the one given, you won't commit problem 1.... If I were your professor, i may fail you on that. Plan your solution well before hitting the keyboard, and make sure your code is clear and readable as plan english, if you stare at your source code for 5 min and cannot figure out what the block of code is for, may be you didn't structure it correctly.
The listing below is an example solution for your question:
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class DualRobot {
public enum Orientation{
E(1, 0), S(0, 1), O(-1, 0), N(0, -1);
public final int dx, dy;
private Orientation(int dx, int dy){
this.dx = dx;
this.dy = dy;
}
public Orientation left(){
return Orientation.values()[(this.ordinal() + 3) % 4];
}
public Orientation right(){
return Orientation.values()[(this.ordinal() + 1) % 4];
}
public static Orientation valueOf(char c){
for(Orientation o : Orientation.values()){
if(o.toString().equalsIgnoreCase("" + c)) return o;
}
return null;
}
}
public enum Action {FORWARD, COUNTER_CLOCKWISE, CLOCKWISE}; // F: forward, L: Counter clockwise, R: clockwise
private static class Robot{
Point position;
Orientation orientation;
public Robot(Robot r){
this.position = new Point(r.position);
this.orientation = r.orientation;
}
public Robot(int x, int y, Orientation orientation){
this.position = new Point(x, y);
this.orientation = orientation;
}
public void move(Action action, char[][] map){
switch (action) {
case FORWARD:
Point nextPosition = new Point(position);
nextPosition.translate(orientation.dx, orientation.dy);
if(isValidPosition(nextPosition, map)) position = nextPosition;
break;
case COUNTER_CLOCKWISE:
this.orientation = this.orientation.left();
break;
case CLOCKWISE:
this.orientation = this.orientation.right();
break;
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Robot) {
Robot r = (Robot) obj;
return r.position.equals(this.position) && r.orientation == this.orientation;
}
return super.equals(obj);
}
#Override
public int hashCode() {
return orientation.ordinal() + position.x * 10 + position.y * 1000;
}
private boolean isValidPosition(Point p, char[][] map){
return p.x >= 0 && p.x < map[0].length
&& p.y >= 0 && p.y < map.length
&& map[p.y][p.x] != '*';
}
}
private static class State{
private Robot a, b;
private int counter;
public State(Robot a, Robot b, int counter) {
this.a = new Robot(a);
this.b = new Robot(b);
this.counter = counter;
}
public List<State> nextStates(char[][] map){
List<State> states = new ArrayList<State>();
for(Action action : Action.values()){
State s = new State(this.a, this.b, this.counter + 1);
s.a.move(action, map);
s.b.move(action, map);
if(!s.a.position.equals(s.b.position)){ // Test for collision
states.add(s);
}
}
return states;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof State) {
State state = (State) obj; // Consider the state to be the same if the 2 robots are at identical location and orientation
return (this.a.equals(state.a) && this.b.equals(state.b))
|| (this.a.equals(state.b) && this.b.equals(state.a));
}
return super.equals(obj);
}
#Override
public int hashCode() {
// The quality of this hashCode can affect the program's speed
// Multiply is transitive, so if you swap a and b, the hashcode is the same
return a.hashCode() * b.hashCode();
}
}
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new FileReader("input.txt"));
int size;
while((size = Integer.parseInt(input.readLine())) > 0){
// Load the data;
char[][] map = new char[size][size];
for (int i = 0; i < size; i++) {
map[i] = input.readLine().toCharArray();
}
// Construct initial state
List<Robot> robots = new ArrayList<Robot>();
List<Point> destinations = new ArrayList<Point>();
for(int i = 0; i < size; i ++){
for(int j = 0; j < size; j ++){
Orientation orientation = Orientation.valueOf(map[i][j]);
if(orientation != null){
robots.add(new Robot(j, i, orientation));
}else if(map[i][j] == 'D'){
destinations.add(new Point(j, i));
}
}
}
System.out.println(BFSSearch(map, new State(robots.get(0), robots.get(1), 0), destinations));
}
}
private static int BFSSearch(char[][] map, State initialState, List<Point> destinations) throws IOException{
List<State> queue = new LinkedList<State>(); // Array list is slightly more efficient
queue.add(initialState); // Initial state
Map<State, Boolean> testedStates = new HashMap<State, Boolean>();
while(queue.size() > 0){
State currentState = queue.remove(0);
if(testedStates.containsKey(currentState)) continue;
// Testing for end condition
if((currentState.a.position.equals(destinations.get(0)) && currentState.b.position.equals(destinations.get(1)))
|| (currentState.a.position.equals(destinations.get(1)) && currentState.b.position.equals(destinations.get(0)))){
return currentState.counter;
}
testedStates.put(currentState, true);
queue.addAll(currentState.nextStates(map));
}
return -1;
}
}
This program spit out the final answer in around 10 seconds.
The main difference is I used an hash table to store the tested states to improve the speed, thus the quality of the hash function would have an effect on the speed.
Recommended reading: hash table, DRY principle.
Related
what the method needs to do: to put it simply, we receive any number of points(from class Point) like (1,4)...(7,2) and there can be anywhere from 3 to 10 (if less then 3 it returns null) and the methods needs to return the rectangle(which needs to be from class Polygon) that blocks the Polygon created from the given points, (in other words we get points that create a polygon and we need to find the rectangle that blocks the polygon),
the problem: I believe the code i created should work? but my main problem is I don't know how to write the return command to return those values that are from class Point and print them in this method which is supposed to be class Polygon, I have a toString command that prints out everything i just don't know how can i take those point values from SW,SE,NE,NW and insert return them with toString inside the getBoundingBox() method
Thanks if you can help i will add the code below, the method i am having trouble with in the return command is public Polygon getBoundingBox()
//tester
Polygon boundingBox = polygon.getBoundingBox();
String boundingBoxStr = boundingBox.toString();
if (boundingBoxStr.equals("The polygon has 4 vertices:\n((1,0),(7,0),(7,6),(1,6))"))
System.out.println("\ngetBoundingBox - OK");
else
{
System.out.println("\nError in getBoundingBox or in toString");
System.out.println("Your bounding box is:\n" + boundingBox + "\nExpected bounding box is:\nThe polygon has 4 vertices:\n((1,0),(7,0),(7,6),(1,6))");
}
// instance variables -
private Point [] _vertices;
private int _noOfVertices;
private final int MAX_VERTICES = 10;
// constructor
public Polygon()
{
_vertices = new Point[MAX_VERTICES];
_noOfVertices = 0;
}
// add vertex(or point)
public boolean addVertex(int x, int y)
{
if (_noOfVertices == MAX_VERTICES)
return false;
_vertices[_noOfVertices++] = new Point(x,y);
return true;
}
//toString
public String toString()
{
String str = "";
if(_noOfVertices == 0)
{
str = "The polygon has 0 vertices.";
}
int i;
if(_noOfVertices > 0)
{
str += "The polygon has " + _noOfVertices + " vertices:" + "\n";
str += "" + ("(");
for(i=0; i < _noOfVertices; i++)
if (i == _noOfVertices-1)
{
str += "" + _vertices[i];
}
else
{
str += "" + _vertices[i] + ",";
}
if(i ==_noOfVertices)
{
str += "" + (")");
}
}
return str;
}
public Polygon getBoundingBox()
{
Polygon rectangle = new Polygon();
String str = "";
if(_noOfVertices < 3)
return null;
Point SW = _vertices[0];
Point SE = _vertices[0];
Point NE = _vertices[0];
Point NW = _vertices[0];
for (int i=1; i<_noOfVertices; i++)
{
if(_vertices[i].isLeft(SW) && _vertices[i].isUnder(SW))
{
SW = _vertices[i];
}
if(_vertices[i].isRight(SE) && _vertices[i].isUnder(SE))
{
SE = _vertices[i];
}
if(_vertices[i].isRight(NE) && _vertices[i].isAbove(NE))
{
NE = _vertices[i];
}
if(_vertices[i].isLeft(NW) && _vertices[i].isAbove(NW))
{
NW = _vertices[i];
}
}
return new Polygon(SW,SE,NE,NW); // if i try to add the points SW,SE,NE,NW to Polygon i get an error "constructor polygon in class polygon can't be
// to given types
// I am suppsoed to print it out like this using toString command:
// The polygon has 5 vertices:
// ((SW,SE,NE,NW))
}
I've just started learning java since last week. I'm using book called 'head first java' and i'm struggling with solving problems about ArrayList. Error says "The method setLocationCells(ArrayList) in the type DotCom is not applicable for the
arguments (int[])" and I haven't found the solution :( help me..!
enter image description here
This looks like a Locate & Conquer type game similar to the game named Battleship with the exception that this game is a single player game played with a single hidden ship in a single horizontal row of columnar characters. Rather simplistic but kind of fun to play I suppose. The hard part is to locate the hidden ship but once you've located it, conquering (sinking) it becomes relatively easy. I'm sure this isn't the games' intent since it is after all named "The Dot Com Game" but the analogy could be possibly helpful.
There are several issues with your code but there are two major ones that just can not be there for the game to work:
Issue #1: The call to the DotCom.setLocationCells() method:
The initial problem is located within the DotComGame class on code line 13 (as the Exception indicates) where the call is made to the DotCom.setLocationCells() method. As already mentioned in comments the wrong parameter type is passed to this method. You can not pass an int[] Array to the setLocationCell() method when this method contains a parameter signature that stipulates it requires an ArrayList object. The best solution in my opinion would be to satisfy the setLocationCells() method parameter requirement...supply an ArrayList to this method.
The reason I say this is because all methods within the DotCom class work with an established ArrayList and one of the tasks of one of these methods (the checkYourself() method) actually removes elements from the ArrayList which is easy to do from a collection but very cumbersome to do the same from an Array.
To fix this problem you will need to change the data type for the locations variable located within the DotComGame class. Instead of using:
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
you should have:
ArrayList<Integer> locations = new ArrayList<>(
Arrays.asList(random, randomNum + 1, randomNum + 2));
or you could do it this way:
ArrayList<Integer> locations = new ArrayList<>();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
There are other ways but these will do for now. Now, when the call to the setLocationCells() method is made you ahouldn't get an exception this issue should now be resolved.
Issue #2: The call to the DotCom.checkYourself() method:
Again, this particular issue is located within the DotComGame class on code line 18 where the call is made to the DotCom.checkYourself() method. Yet another parameter data type mismatch. You are trying to pass a variable of type String (named guess) to this method whereas its signature stipulates that it requires an integer (int) value. That again is a no go.
To fix this problem you will need to convert the string numerical value held by the guess variable to an Integer (int) value. So instead of having this:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
String result = theDotCom.checkYourself(guess);
// ... The rest of your while loop code ...
}
you should have something like:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
/* Validate. Ensure guess holds a string representation
of a Integer numerical value. */
if (!guess.matches("\\d+")) {
System.err.println("Invalid Value (" + guess
+ ") Supplied! Try again...");
continue;
}
int guessNum = Integer.parseInt(guess);
String result = theDotCom.checkYourself(guessNum);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println(numOfGuesses + " guesses!");
}
else if (result.equals("hit")) {
// Do Something If You Like
System.out.println("HIT!");
}
else {
System.out.println("Missed!");
}
}
Below is a game named Simple Battleship which I based off of your code images (please don't use images for code anymore - I hate using online OCR's ;)
BattleshipGame.java - The application start class:
import java.awt.Toolkit;
public class BattleshipGame {
public static int gameLineLength = 10;
public static void main(String[] args) {
GameHelper helper = new GameHelper();
Battleship theDotCom = new Battleship();
int score = 0; // For keeping an overall score
// Display About the game...
System.out.println("Simple Battleship Game");
System.out.println("======================");
System.out.println("In this game you will be displayed a line of dashes.");
System.out.println("Each dash has the potential to hide a section of a");
System.out.println("hidden Battleship. The size of this ship is randomly");
System.out.println("chosen by the game engine and can be from 1 to 5 sections");
System.out.println("(characters) in length. The score for each battle is based");
System.out.println("on the length of the game line that will be displayed to");
System.out.println("you (default is a minimum of 10 charaters). You now have");
System.out.println("the option to supply the game line length you want to play");
System.out.println("with. If you want to use the default then just hit ENTER:");
System.out.println();
// Get the desire game line length
String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
if (!length.isEmpty()) {
gameLineLength = Integer.parseInt(length);
}
System.out.println();
// Loop to allow for continuous play...
boolean alwaysReplay = true;
while (alwaysReplay) {
int numOfGuesses = 0;
/* Create a random ship size to hide within the line.
It could be a size from 1 to 5 characters in length. */
int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
int[] locations = new int[shipSize];
for (int i = 0; i < locations.length; i++) {
locations[i] = randomNum + i;
}
System.out.println("Destroy the " + shipSize + " character ship hidden in the");
System.out.println("displayed line below:");
System.out.println();
String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
theDotCom.setLocationCells(locations);
// Play current round...
boolean isAlive = true;
while (isAlive == true) {
System.out.println(gameLine);
String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
+ " (0 to quit): --> ", "Integer", 1, gameLineLength);
int idx = Integer.parseInt(guess);
if (idx == 0) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
alwaysReplay = false;
break;
}
idx = idx - 1;
String result = theDotCom.checkYourself(idx);
numOfGuesses++;
System.out.println(result);
if (result.equalsIgnoreCase("kill")) {
Toolkit.getDefaultToolkit().beep();
isAlive = false;
/* Tally the score dependent upon the gameLineLength... */
if (gameLineLength <= 10) { score += 5; }
else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
else { score += 25; }
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
System.out.println(gameLine);
System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
}
else if (result.equalsIgnoreCase("hit")) {
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
}
if (result.equalsIgnoreCase("miss")) {
score -= 1;
}
System.out.println();
}
// Play Again? [but only if 'alwaysReplay' holds true]
if (alwaysReplay) {
String res = helper.getAnything("<< Press ENTER to play again >>\n"
+ "<< or enter 'q' to quit >>");
if (res.equalsIgnoreCase("q")) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
break;
}
System.out.println();
}
}
}
}
GameHelper.java - The GameHelper class:
import java.util.Scanner;
public class GameHelper {
private final Scanner in = new Scanner(System.in);
public String getUserInput(String prompt, String responseType, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (response.isEmpty() && allowNothing) {
return "";
}
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getAnything(String prompt) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
return in.nextLine().trim();
}
}
Battleship.java - The Battleship class:
import java.util.ArrayList;
public class Battleship {
private ArrayList<Integer> locationCells;
public void setLocationCells(java.util.ArrayList<Integer> loc) {
locationCells = loc;
}
// Overload Method (Java8+)
public void setLocationCells(int[] loc) {
locationCells = java.util.stream.IntStream.of(loc)
.boxed()
.collect(java.util.stream.Collectors
.toCollection(java.util.ArrayList::new));
}
/*
// Overload Method (Before Java8)
public void setLocationCells(int[] loc) {
// Clear the ArrayList in case it was previously loaded.
locationCells.clear();
// Fill the ArrayList with integer elements from the loc int[] Array
for (int i = 0; i < loc.length; i++) {
locationCells.add(loc[i]);
}
}
*/
/**
* Completely removes one supplied Integer value from all elements
* within the supplied Integer Array if it exist.<br><br>
*
* <b>Example Usage:</b><pre>
*
* {#code int[] a = {103, 104, 100, 10023, 10, 140, 2065};
* a = removeFromArray(a, 104);
* System.out.println(Arrays.toString(a);
*
* // Output will be: [103, 100, 10023, 10, 140, 2065]}</pre>
*
* #param srcArray (Integer Array) The Integer Array to remove elemental
* Integers from.<br>
*
* #param intToDelete (int) The Integer to remove from elements within the
* supplied Integer Array.<br>
*
* #return A Integer Array with the desired elemental Integers removed.
*/
public static int[] removeFromArray(int[] srcArray, int intToDelete) {
int[] arr = {};
int cnt = 0;
boolean deleteIt = false;
for (int i = 0; i < srcArray.length; i++) {
if (srcArray[i] != intToDelete) {
arr[cnt] = srcArray[i];
cnt++;
}
}
return arr;
}
public String checkYourself(int userInput) {
String result = "MISS";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "KILL";
}
else {
result = "HIT";
}
}
return result;
}
}
I am following a tutorial which partially deals with printing the elements of ArrayLists. The program runs exactly as I'd expect when dealing with small lists. However the string formatting ( I believe ) causes some strange results when larger numbers are input.
My code is as follows:
public class Theatre {
private final String theatreName;
public List<Seat> seats = new ArrayList<>();
public Theatre(String theatreName, int numRows, int seatsPerRow) {
this.theatreName = theatreName;
int lastRow = 'A' + (numRows -1);
for (char row = 'A'; row <= lastRow; row++) {
for(int seatNum = 1; seatNum <= seatsPerRow; seatNum++) {
Seat seat = new Seat(row + String.format("%02d", seatNum));
seats.add(seat);
}
}
}
public String getTheatreName() {
return theatreName;
}
public boolean reserveSeat(String seatNumber) {
int low = 0;
int high = seats.size()-1;
while(low <= high) {
System.out.print(".");
int mid = (low + high) /2;
Seat midVal = seats.get(mid);
int cmp = midVal.getSeatNumber().compareTo(seatNumber);
if(cmp <0) {
low = mid + 1;
} else if(cmp > 0) {
high = mid -1;
} else {
return seats.get(mid).reserve();
}
}
System.out.println("There is no seat " + seatNumber);
return false;
}
// for testing
public void getSeats() {
for(Seat seat : seats) {
System.out.println(seat.getSeatNumber());
}
}
public class Seat implements Comparable<Seat > {
private final String seatNumber;
private boolean reserved = false;
public Seat(String seatNumber) {
this.seatNumber = seatNumber;
}
public boolean reserve() {
if(!this.reserved) {
this.reserved = true;
System.out.println("Seat " + seatNumber + " reserved");
return true;
} else {
return false;
}
}
public boolean cancel() {
if(this.reserved) {
this.reserved = false;
System.out.println("Reservation of seat " + seatNumber + " cancelled");
return true;
} else {
return false;
}
}
public String getSeatNumber() {
return seatNumber;
}
#Override
public int compareTo(Seat seat) {
// returns integer greater than 0 if greater than, less than if less than, 0 if equal
return this.seatNumber.compareTo(seat.getSeatNumber());
}
}
With a Main method class:
public static void main(String[] args) {
Theatre theatre = new Theatre("Olympian", 800, 12);
List<Theatre.Seat> seatCopy = new ArrayList<>(theatre.seats); // shallow copy, contains references to all
// elements of both lists, original and copy
printList(seatCopy);
seatCopy.get(1).reserve();
if (theatre.reserveSeat("A02")) {
System.out.println("Please pay for A02");
} else {
System.out.println("seat already reserved");
}
// see that they are clearly two separate array lists
Collections.reverse(seatCopy);
System.out.println("Printing seat copy");
printList(seatCopy);
System.out.println("Printing theatre.seats");
printList(theatre.seats);
System.out.println("Shuffling seatCopy");
Collections.shuffle(seatCopy);
printList(seatCopy);
}
public static void printList(List<Theatre.Seat> list) {
for (Theatre.Seat seat : list) {
System.out.print(" " + seat.getSeatNumber());
}
System.out.println();
System.out.println("===============================");
}
}
The output (I only quote enough to see ) is:
12 ͠11 ͠10 ͠09 ͠08 ͠07 ͠06 ͠05 ͠04 ͠03 ͠02 ͠01 ͟12 ͟
===============================
Printing theatre.seats
A01 A02 A03 A04 A05 A06 A07 A08 A09 A10
===============================
===============================
Shuffling seatCopy
V07 Ý11 11 ű05 Ú02 ̄06 ̓01 ŕ12 ȣ03 Ǔ05 S07
I am aware that I run out of alphabetical characters and that the formatting in this line:
Seat seat = new Seat(row + String.format("%02d", seatNum));
is intended only to deal with seats of the format "X##".
What I want to understand is specificallty why the odd characters appear ( the "~" and "'", etc. ). Obviously, the formatting is inappropriate. But why does it produce specifically this output?
Thank you for your help,
Marc
You said it yourself. You're running out of alphabetical characters. In fact, you're running out of ASCII characters altogether. From this line:
for (char row = 'A'; row <= lastRow; row++)
What you are doing is starting the row letters from 'A' and continuing across the Unicode character set. So, with more than 26 rows, you start getting symbols like ~, and with enough rows, you leave ASCII altogether and start getting weird row letters like Ý.
If you don't want this to happen, you'll need to ditch the for loop and come up with an entirely different (and more complex) way of assigning row labels.
I'm making a small game for a school project. In my game I have 9 cards on a 3x3 field, every card has 3 properties: count, shape and color. You have a set when 3 cards share the same or different properties, so when all colors are the same or different and all three shapes are the same or different and all the colors are the same or different.
For example:
1 red triangle, 1 red rectangle, 1 red ellipse.
1 blue triangle, 2 green triangle
The 3 priorities have to be the same of have to be different. As you see here above the first card has the same count, different shapes and the same color.
Now I have to make a function that will check how many sets there are on the table. I have a function that will check if 3 cards are a set, but I'm not able to make a function that will check all the possible combinations of 3 cards on the field. The cards on the field are saved in a 2 dimensional array.
My program is in Dutch:
setsOpTafel == sets on the table
kaarten == cards
aantalSets == number of sets
http://pastie.org/private/zqkfhqew1q8kwqvi6cvm0w
Can somebody help please?
edit:
How to function has to work.
so first of i have to check the combo of 3 cards -> card 1, card 2, card3.
Then card 1, card 2, card 4. and so forth till it has checked all the different combination of 3 different cards.
Here is simple solution. I dont know whether it is like you intended or not.
Run Code
class GAME {
static class Card {
public enum Shape {
square, triangle, circle
}
public enum Color {
red, blue, green
}
public int count;
public Shape shape;
public Color color;
public int gencode(boolean difcount, boolean difcolor, boolean difshape) {
int gen = -1;
if (difcount == true || difcolor == true || difshape == true) {
gen = 0;
}
if (difcount == true) {
gen = count+1;//for count=0
}
if (difcolor == true && shape != null) {
gen += 1000 * (shape.ordinal() + 1);
}
if (difshape == true && color != null) {
gen += 100000 * (color.ordinal() + 1);
}
return gen;
}
public String toString() {
String s = "Card::properties " + count;
if (color != null) {
switch (color) {
case red:
s += " red";
break;
case blue:
s += " blue";
break;
case green:
s += " green";
break;
default:
}
}
if (shape != null) {
switch (shape) {
case square:
s += " square";
break;
case triangle:
s += " triangle";
break;
case circle:
s += " circle";
break;
default:
}
}
return s;
}
}
public static void add(HashMap<Integer, ArrayList<GAME.Card>> cardmap, GAME.Card card, int key) {
ArrayList<GAME.Card> cardlist = cardmap.get(key);
if (cardlist == null) {
cardlist = new ArrayList<Card>();
cardlist.add(card);
cardmap.put(key, cardlist);
return;
}
cardlist.add(card);
return;
}
public static void showGroups( HashMap<Integer, ArrayList<GAME.Card>> cardmap){
for (List<GAME.Card> value : cardmap.values()) {
if(value.size()<=1) continue;
System.out.println("---------------------------------------------------");
int ii = 0;
for (GAME.Card p : value) {
ii += 1;
System.out.println("" + ii + ") "+p);
}
}
}
public static void main(String[] args) {
HashMap<Integer, ArrayList<GAME.Card>> cardmap = new HashMap< >();
GAME.Card[] allcards = new Card[9];
//init here (simple test
int lennn = GAME.Card.Shape.values().length;
int lennm = GAME.Card.Color.values().length;
Random randomGenerator = new Random();
for (int i = 0; i < allcards.length; i++) {
int ppp=randomGenerator.nextInt(9);
int kkk=randomGenerator.nextInt(2456);
allcards[i] = new Card();
allcards[i].count = ppp ;
allcards[i].shape = GAME.Card.Shape.values()[ppp % lennn];
allcards[i].color = GAME.Card.Color.values()[kkk % lennm];
}
System.out.println("######## Generated random cards");
int ii = 0;
for (GAME.Card p : allcards) {
ii += 1;
System.out.println("" + ii + ") "+p);
}
System.out.println("\n########Group at least by one property");
//group Cards by properties and its values
for (int i = 0; i < allcards.length; i++) {
//check one property
add(cardmap, allcards[i], allcards[i].gencode(true, false, false));
add(cardmap, allcards[i], allcards[i].gencode(false, true, false));
add(cardmap, allcards[i], allcards[i].gencode(false, false, true));
}
//show groups
showGroups(cardmap);
//check two
System.out.println("\n########Group at least by two properties");
cardmap = new HashMap< >();
//group Cards by properties and its values
for (int i = 0; i < allcards.length; i++) {
//check two properties
add(cardmap, allcards[i], allcards[i].gencode(true, true, false));
add(cardmap, allcards[i], allcards[i].gencode(true, false, true));
add(cardmap, allcards[i], allcards[i].gencode(false, true, true));
}
//show groups
showGroups(cardmap);
//check all
System.out.println("\n########Group by all properties");
cardmap = new HashMap< >();
//group Cards by properties and its values
for (int i = 0; i < allcards.length; i++) {
//check all properties
add(cardmap, allcards[i], allcards[i].gencode(true, true, true));
}
//show groups
showGroups(cardmap);
}
}
I am trying to have a mouse go through rooms to a target room. I am using a graph-like system with an x and y axis. I have a problem where the computer doesn't seem to want to add or subtract from an already existing variable.
Console:
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (6,5)
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (5,6)
Code for mouse:
package mouse_maze;
public class Mouse {
private int xCord = 5;
private int yCord = 5;
//position of the mouse when it starts
public int getXCord() {
return this.xCord;
}
public int getYCord() {
return this.yCord;
}
public void move() {
//method for the movement of the mouse
boolean verticalMove = Math.random() < .5;
boolean horizontalMove;
if (verticalMove == true)
horizontalMove = false;
else
horizontalMove = true;
int moveBy = 1;
if (Math.random() < .5)
moveBy = -1;
if (verticalMove) {
int test = this.yCord + moveBy;
if(test < 1 || test > 9) return;
this.yCord += moveBy;
}
if (horizontalMove) {
int test = this.xCord + moveBy;
if(test < 1 || test > 9) return;
this.xCord += moveBy;
}
System.out.println("The mouse is in room (" + xCord + "," + yCord + ")");
}
}
Code for maze:
package mouse_maze;
public class Maze {
private boolean onGoing = false;
private int tarX;
private int tarY;
//creates the target for the mouse.
public static void main(String[] args) {
new Maze(6, 8).init();
}
public Maze(int tarX, int tarY) {
this.tarX = tarX;
this.tarY = tarY;
}
public void init() {
this.onGoing = true;
while(this.onGoing)
this.iterate();
}
public void iterate() {
Mouse m = new Mouse();
m.move();
if (m.getXCord() == tarX && m.getYCord() == tarY) {
this.onGoing = false;
System.out.println("The mouse has beat the maze!");
//checks if the mouse has gotten to the target room.
}
}
}
First, learn to use a debugger, or at least learn to debug by whatever means. It is meaningless to always "assume" the problem without actually proving it.
Your whole problem has nothing to do with random etc.
In your iterate() method, you are creating a new mouse every time, instead of having the same mouse keep on moving.