Java game error - java

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.

Related

Build Blackjack program in Java, but "split" method would require rewriting whole program?

Getting back into programming after many years, and build a simple "blackjack" program in Java.
I'm wondering if the way I structured the methods/objects is bad, using global static variables. The program seems to work fine, but there's no way to implement a "split" method without re-writing everything, since you can't pass the new "split" hands into the "hit" or "stand" functions.
I'm curious how others would structure this and what the flaws in my methodology were. Thanks!
import java.io.*;
import java.util.*;
public class BlackJack {
static int bankroll = 0;
static int bet = 1;
static int index = 0;
static CardDeck d = new CardDeck();
static ArrayList<Card> playerCards = new ArrayList<Card>();
static ArrayList<Card> playerCards2 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards3 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards4 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards5 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards6 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> dealerCards = new ArrayList<Card>(); //unused - was thinking of using for splitting
static int playerScore = 0;
static int dealerScore = 0;
static String action = "";
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
initializeBankroll();
while (bet != 0) {
startRound();
display();
if(checkBlackJacks()) continue;
while (playerScore <= 21) {
System.out.println("H - hit, S - stand, X - surrender, D - double down");
action = s.nextLine();
if (action.equals("H")) hit();
else if (action.equals("S")) {
stand();
break;
}
else if (action.equals("X")) surrender();
else if (action.equals("D")) {
doubleDown();
break;
}
}
eval();
}
}
public static int score (ArrayList<Card> list) {
int ret = 0;
int acecounter = 0;
for (int i=0; i<list.size(); i++) {
if (list.get(i).getVal()>1) {
ret += Math.min(10, list.get(i).getVal());
}
else { //An ace
ret += 11;
acecounter++;
}
}
while(ret >21 && acecounter >0) {
ret -= 10;
acecounter -= 1;
}
return ret;
}
public static void dealToPlayer() {
playerCards.add(d.getCard(index));
index++;
}
public static void dealToDealer() {
dealerCards.add(d.getCard(index));
index++;
}
public static void display() {
System.out.println("PLAYER CARDS:");
String playerCardString = "";
for (int i=0; i<playerCards.size(); i++) {
playerCardString += playerCards.get(i).toString();
playerCardString += " ";
}
System.out.println(playerCardString);
System.out.println("DEALER CARD:");
System.out.println(dealerCards.get(0).toString());
}
public static void hit() {
dealToPlayer();
reScore();
display();
}
public static void surrender() {
if(playerCards.size()>2) {
System.out.println("You can't do that");
return;
}
bankroll -= (bet / 2);
playerScore = 100; //surrender
}
public static void reScore() {
playerScore = score(playerCards);
dealerScore = score(dealerCards);
}
public static void stand() {
try {
System.out.println("DEALER DOWNCARD: " + dealerCards.get(1).toString());
Thread.sleep(1000);
while (dealerScore <17) {
dealToDealer();
System.out.println(dealerCards.get(dealerCards.size()-1).toString());
reScore();
System.out.println("DEALER SCORE " + Integer.toString(dealerScore));
Thread.sleep(1000);
}
}catch(Exception E) {
System.out.println("Exception");
}
}
public static void doubleDown() {
if(playerCards.size()>2) {
System.out.println("You can't do that, hitting instead");
hit();
if(playerScore<=21) stand();
return;
}
if( bet * 2 > bankroll) {
System.out.println("Doubling for less...");
bet = bankroll;
hit();
if(playerScore<=21) stand();
return;
}
bet *= 2;
hit();
if(playerScore<=21) stand();
}
public static void split(ArrayList<Card> splitarray, int splitcount) { //INCOMPLETE. How to get this to work?
if(splitarray.size()>2 || bet * (splitcount+1) > bankroll || splitarray.get(1).getVal() != splitarray.get(0).getVal()) {
System.out.println("Can't split. Hitting instead");
hit();
}
ArrayList<Card> s1 = new ArrayList<Card>();
ArrayList<Card> s2 = new ArrayList<Card>();
s1.add(splitarray.get(0));
s2.add(splitarray.get(1));
}
public static void eval() {
if (playerScore==100) { //indicates a surrender, and bankroll has already been adjusted
return;
}
if (playerScore>21) {
System.out.println("BUST");
bankroll -= bet;
return;
}
if (dealerScore>21) {
System.out.println("DEALER BUST");
bankroll += bet;
return;
}
if (playerScore > dealerScore) {
System.out.println("WIN");
bankroll += bet;
return;
}
if (playerScore < dealerScore) {
System.out.println("LOSE");
bankroll -= bet;
return;
}
System.out.println("PUSH");
return;
}
public static void newhand() {
d.shuffle();
playerCards.clear();
dealerCards.clear();
index = 0;
reScore();
}
public static boolean checkBlackJacks() {
if(playerScore == 21) {
if(dealerCards.get(0).getVal()==1) {
System.out.println("Even money? Y / N");
String even = s.nextLine();
if (even=="Y"){
bankroll += bet;
newhand();
return true;
}
}
if(dealerScore != 21) {
System.out.println("BlackJack");
bankroll += (1.5 * bet);
newhand();
return true;
}
else {
System.out.println("Push - Mutual Blackjack");
newhand();
return true;
}
}
if(dealerCards.get(0).getVal()==1) { //insurance
System.out.println("Insurance? Type wager or 0, up to half your bet");
int insuranceBet = s.nextInt();
if (insuranceBet > bankroll) insuranceBet = bankroll;
if (insuranceBet > (bet / 2)) insuranceBet = bet / 2;
if (dealerScore == 21) bankroll += (insuranceBet * 2);
else bankroll -= insuranceBet;
}
if(dealerScore==21) {
System.out.println("Dealer Blackjack");
bankroll -= bet;
newhand();
return true;
}
return false;
}
public static void initializeBankroll() {
System.out.println("Enter your buy-in");
bankroll = s.nextInt();
}
public static void startRound() {
newhand();
System.out.println("Money remaining:" + Integer.toString(bankroll));
System.out.println("Enter your bet");
bet = s.nextInt();
if (bet>bankroll) bet=0;
dealToPlayer();
dealToDealer();
dealToPlayer();
dealToDealer();
reScore();
}
}
___________________
public class Card {
int val; //1 = Ace, 11 = Jack, 12 = Queen, 13 = King
int suit; //1 = Club, 2 = Diamond, 3 = Heart, 4 = Spade
public Card() {
this(1,1);
}
public Card(int val, int suit) {
this.val = val;
this.suit = suit;
}
public int getSuit(){
return suit;
}
public int getVal() {
return val;
}
public void setVal(int a) {
if(a>=1 && a<= 13) val = a;
}
public void setSuit(int a) {
if (a>=1 && a<=4) suit = a;
}
public String toString() {
String valString = "";
String suitString = "";
String ret = "";
switch(val) {
case 1: valString = "A"; break;
case 10: valString = "T"; break;
case 11: valString = "J"; break;
case 12: valString = "Q"; break;
case 13: valString = "K"; break;
default: valString = Integer.toString(val);
}
switch(suit) {
case 1: suitString = "c"; break;
case 2: suitString = "d"; break;
case 3: suitString = "h"; break;
case 4: suitString = "s"; break;
default: suitString = "ERROR"; break;
}
ret = valString + suitString;
return ret;
}
}
______________________
public class CardDeck{
Card[] deck;
public CardDeck(){
int k=0;
deck = new Card[52];
for (int i=0; i<13; i++){
for (int j=0; j<4; j++){
Card c = new Card(i+1,j+1);
deck[k]=c;
k++;
}
}
shuffle();
}
public void shuffle(){
Card[] deckCopy = new Card[52];
boolean[] flags = new boolean[52];
for (int i=0; i<flags.length; i++) flags[i]=false;
int numConverted=0;
while(numConverted<52){
int num = (int)(Math.random() * 52);
if (flags[num]==false){
deckCopy[numConverted]=deck[num];
numConverted++;
flags[num]=true;
}
}
deck = deckCopy;
} //end shuffle
public String toString() {
String ret = "";
for (int i = 0; i<deck.length; i++) {
ret += deck[i].toString();
ret += " ";
}
return ret;
}
public Card getCard(int a) {
if (a<0 || a > 51) return null;
else return deck[a];
}
public int getSuit(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getSuit();
}
public int getVal(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getVal();
}
}

Peg solitaire solution change destination

I wrote a program that solves a peg solitaire in java.
My program gets a starting board and a destination board and try to finish the game.
I have a sort of counter that count my turn because I have a destination with more the 1 peg rest and as assume that if I have to remove only 2 pegs so I can solve it in only 2 moves.
I have an board class that I create:
public class Board {
private int board[][] = new int[7][7];
public Board(String place)
{
board[0][0]=2;
board[1][0]=2;
board[5][0]=2;
board[6][0]=2;
board[0][1]=2;
board[1][1]=2;
board[5][1]=2;
board[6][1]=2;
board[0][5]=2;
board[1][5]=2;
board[5][5]=2;
board[6][5]=2;
board[0][6]=2;
board[1][6]=2;
board[5][6]=2;
board[6][6]=2;
int loca=0;//location on the string of place
for(int i=0;i<7;i++){
for(int j=0;j<7;j++){
if(board[i][j]!=2) {
if (place.charAt(loca) == 'O') {
loca++;
board[i][j] = 1;
} else if (place.charAt(loca) == '.') {
loca++;
board[i][j] = 0;
}
}
System.out.print(board[i][j]);//print for test
}
System.out.println();//print for test
}
System.out.println();
}
public Board(Board copy){
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
board[i][j]=copy.getValue(i,j);
}
}
}
public int getValue(int x, int y)
{
return board[x][y];
}
public boolean isFinished(Board destination)
{
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
if(this.getValue(i,j)!=destination.getValue(i,j))
{
return false;
}
}
}
return true;
}
public Board turn(Board board,String direction,int x,int y)
{
if(direction.equals("right"))
{
board.setValue(x,y,0);
board.setValue(x+1,y,0);
board.setValue(x+2,y,1);
return board;
}
else if(direction.equals("left"))
{
board.setValue(x,y,0);
board.setValue(x-1,y,0);
board.setValue(x-2,y,1);
return board;
}
else if(direction.equals("up"))
{
board.setValue(x,y,0);
board.setValue(x,y-1,0);
board.setValue(x,y-2,1);
return board;
}
else if(direction.equals("down"))
{
board.setValue(x,y,0);
board.setValue(x,y+1,0);
board.setValue(x,y+2,1);
return board;
}
else{
System.out.println("there is not such direction, method turn on board class");
return null;//just for caution
}
}
public boolean isLegal(int x, int y){
if(board[x][y]==2)
{
return false;
}
else{
return true;
}
}
public boolean canTurn(String direction,int x,int y){
if(direction.equals("right"))
{
if(x<5) {
if (board[x][y] == 1 && board[x + 1][y] == 1 && board[x + 2][y] == 0) {
return true;
}
}
}
else if(direction.equals("left"))
{
if(x>1) {
if (board[x][y] == 1 && board[x - 1][y] == 1 && board[x - 2][y] == 0) {
return true;
}
}
}
else if(direction.equals("up"))
{
if(y>1) {
if (board[x][y] == 1 && board[x][y - 1] == 1 && board[x][y - 2] == 0) {
return true;
}
}
}
else if(direction.equals("down"))
{
if(y<5) {
if (board[x][y] == 1 && board[x][y + 1] == 1 && board[x][y + 2] == 0) {
return true;
}
}
}
else{
System.out.println("there is not such direction, method canTurn on board class");
return false;//just for caution
}
return false;
}
public void setValue(int x, int y, int value)
{
board[x][y]=value;
}
}
and I wrote my "solver" class.
public class PegSolver {
public int peg =1;
Board destinationBoard = new Board("OOOOOOOOOOOOOOOOO..OOOOOOOOOOOOOO");
Board board = new Board("OOOOOOOOOOOOOOOO.OOOOOOOOOOOOOOOO");
public void start(){
solve(0,board);
}
public boolean solve(int turn, Board board){
Board temp = new Board(board);
if(turn>peg)
{
return false;
}
else if(turn==peg){
//todo:check if solve
if(temp.isFinished(destinationBoard))
{
System.out.println("solution");
return true;
}
else
{
return false;
}
}
else//lower then 8
{
for(int i=0;i<7;i++){
for (int j=0;j<7;j++)
{
if(board.isLegal(i,j)) {
if(board.canTurn("right",i,j) && solve(turn++, temp.turn(temp, "right", i, j)))
{
return true;
}
else if(board.canTurn("left",i,j) && solve(turn++, temp.turn(temp, "left", i, j)))
{
return true;
}
else if(board.canTurn("up",i,j) && solve(turn++, temp.turn(temp, "up", i, j)))
{
return true;
}
else if(board.canTurn("down",i,j) && solve(turn++, temp.turn(temp, "down", i, j)))
{
return true;
}
}
}
}
}
return false;
}
}
When the program finds a solution, it needs to print "solution" but for some reason my program can't find a solution even when it's a basic destination with one move.
Can someone help me please?
Please review the modified code.
Many of the changes are related to indices and directions inconsistency across the code: where x represents horizontal index and y represents vertical index: array index should be board[y][x] (and not board[x][y]).
Many "magic numbers" were changed to constants for better readability of the code.
A toString method was added to the Boardclass to print out a board state. It uses special characters to make a nice printout :
This is helpful when debugging.
public class PegSolver {
private final Board startBoard, destinationBoard;
public PegSolver(Board startBoard, Board destinationBoard) {
super();
this.startBoard = startBoard;
this.destinationBoard = destinationBoard;
}
public void start(){
solve(0,startBoard);
}
private boolean solve(int turn, Board board){
//check if solve
if(board.isFinished(destinationBoard))
{
System.out.println("solved after "+ turn +" turns");
return true;
}
for(int x=0;x<board.boardSize();x++){
for (int y=0;y<board.boardSize();y++)
{
if(board.isLegal(x,y)) {
if(board.canTurn("right",x,y)
//turn++ changed to turn+1 so turn is incremented before invoking next solve
//and avoid changing the value of turn
&& solve(turn+1, board.turn(new Board(board), "right", x, y)))
return true;
else if(board.canTurn("left",x,y)
&& solve(turn+1, board.turn(new Board(board), "left", x, y)))
return true;
else if(board.canTurn("up",x,y)
&& solve(turn+1, board.turn(new Board(board), "up", x, y)))
return true;
else if(board.canTurn("down",x,y)
&& solve(turn+1, board.turn(new Board(board), "down", x, y)))
return true;
}
}
}
return false;
}
public static void main(String[] args) {
Board[] destinationBoards = {
//by order of number of turns
new Board("OOOOOOOOOOOOOO..OOOOOOOOOOOOOOOOO"), //one right turn
new Board("OOO.OOOO.OOOOO.OOOOOOOOOOOOOOOOOO"), //right, down
new Board("OOO.OO..OOOOOO.OOOOOOOOOOOOOOOOOO"), //right, down,right
new Board("OOO.OOO.OOOOO..OOOOO.OOOOOOOOOOOO"), //right, down,right,up
new Board("OOOOOOO..OOOO...OOOO.OOOOOOOOOOOO"), //right, down,right,up,up
new Board(".OO.OOO.OOOOO...OOOO.OOOOOOOOOOOO"), //right, down,right,up,up,down
new Board(".OO.OOO.OOOOO...OOOOO..OOOOOOOOOO"), //right, down,right,up,up,down, left
new Board(".OO.OOO.OOOOO...OOOOO.OOOOO.OO.OO"), //right, down,right,up,up,down,left,up
new Board(".OO.OO..O.OOO...OOOOO.OOOOO.OO.OO"), //10 turns
new Board("..O..O.O..OOO...OOOO..OOOOO..O..O"), //15 turns
new Board(".........O................O......"), //30 turns
new Board("...................O............."), //31 turns
};
Board startBoard = new Board("OOOOOOOOOOOOOOOO.OOOOOOOOOOOOOOOO");
for(Board destinationBoard : destinationBoards ){
new PegSolver(startBoard, destinationBoard).start();
}
}
}
class Board {
//int representation of the three states of a board cell
private final static int EMPTY = 0, PEG = 1, BORDER = 2;
/*cahr representation of the three states of a board cell
special chars are used to get nice printout
todo: change board to char[][] to avoid the need for two
representations (int and char)
*/
private final static char[] CHAR_REPRESENTATION = {9898,9899,10062};
private final static char ERROR = '?';
private final int BOARD_SIZE=7, CORNER_SIZE=2;
private final int board[][] = new int[BOARD_SIZE][BOARD_SIZE];
public Board(String place) {
int loca=0;
for(int y=0;y<BOARD_SIZE;y++){
for(int x=0;x<BOARD_SIZE;x++){
if(isWithinBoard(x,y)) {
if (place.charAt(loca) == 'O') {
loca++;
board[y][x] = PEG;
} else if (place.charAt(loca) == '.') {
loca++;
board[y][x] = EMPTY;
}
}else{
board[y][x] = BORDER;
}
}
}
//for testing
//System.out.println(this);
}
//copy constructor
public Board(Board copy){
for(int x=0;x<BOARD_SIZE;x++)
{
for(int y=0;y<BOARD_SIZE;y++)
{
board[y][x]=copy.getValue(x,y);
}
}
}
public int getValue(int x, int y)
{
return board[y][x]; //and not return board[x][y];
}
public boolean isFinished(Board destination)
{
for(int i=0;i<BOARD_SIZE;i++)
{
for(int j=0;j<BOARD_SIZE;j++)
{
if(this.getValue(i,j)!=destination.getValue(i,j))
return false;
}
}
return true;
}
public Board turn(Board board,String direction,int x,int y)
{
if(direction.equals("right"))
{
board.setValue(x,y,EMPTY);
board.setValue(x+1,y,EMPTY);
board.setValue(x+2,y,PEG);
return board;
}
else if(direction.equals("left"))
{
board.setValue(x,y,EMPTY);
board.setValue(x-1,y,EMPTY);
board.setValue(x-2,y,PEG);
return board;
}
else if(direction.equals("up"))
{
board.setValue(x,y,EMPTY);
board.setValue(x,y-1,EMPTY);
board.setValue(x,y-2,PEG);
return board;
}
else if(direction.equals("down"))
{
board.setValue(x,y,EMPTY);
board.setValue(x,y+1,EMPTY);
board.setValue(x,y+2,PEG);
return board;
}
System.out.println("there is not such direction, method turn on startBoard class");
return null;
}
public boolean isLegal(int x, int y){
if(board[y][x]==BORDER) //and not if(board[x][y]==BORDER)
return false;
return true;
}
public boolean canTurn(String direction,int x,int y){
if(direction.equals("right") && x < BOARD_SIZE - 2)
{
if (board[y][x] == PEG && board[y][x + 1] == PEG && board[y][x + 2] == EMPTY)
return true;
}
else if(direction.equals("left") && x > 1)
{
if (board[y][x] == PEG && board[y][x - 1] == PEG && board[y][x - 2] == EMPTY)
return true;
}
else if(direction.equals("up") && y > 1)
{
if (board[y][x] == PEG && board[y - 1][x] == PEG && board[y - 2][x] == EMPTY)
return true;
}
else if(direction.equals("down") && y < BOARD_SIZE - 2)
{
if (board[y][x] == PEG && board[y + 1][x] == PEG && board[y + 2][x] == EMPTY)
return true;
}
return false;
}
public void setValue(int x, int y, int value)
{
board[y][x]=value; //and not board[x][y]=value;
}
//for square nxn board
public int boardSize(){
return board.length;
}
public boolean isWithinBoard(int x, int y){
//check bounds
if (x < 0 || y < 0 || x >= BOARD_SIZE || y >= BOARD_SIZE) return false;
//left top corner
if (x < CORNER_SIZE && y < CORNER_SIZE) return false;
//right top corner
if(x >= BOARD_SIZE - CORNER_SIZE && y < CORNER_SIZE) return false;
//left bottom corner
if(x < CORNER_SIZE && y >= BOARD_SIZE - CORNER_SIZE) return false;
//right bottom corner
if(x >= BOARD_SIZE - CORNER_SIZE && y >= BOARD_SIZE - CORNER_SIZE) return false;
return true;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int[] row : board) {
for(int cell : row){
if(cell<CHAR_REPRESENTATION.length && cell >= 0) {
sb.append(CHAR_REPRESENTATION[cell]);
}else{
sb.append(ERROR);
}
}
sb.append("\n"); //new line
}
return sb.toString();
}
}
Todo:
The code is working but it needs further in-depth testing and debugging.
If something is not clear, don't hesitate to ask.

Is there a solution to prevent this recursion?

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));
}
}

PALIN- The next Palindrome - a SPOJ problem

I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}

Time limit exceeded online judge

This is the problem :
Input
The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T
lines contains a positive integer N that is no more than 80 digits in length.
Output
The output of each test case will be a single line containing the smallest palindrome that is greater
than or equal to the input number.
Sample Input
2
42
321
Sample Output
44
323
I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit)
class Main {
static String ReadLn (int maxLg)
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
static boolean isPalandriome(String s){
String newString = "";
for(int i =s.length()-1;i >= 0; i--){
newString += s.charAt(i);
}
if(newString.equals(s))
return true;
else
return false;
}
public static void main(String[] args) {
BigInteger entredNumber;
String input;
input = Main.ReadLn(10);
int tests = Integer.parseInt(input);
List<BigInteger> numbers = new ArrayList<BigInteger>();
for (int i =0;i<tests;i++)
{
input = Main.ReadLn(100);
entredNumber = new BigInteger(input);
numbers.add(entredNumber);
}
for(int i=0;i<tests;i++){
BigInteger number = numbers.get(i);
while(!isPalandriome(String.valueOf(number))){
number = number.add(BigInteger.ONE);
}
System.out.println(number);
}
}
}
I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
CustomReader cr = new CustomReader(1000000);
int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex;
StringBuilder output = new StringBuilder();
byte[] input;
boolean isAppend1 = false;
for (int i = 0; i < T; i++) {
input = cr.nextInput();
fStartIndex = bStartIndex = cr.getCurrInputLength() / 2;
isAppend1 = false;
if (cr.getCurrInputLength() % 2 == 0) {
bStartIndex--;
}
fIndex = fStartIndex;
bIndex = bStartIndex;
while (input[bIndex] == input[fIndex]) {
if (bIndex - 1 < 0) {
break;
} else {
bIndex--;
fIndex++;
}
}
if (input[bIndex] > input[fIndex]) {
while (bIndex >= 0) {
input[fIndex++] = input[bIndex--];
}
} else {
if (input[bStartIndex] < 57) {
input[bStartIndex] = (byte) (input[bStartIndex] + 1);
} else {
bIndex = bStartIndex;
while (bIndex >= 0 && input[bIndex] == 57) {
input[bIndex] = 48;
bIndex--;
}
if (bIndex >= 0) {
input[bIndex] = (byte) (input[bIndex] + 1);
} else {
input[0] = 49;
if (fStartIndex != bStartIndex) {
input[fStartIndex] = 48;
bStartIndex = fStartIndex;
} else {
input[fStartIndex + 1] = 48;
bStartIndex = fStartIndex = fStartIndex + 1;
}
isAppend1 = true;
}
}
while (bStartIndex > -1) {
input[fStartIndex++] = input[bStartIndex--];
}
}
for (int j = 0; j < cr.getCurrInputLength(); j++) {
output.append((char) input[j]);
}
if (isAppend1) {
output.append("1");
}
output.append("\n");
}
System.out.print(output.toString());
// genInput();
}
private static class CustomReader {
private byte[] buffer;
private byte[] currInput = new byte[1000000];
private int currInputLength;
private int currIndex;
private int validBytesInBuffer;
CustomReader(int buffSize) {
buffer = new byte[buffSize];
}
public int nextInt() throws IOException {
int value;
byte b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
value = b - 48;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
value = (value * 10) + (b - 48);
} else {
break;
}
}
return value;
}
public byte[] nextInput() throws IOException {
byte b;
this.currInputLength = 0;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
currInput[currInputLength++] = b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
currInput[currInputLength++] = b;
} else {
break;
}
}
return this.currInput;
}
public int getCurrInputLength() {
return this.currInputLength;
}
private byte getNextByte() throws IOException {
if (currIndex == buffer.length || currIndex == validBytesInBuffer) {
validBytesInBuffer = System.in.read(buffer);
currIndex = 0;
}
return buffer[currIndex++];
}
}
public static void genInput() {
for (int i = 0; i < 100; i++) {
System.out.println((int) (Math.random() * 1000000000));
}
}
}

Categories

Resources