Is there a solution to prevent this recursion? - java

In this program, a randomly generated 2D array is populated with 1's or 0's and I attempt to find a path of 1's (no diagonal movement). I have got the program to work for smaller dimensions of the 2D array, but when the dimensions are too large, the error Exception in thread "main" java.lang.StackOverflowError occurs.
import java.util.Scanner;
import java.util.Random;
public class Daft {
private int counter = 0;
public static void main(String[] args) {
Daft punk = new Daft();
punk.run();
}
public void run() {
int ans;
int[][] array;
int[][] solvedPath;
do {
counter = 1;
array = populate(defineArray(firstDimension(),secondDimension()));
solvedPath = findPath(array);
System.out.println("Times before solvable: " + counter);
print(solvedPath);
ans = continuity();
}while(ans != 0);
}
public int[][] findPath(int[][] array) {
int r = 0, c = 0;
while(true) {
array[0][0] = 7;
if(c == 0 && r == array.length-1) { //reached the bottom left, checks right
if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else {
array[r][c] = 7;
break;
}
} else if(c == array[0].length-1 && r == array.length-1) { //reached the bottom right, checks left
if(array[r][c-1] == 1) {
array[r][c-1] = 7;
} else {
array[r][c] = 7;
break;
}
} else if(r == array.length-1) { //reached the bottom, checks left/right
if(array[r][c+1] == 1 && array[r][c-1] == 1) {
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else { //end of path
array[r][c] = 7;
break;
}
} else if(c == 0) { //reached the left, checks right/bottom
if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(c == array[0].length-1) { //reached the right, checks left/bottom
if(array[r+1][c] == 1 && array[r][c-1] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) {
array[r][c-1] = 7;
c-=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c-1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) { //checks bottom
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else {
counter++;
newPath(array);
break;
}
}
return array;
}
public int firstDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the first dimension:");
return in.nextInt();
}
public int secondDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the second dimension:");
return in.nextInt();
}
public int[][] defineArray(int firstDimension, int secondDimension) {
return new int[firstDimension][secondDimension];
}
public int[][] populate(int[][] array) {
Random rand = new Random();
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
array[i][j] = rand.nextInt(2);
}
}
return array;
}
public int continuity() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to continue (0 to quit):");
return in.nextInt();
}
public void print(int[][] array) {
for(int[] ints : array) {
for(int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
System.out.println();
}
public void newPath(int[][] array) {
findPath(populate(array));
}
}

Related

How can I update my output on console in Java? (Right hand rule maze solver)

I'm trying to solve maze by using right hand rule, and my algorithm seems pretty good to me.
I have a little problem with my codes though.
I want to update my output on console, but I really don't know how to do it.
I kind of got the sense that I have to use Thread.sleep, but I don't know where to put it so that it can update my console constantly without printing whole new maze each move.
I want to make user can see the X's current position, and I want there's no trailing X.
It's a bit hard to explain with just words, so I made an gif picture.
And here are my codes. Thank you for anyone who will answer my question! Have a nice day y'all :D
public class MazeTraversalGradedProgram {
private static int row, column, count;
private static String direction = "right";
private static char maze1 [] [] = {
{'#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','#'},
{'.','.','#','.','#','.','#','#','#','#','.','#'},
{'#','#','#','.','#','.','.','.','.','#','.','#'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','#','#','#','.','#','.','#','.','#','.','#'},
{'#','.','.','#','.','#','.','#','.','#','.','#'},
{'#','#','.','#','.','#','.','#','.','#','.','#'},
{'#','.','.','.','.','.','.','.','.','#','.','#'},
{'#','#','#','#','#','#','.','#','#','#','.','#'},
{'#','.','.','.','.','.','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#'}};
private static char maze2 [] [] = {
{'#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','.','.','#','.','.','.','.','#'},
{'#','.','#','.','#','.','#','#','#','#','.','#'},
{'#','#','#','.','#','.','.','.','.','#','.','#'},
{'#','.','.','.','.','#','#','#','.','#','.','#'},
{'#','#','#','#','.','#','.','#','.','#','.','#'},
{'#','.','.','#','.','#','.','#','.','#','.','.'},
{'#','#','#','#','.','#','.','#','.','#','.','#'},
{'#','.','.','.','.','#','.','.','.','#','.','#'},
{'#','.','#','#','#','#','#','#','.','#','.','#'},
{'.','.','#','.','.','.','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#'}};
private static void printMaze (char [] [] maze) {
for (int i = 0; i<maze.length; i++) {
for(int j = 0; j<maze[i].length; j++) {
System.out.print(maze [i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println();
}
private static void goForward (char [] [] maze){
if (direction == "right") {
column++;
maze[row][column] = 'X';
} else if (direction == "up") { // array[xnd row --- ][ynd column | ]
row--;
maze[row][column] = 'X';
} else if (direction == "left") {
column--;
maze[row][column] = 'X';
} else if (direction == "down") {
row++;
maze[row][column] = 'X';
}
}
private static boolean wallOnRight (char [] [] maze) {
if (direction == "right" && maze[row+1][column] == '#') {
return true;
}
else if (direction == "up" && maze[row][column+1] == '#') {
return true;
}
else if (direction == "left" && maze[row-1][column] == '#') {
return true;
}
else if (direction == "down" && maze[row][column-1] == '#') {
return true;
}
return false;
}
private static boolean wallOnFront (char [] [] maze) {
if (direction == "right" && maze[row][column+1] == '#') {
return true;
}
else if (direction == "up" && maze[row-1][column] == '#') {
return true;
}
else if (direction == "left" && maze[row][column-1] == '#') {
return true;
}
else if (direction == "down" && maze[row+1][column] == '#') {
return true;
}
return false;
}
private static void traverseMaze (char [] [] maze){
if (count == 0) {
for (int i = 0; i < 12; i++) {
if (maze[i][0] == '.'){ // array[xnd row --- ][ynd column | ]
maze[i][0] = 'X';
row = i; column = 0;
}
}
count++;
}
if (wallOnRight(maze) && !wallOnFront(maze)) {
goForward(maze);
} else if (wallOnRight(maze) && wallOnFront(maze)) {
if (direction == "right") {
direction = "up";
} else if (direction == "up") {
direction = "left";
} else if (direction == "left") {
direction = "down";
} else if (direction == "down") {
direction = "right";
}
} else if (!wallOnRight(maze)) {
if (direction == "right") {
direction = "down";
} else if (direction == "up") {
direction = "right";
} else if (direction == "left") {
direction = "up";
} else if (direction == "down") {
direction = "left";
}
goForward(maze);
}
if (column == 11) {
count = 0 ;
} else {
traverseMaze(maze);
}
}
public static void main (String [] args){
printMaze(maze1);
traverseMaze(maze1);
printMaze(maze2);
traverseMaze(maze2);
}
}

Denary number to hexadecimal

As a homework, I was asked to write a program which would convert a denary number to hexadecimal. What I've created kinda works but as the output it gives me reversed number and I have no idea how to solve it (it is my first program).
public static void main(String[] args) {
System.out.println("Give a denary number: ");
Scanner sc = new Scanner(System.in);
int dec1 = sc.nextInt();
String dec = Integer.toString(dec1);
int zmienna;
for(int i = 0; i < dec.length(); i++) {
zmienna = dec1 % 16;
dec1 = dec1 / 16;
if(zmienna == 10) {
System.out.print("A");
}
else if (zmienna == 11) {
System.out.print("B");
}
else if (zmienna == 12) {
System.out.print("C");
}
else if (zmienna == 13) {
System.out.print("D");
}
else if (zmienna == 14) {
System.out.print("E");
}
else if (zmienna == 15) {
System.out.print("F");
}
else if (zmienna == 0 & i == dec.length() - 1) {
System.out.print("");
}
else {
System.out.print(zmienna);
}
}
}
I just change a little in your program i just tried to solve your problem and it works. I just added a StringBuilder and append characters and at the last reverse it.
code
import java.util.Scanner;
public class A {
public static void main(String[] args) {
System.out.println("Give a denary number: ");
Scanner sc = new Scanner(System.in);
int dec1 = sc.nextInt();
StringBuilder sb =new StringBuilder();
String dec = Integer.toString(dec1);
int zmienna;
for(int i = 0; i < dec.length(); i++) {
zmienna = dec1 % 16;
dec1 = dec1 / 16;
if(zmienna == 10) {
//System.out.print("A");
sb.append("A");
}
else if (zmienna == 11) {
//System.out.print("B");
sb.append("B");
}
else if (zmienna == 12) {
//System.out.print("C");
sb.append("C");
}
else if (zmienna == 13) {
//System.out.print("D");
sb.append("D");
}
else if (zmienna == 14) {
//System.out.print("E");
sb.append("E");
}
else if (zmienna == 15) {
// System.out.print("F");
sb.append("F");
}
else if (zmienna == 0 & i == dec.length() - 1) {
System.out.print("");
}
else {
//System.out.print(zmienna);
sb.append(zmienna);
}
}
System.out.println(sb.reverse());
}
}

How can I check java console output

I am making SOS game with "stack".No other data structures such as normal array, string etc.
Gameboard size 3*6 and I am using random for determining letters.
But I don't know is the game over or not.
How can I control is there any horizontal or vertical sos at the console
Here is my code(I am beginner)
public static void main(String[] args) {
Random rnd = new Random();
Stack S1 = new Stack(6);
Stack S2 = new Stack(6);
Stack S3 = new Stack(6);
Stack ts1 = new Stack(6);
Stack ts2 = new Stack(6);
Stack ts3 = new Stack(6);
int Round = 0;
int satir;
boolean winner = false;
// for S1
int i = 0;
while (i != 6) { // 6time
i++;
// System.out.println(i);
if (rnd.nextBoolean()) {
S1.push("S");
} else {
S1.push("O");
}
}
// for S2
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S2.push("S");
} else {
S2.push("O");
}
}
// for S3
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S3.push("S");
} else {
S3.push("O");
}
}
int a = 0, b = 0, c = 0;
int tempa = a;
int tempb = b;
int tempc = c;
while (!winner) {
System.out.println("User" + ((Round % 2) + 1) + ":"); // User1:
// User2:
satir = rnd.nextInt(3) + 1;
if (satir == 1 && a != 6) {
a++;
}
if (satir == 2 && b != 6) {
b++;
}
if (satir == 3 && c != 6) {
c++;
}
tempa = a;
tempb = b;
tempc = c;
System.out.print("S1 ");
while (a > 0) { // S1 in icini yazdir bosalt ts1e kaydet
System.out.print(S1.peek() + " ");
ts1.push(S1.pop());
a--;
}
a = tempa;
while (!ts1.isEmpty()) { // S1i tekrar doldur
S1.push(ts1.pop());
}
System.out.println();
System.out.print("S2 ");
while (b > 0) { // S2 in icini yazdir bosalt ts1e kaydet
System.out.print(S2.peek() + " ");
ts2.push(S2.pop());
b--;
}
b = tempb;
while (!ts2.isEmpty()) { // S2i tekrar doldur
S2.push(ts2.pop());
}
System.out.println();
System.out.print("S3 ");
while (c > 0) { // S3 in icini yazdir bosalt ts1e kaydet
System.out.print(S3.peek() + " ");
ts3.push(S3.pop());
c--;
}
c = tempc;
while (!ts3.isEmpty()) { // S3i tekrar doldur
S3.push(ts3.pop());
}
System.out.println();
// check if there is sos winner=true;
if (a > 2) { //check S1 Horizontal
for (int yatay1 = 0; yatay1 < a; yatay1++) {
if (S1.peek().equals("S")) {
ts1.push(S1.pop());
if (S1.peek().equals("O")) {
ts1.push(S1.pop());
if (S1.peek().equals("S")) {
System.out.println("SOS-wow");
winner = true;
} else {
while (!ts1.isEmpty()) {
S1.push(ts1.pop());
}
}
} else {
S1.push(ts1.pop());
}
}
}
}
Round++;
} // end of loop
}

Java game error

I'm programming a java game. It's almost done but it's giving me a error (and I don't understand why it happens, the code seems okay).
Error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: projetofinal.ProjetoFinalv2.movimento
at projetofinal.ProjetoFinalv2.main(ProjetoFinalv2.java:26)
C:\Users\Francisco\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)
Here's the code:
package projetofinal;
import java.util.Scanner;
import java.util.Random;
public class ProjetoFinalv2 {
static char[][] tabuleiro;
static int x, y, jogadorX, jogadorY, pontos;
static char direction;
static boolean inGame = true;
public static void main(String[] args) {
x = 5;
y = 5;
tabuleiro = new char[x][y];
jogadorX = 0;
jogadorY = 4;
pontos = 7;
quadro();
while(inGame == true)
{
customcreator();
Scanner scan = new Scanner(System.in);
String resposta = scan.nextLine();
movimento(resposta.charAt(0));
}
}
public static void placePot()
{
boolean notDone = true;
while(notDone)
{
int tabX = random(0, 4);
int tabY = random(0, 4);
if(tabuleiro[tabX][tabY] == '.')
{
tabuleiro[tabX][tabY] = 'P';
notDone = false;
}
}
}
public static boolean bomba(int x, int y)
{
if(tabuleiro[x][y] == 'B')
{
return true;
}
else
{
return false;
}
}
public static boolean win()
{
if(tabuleiro[jogadorX][jogadorY] == 'F')
{
return true;
}
else
{
return false;
}
}
public static boolean gameover()
{
if(pontos > 0)
{
return false;
}
else
{
return true;
}
}
public static int potepoints(int x, int y)
{
if(tabuleiro[x][y] == 'P')
{
return random(3,5);
}
else
{
return -1;
}
}
public static void quadro()
{
for(int linha = 0; linha < x; linha++)
{
for(int vertical = 0; vertical < y; vertical++)
{
tabuleiro[linha][vertical] = '.';
}
}
//Por as bombas na posição correta
for(int i = quantos(); i>0; i--)
{
boolean tab = true;
while(tab)
{
int tabX = random(1, 3);
int tabY = random(1, 2);
if(tabuleiro[tabX][tabY] != 'B')
{
tabuleiro[tabX][tabY] = 'B';
tab = false;
}
}
}
//Mete o pote que da pontos
placePot();
}
public static void tabuleirocreator()
{
playercreator();
for(int linha = 0; linha < y; linha++)
{
for(int vertical = 0; vertical < x; vertical++)
{
System.out.print(tabuleiro[vertical][linha]);
}
System.out.print("\n");
}
}
public static void playercreator()
{
tabuleiro[jogadorX][jogadorY] = 'J';
}
public static void customcreator()
{
tabuleiro[0][4] = 'I';
tabuleiro[4][0] = 'F';
tabuleirocreator();
}
public static int random(int min, int max)
{
Random generator = new Random();
int Num = generator.nextInt((max - min) + 1) + min;
return Num;
}
public static int quantos()
{
return random(2, 3);
}
}
//Ciclo do jogo
public static void movimento(char newDirection)
{
if(newDirection == 'w' || newDirection == 'W')
{
if(jogadorY > 0)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorY -= 1;
pontos--;
}
}
else
{
if(newDirection == 'a' || newDirection == 'A')
{
if(jogadorX > 0)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorX -= 1;
pontos--;
}
}
else
{
if(newDirection == 's' || newDirection == 'S')
{
if(jogadorY < 4)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorY += 1;
pontos--;
}
}
else
{
if(newDirection == 'd' || newDirection == 'D')
{
if(jogadorX < 4)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorX += 1;
pontos--;
}
}
else
{
System.out.println("Wrong direction!");
}
}
}
}
if(bomba(jogadorX, jogadorY))
{
pontos = 0;
}
int tab = potepoints(jogadorX, jogadorY);
if(tab != -1)
{
pontos += tab;
}
if(win())
{
System.out.println("You won");
inGame = false;
}
if(gameover())
{
System.out.println("Game Over");
inGame = false;
}
}
//////////////////////////////////////////////////////////////
I'm a quite noob in java (i started to learn recently) so, i'm sorry if the question is bad.
The message tells you that the compiler cannot find a definition for projetofinal.ProjetoFinalv2.movimento, a symbol on line 26: movimento(resposta.charAt(0));. But movimento is not defined inside the class. The class definition ends with the closing brace (}) just before the orphaned method definition for movimento. Not only does that make the method definition inaccessible to the caller, it is utterly illegal to define methods or variables outside of a class.

Nim game backtracking doesn't work on all row sequences - Java

I have a question. As an assignment we have to make the Nim game resolver using backtracking to predict which player is going to win based on the input on which player is going to start first (assuming that both players have a perfect decision rate).
Here is the code for the NimGame:
package Nim;
import java.util.ArrayList;
public class NimGame {
private int[] elements;
public NimGame(int[] elements) {
this.elements = new int[elements.length];
this.elements = elements;
}
public int NimSolver(boolean player) {
if (player == true && NimHelp(elements) == true) {
return 1;
} else if (player == false && NimHelp(elements) == true) {
return -1;
} else {
int score = 0;
int tmp = 0;
if (player == true) {
score = -1;
} else {
score = 1;
}
for (int i = 0; i < elements.length; i++) {
for (int j = 1; j <= elements[i]; j++) {
// Decrement element (Do thing)
elements[i] -= j;
// Backtrack
tmp = NimSolver(!player);
// SetScore
if (player == true && tmp > score) {
score = tmp;
} else if (player == false && tmp < score) {
score = tmp;
}
// Increment element (Undo thing)
elements[i] += j;
}
}
return score;
}
}
private boolean NimHelp(int[] elements) {
boolean[] isEmpty = new boolean[elements.length];
for (int i = 0; i < elements.length; i++) {
if (elements[i] == 0) {
isEmpty[i] = true;
} else {
isEmpty[i] = false;
}
}
for (boolean value : isEmpty) {
// If not all value is empty return false
if (!value)
return false;
}
return true;
}
public void NimResult(int player,int result)
{
if (player == 1) {
result = NimSolver(true);
} else if (player == 2) {
result = NimSolver(false);
}
if (result == 1) {
System.out.println("");
System.out.println("PLAYER 1 WON");
} else {
System.out.println("");
System.out.println("PLAYER 2 WON");
}
}
public void NimPrint(ArrayList<Integer> element)
{
System.out.println("");
System.out.print("MATCHES--------------------------------------");
for(int i = 0; i < element.size() ;i++)
{
System.out.println("");
for (int j = 0; j < element.get(i) ; j++) {
System.out.print("|");
}
}
}
}
Here is the code for Test Main class:
package Main;
import java.util.ArrayList;
import java.util.Scanner;
import Nim.NimGame;
public class Main {
public static void main(String[] args) {
int rows;
int elementTmp;
ArrayList<Integer> rowTmp = new ArrayList<Integer>();
int playerNo;
int result = 0;
int[] elements;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Input number of rows: ");
rows = sc.nextInt();
elements = new int[rows];
System.out.println("");
System.out.println("Input number of elements in each row");
for (int i = 0; i < rows; i++) {
System.out.print("Row number " + (i + 1) + " : ");
elementTmp = sc.nextInt();
elements[i] = elementTmp;
rowTmp.add(elementTmp);
}
NimGame nim = new NimGame(elements);
nim.NimPrint(rowTmp);
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("");
System.out.println("First player to move");
System.out.println("1) Player 1");
System.out.println("2) Player 2");
System.out.print("Input: ");
playerNo = sc.nextInt();
nim.NimResult(playerNo, result);
}
}
It works for the sequence: 3 rows , Row1 = 1, Row2 = 2, Row3 = 3 for example:
Input number of rows: 3
Input number of elements in each row
Row number 1 : 1
Row number 2 : 2
Row number 3 : 3
MATCHES--------------------------------------
|
||
|||
---------------------------------------------
First player to move
1) Player 1
2) Player 2
Input: 1
PLAYER 2 WON
But it doesn't work for all the sequences. I don't understand why.

Categories

Resources