Welcome to Dream.In.Code
Become a Java Expert!

Join 150,357 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,877 people online right now. Registration is fast and FREE... Join Now!




Quick Program question:

2 Pages V  1 2 >  
Reply to this topicStart new topic

Quick Program question:, converting/changing methods

needhelpbadly
5 Feb, 2008 - 11:31 PM
Post #1

New D.I.C Head
*

Joined: 5 Feb, 2008
Posts: 13

* I put a lot of time into this post so please help me. *
This is for a project due soon.. Immediate attention necessary


Hello all, I hope I have permission to ask here, if not -- can you please link me to a forum that allows code/project help?

Let me explain just a little before I ask - I have to make a Knight's Tour program, on an 8x8 grid.
I already completed the project, but found out that instead of user input, it is supposed to quickly process the solution (meaning random numbers).

Everything is set up and working correctly, but I have the user inputs instead of the random.

Here are my questions:

There are 2 main lines where the program asks for input,
CODE
int m = in.nextInt()-1; and
moveNumber = in.nextInt()-1;

I'm thinking I can edit those methods (including removing the print line statements about entering an integer) and add a:

CODE

Random rndgenerator = new Random.nextInt(8) +1;

//the +1 makes a random int of 0-7 become 1-8 ( what we want )

twice, with the generator having a different name.

Also, we mustn't forget about


CODE
import java.util.Random;





Is this conversion as simple as it seems? Is there something I'm missing? Any tips are appreciated, as this is actually a really heavily weighted assignment.

Code:
CODE

import java.util.*;
public class KnightsTourMain
{
        
        int board[][]= new int [8][8];//Initializing the board to a 2d 8 b 8 array
        int horizontal[] = {2,1,-1,-2,-2,-1,1,2}; //declaring the horizontal moves the knight can do
        int vertical[] = {-1,-2,-2,-1,1,2,2,1}; //declaring the vertical moves the knight can do
        int currentRow = 4; //current starting Row for the knight
        int currentColumn = 4;//current staring column for the knight
        int moves = 0; //initializing the number of moves
        
        public void move(int moveNumber)//checks whether the moveNumber is a valid on the board move
        {                               //then will move providing that there hasn't been a move there already  
            Scanner in = new Scanner(System.in);
            while ((validrow(moveNumber)==false) || (validColumn(moveNumber)==false))
            {
                System.out.println("That move would take you off the board, enter another move number between 1 and 8");
                moveNumber = in.nextInt()-1;
            }//end while
            if((validrow(moveNumber)==true) &&(validColumn(moveNumber)==true))
            {
                currentRow +=vertical[moveNumber];
                currentColumn+=horizontal[moveNumber];
                moves++;
                board[currentRow][currentColumn]= moves;
                System.out.println("Current number of moves is :"+moves);
                output();
            }
            
        }//end move
        public boolean anyvalidmoves()//checks whether there are any available moves
        {
            for (int i =0;i<8;i++)
            {
                while (((validrow(i)==false) ||(validColumn(i)==false))&&(i<7))
                {
                    i++;
                }//end while
                
                if(board[currentRow+vertical[i]][currentColumn+horizontal[i]]==0);
                    return true;
            }//end for
            return false;
        }//end any valid moves
        public boolean validrow(int moveNumber)//checks if the move will be a row that is on the board
        {
            if((currentRow+vertical[moveNumber] < 0)||(currentRow+vertical[moveNumber] >7))
                return false;
            else
                return true;
        }//end valid row
        public boolean validColumn(int moveNumber)//checks whether the move will be to a column
        {                                           //that is on the board
            if((currentColumn+horizontal[moveNumber] < 0)||(currentColumn+horizontal[moveNumber] > 7))
                return false;
            else
                return true;
        }//end validColumn
        public void output()//outputs the chess board
        {
            for (int i =0;i<board.length;i++)
            {
                for (int j =0;j<board[i].length;j++)
                {
                    System.out.printf("%d ",board[i][j]);
                }//end inner for
                System.out.println();
            }//end outer for
        }//end method output
        
        
        public void input()//while there are any valid moves this will ask you to move
        {
            while(anyvalidmoves()==true)
            {
                Scanner in = new Scanner(System.in);
                System.out.println("Enter a move between 1 and 8");
                int m = in.nextInt()-1;
                move(m);
            }//end while
          
          
          
            if(moves <64)
            {
                System.out.println("There are no valid moves left");
                System.out.println("Youre knights tour lasted "+moves);
                output();
            }
            else
            {
                System.out.println("You managed a full knights tour well done!!");
                output();
            }
            System.exit(0);
            
            
            
        }//end method in out
        public static void main(String[]args)
        {
            KnightsTourMain k = new KnightsTourMain();
            k.input();
            
        }//end main
        
        
        
    }//end KnightsTour



User is offlineProfile CardPM
+Quote Post

KYA
RE: Quick Program Question:
5 Feb, 2008 - 11:46 PM
Post #2

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 5,933



Thanked: 159 times
Dream Kudos: 1375
My Contributions
Have you run this current code and have had the expected outcome?

--KYA
User is offlineProfile CardPM
+Quote Post

needhelpbadly
RE: Quick Program Question:
6 Feb, 2008 - 08:10 AM
Post #3

New D.I.C Head
*

Joined: 5 Feb, 2008
Posts: 13

QUOTE(KYA @ 6 Feb, 2008 - 12:46 AM) *

Have you run this current code and have had the expected outcome?

--KYA



to answer your question, yes - the code DOES work when compiled and run.


But I no longer want the code to have user input, I want it to be more streamlined - completely autonomous
User is offlineProfile CardPM
+Quote Post

DillonSalsman
RE: Quick Program Question:
6 Feb, 2008 - 09:09 AM
Post #4

D.I.C Head
Group Icon

Joined: 30 Oct, 2007
Posts: 72


Dream Kudos: 50
My Contributions
Hmm I think you need to generate a random number from 0-7, plug it into your 2 move arrays (horizontal, and vertical)with something along the lines of:
CODE

int thisMoveX = horizontal[randomNumber];
int thisMoveY = vertical[randomNumber];

Now, what if this move is invalid?
CODE

while(moveValid == false)
{
       //however  you generate your random number
       int thisMoveX = horizontal[randomNumber];
       int thisMoveY = vertical[randomNumber];
       //call your method of checking if move is valid
       //set moveValid == true if it is valid
}

User is offlineProfile CardPM
+Quote Post

baavgai
RE: Quick Program Question:
6 Feb, 2008 - 09:13 AM
Post #5

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,289



Thanked: 136 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua, Cheese

My Contributions
If your move method was set up for it, your answer would be as simple as
CODE

public void inputRandom() {
    java.util.Random rnd = new java.util.Random();
    
    while(anyvalidmoves()) {
        move(rnd.nextInt(8) );
    }
}


Unfortunately, the move method also accepts user input. I'd make the move method return a boolean, indicating success or not. While not successful and still moves remaining, loop.

It's not the most elegant menthod. Ideally, you'd wouldn't ask for the same random move in a set. There are numer of ways to attack it, but that should be the first iteration for just getting it working.

Hope this helps.

EDIT: removed a "+1", twas wrong.

This post has been edited by baavgai: 6 Feb, 2008 - 10:49 AM
User is online!Profile CardPM
+Quote Post

needhelpbadly
RE: Quick Program Question:
6 Feb, 2008 - 01:24 PM
Post #6

New D.I.C Head
*

Joined: 5 Feb, 2008
Posts: 13

I did what you said, Baavgai, at least I hope. I removed the input method and created the random method.

I had to remove the input line from Main, and now the program compiles but doesn't run. Where did I lose track? Its getting too complicated to remember what I'm trying to do sad.gif

Am I missing something in Main? How do I get the program to start at 0,0, or say, another coordinate of my choose?
** Edit, I have variables for starting coordinates. to start at 0,0 , these should say currentRow = 0; and currentColumn = 0;**
I also only want it to print out when its all finished now, not every time a move happens. How do I do that?

Thank you so much, this is due Friday and sadly I'm still not ready. Thank you again so much.

This is my new code: You will notice it is a new filename/project name now because I didnt want to edit the original, working code.

CODE
import java.util.*;
public class KTAuto
{
        
        int board[][]= new int [8][8];//Initializing the board to a 2d 8 b 8 array
        int horizontal[] = {2,1,-1,-2,-2,-1,1,2}; //declaring the horizontal moves the knight can do
        int vertical[] = {-1,-2,-2,-1,1,2,2,1}; //declaring the vertical moves the knight can do
        int currentRow = 4; //current starting Row for the knight
        int currentColumn = 4;//current staring column for the knight
        int moves = 0; //initializing the number of moves
        
        public void inputRandom()
        {
            java.util.Random rnd = new java.util.Random();
            
            while(anyvalidmoves())
            {
                move(rnd.nextInt(8) );
            }
            if(moves <64)
            {
                System.out.println("There are no valid moves left");
                System.out.println("Youre knights tour lasted "+moves);
                output();
            }
            else
            {
                System.out.println("You managed a full knights tour well done!!");
                output();
            }
            System.exit(0);
        }
        
        
        public void move(int moveNumber)//checks whether the moveNumber is a valid on the board move
        {                               //then will move providing that there hasn't been a move there already  
            Scanner in = new Scanner(System.in);
            while ((validrow(moveNumber)==false) || (validColumn(moveNumber)==false))
            {
                System.out.println("That move would take you off the board, enter another move number between 1 and 8");
                moveNumber = in.nextInt()-1;
            }//end while
            if((validrow(moveNumber)==true) &&(validColumn(moveNumber)==true))
            {
                currentRow +=vertical[moveNumber];
                currentColumn+=horizontal[moveNumber];
                moves++;
                board[currentRow][currentColumn]= moves;
                System.out.println("Current number of moves is :"+moves);
                output();
            }
            
        }//end move
        public boolean anyvalidmoves()//checks whether there are any available moves
        {
            for (int i =0;i<8;i++)
            {
                while (((validrow(i)==false) ||(validColumn(i)==false))&&(i<7))
                {
                    i++;
                }//end while
                
                if(board[currentRow+vertical[i]][currentColumn+horizontal[i]]==0);
                    return true;
            }//end for
            return false;
        }//end any valid moves
        public boolean validrow(int moveNumber)//checks if the move will be a row that is on the board
        {
            if((currentRow+vertical[moveNumber] < 0)||(currentRow+vertical[moveNumber] >7))
                return false;
            else
                return true;
        }//end valid row
        public boolean validColumn(int moveNumber)//checks whether the move will be to a column
        {                                           //that is on the board
            if((currentColumn+horizontal[moveNumber] < 0)||(currentColumn+horizontal[moveNumber] > 7))
                return false;
            else
                return true;
        }//end validColumn
        public void output()//outputs the chess board
        {
            for (int i =0;i<board.length;i++)
            {
                for (int j =0;j<board[i].length;j++)
                {
                    System.out.printf("%d ",board[i][j]);
                }//end inner for
                System.out.println();
            }//end outer for
        }//end method output
        
      
        public static void main(String[]args)
        {
            
            
        }//end main
        
        
        
    }


This post has been edited by needhelpbadly: 6 Feb, 2008 - 01:25 PM
User is offlineProfile CardPM
+Quote Post

needhelpbadly
RE: Quick Program Question:
6 Feb, 2008 - 01:36 PM
Post #7

New D.I.C Head
*

Joined: 5 Feb, 2008
Posts: 13

I'd like to follow up by stating that I put a simple

System.out.Println("abc");

in my new random move method, and no text gets printed to the screen. That means somewhere in my program, it is getting "short-circuited", possible because I dont have any starting function calls in Main?


Please help, im completely lost now ;p
User is offlineProfile CardPM
+Quote Post

KYA
RE: Quick Program Question:
6 Feb, 2008 - 04:34 PM
Post #8

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 5,933



Thanked: 159 times
Dream Kudos: 1375
My Contributions
QUOTE(needhelpbadly @ 6 Feb, 2008 - 03:36 PM) *

I'd like to follow up by stating that I put a simple

System.out.Println("abc");

in my new random move method, and no text gets printed to the screen. That means somewhere in my program, it is getting "short-circuited", possible because I dont have any starting function calls in Main?


Please help, im completely lost now ;p

Nothing is being printed to the screen in that case becasue there is literally nothing in your main() function.

--KYA
User is offlineProfile CardPM
+Quote Post

baavgai
RE: Quick Program Question:
6 Feb, 2008 - 04:56 PM
Post #9

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,289



Thanked: 136 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua, Cheese

My Contributions
You're still asking for user input moveNumber = in.nextInt()-1;.

Also, your main is empty. It should look something like this?
CODE

public static void main(String[]args) {
    KTAuto pgm = new KTAuto();
    pgm.inputRandom();
}


You have all the code. This should just be an exercise in refactoring.

User is online!Profile CardPM
+Quote Post

needhelpbadly
RE: Quick Program Question:
6 Feb, 2008 - 08:12 PM
Post #10

New D.I.C Head
*

Joined: 5 Feb, 2008
Posts: 13

Thanks so much for the help. I spent 10 minutes re-vamping the code and all the random inputs are working now. I made the variables clearer so the code is easier to read.


One problem I'm having now is that the program seems to not want to pass move # 29.

From any starting position, the program stops at 29. The error must reside in one of my loops somewhere but I cant find it. I'm desperate, can someone help me with this?

I tried using <7, <6, <5 etc on the loops, but thats a no go. Please hint the answer, or tell me outright. My due date is getting closer. Thank you so much Baavgai, and everyone else.

Heres my new code:
CODE

public class KnightsTour
{
    int grid[][];
    boolean finished;
    final int Xcord[] = {-1, 1, -1, 1, -2, 2, -2, 2};
    final int Ycord[] = {-2, 2, 2, -2, -1, 1, 1, -1};

    public static void main(String args[])
    {
        int totMoves = 1;
        KnightsTour kt = new KnightsTour();
        kt.check( 0, 0, totMoves);
        kt.drawGrid();
    }
    
    public KnightsTour()
    {
        grid = new int[8][8];
        finished = false;
        grid[0][0] = 1;
    }
    
    public int check(int x, int y, int totMoves)
    {
        System.out.println("Printed from check outside loop()");
        for(int i = 0; i < 8; i++)
        {
            if(finished == true)
            {
                return totMoves;
            }
            else
            {
                if(x+Xcord[i]<8 && x+Xcord[i]>=0)
                {
                    if(y+Ycord[i]<8 && y+Ycord[i]>=0)
                    {                
                        //on the grid
                        if((grid[x+Xcord[i]][y+Ycord[i]])==0)
                        {
                            grid[x+Xcord[i]][y+Ycord[i]]=-1;
                            grid[x+Xcord[i]][y+Ycord[i]]=check(x+Xcord[i],y+Ycord[i], totMoves + 1);
                            finished = true;
                            
                        }
                    }
                        
                }
            }
            
            
        }
        if(totMoves >= 64 || finished == true)
        {
            finished = true;
            return totMoves;
        }
        else
        {
            return 0;
        }
        
        
    }
    
    public void drawGrid()
    {
        System.out.println("Drawing grid");
        //Draw grid
        for(int i = 0; i < 8; i++)
        {
            System.out.println("\n________________________");
            for(int j = 0; j < 8; j++)
            {
                if(grid[j][i] < 10)
                {
                    System.out.print("|0" + grid[j][i]);
                }
                else
                {
                    System.out.print("|" + grid[j][i]);
                }
            }
        }
    }

}

User is offlineProfile CardPM
+Quote Post

baavgai
RE: Quick Program Question:
7 Feb, 2008 - 05:31 AM
Post #11

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,289



Thanked: 136 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua, Cheese

My Contributions
This is setup completely differently from the one before. You have no random. You're now using recursion.

It looks like it's a solver, but it's fundamentally flawed in many ways. Event the draw grid is different, you used printf before and now it's like you forgot printf.

Um, are you just grabbing code from other people?

User is online!Profile CardPM
+Quote Post

needhelpbadly
RE: Quick Program Question:
7 Feb, 2008 - 07:09 AM
Post #12

New D.I.C Head
*

Joined: 5 Feb, 2008
Posts: 13

I didn't realize I had to use recursion. I met with my professor to get some help.

I just honestly dont know whats wrong with this code now. I dont think i'm going to get anywhere with this project. I put test Print line statements in all the methods. It appears as tho the first and second if statement run 20-30 times before finally going into the 3rd if statement ( the main one ).


I'm completely lost and I'm going to give up.

I dont even know if the Knight's move table is set up correctly, because I did infact copy that from someone else.
User is offlineProfile CardPM
+Quote Post

2 Pages V  1 2 >
Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 01:08PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter