2 Replies - 7852 Views - Last Post: 29 July 2012 - 11:05 AM Rate Topic: -----

#1 ahmehmood  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 29-July 12

Random Walk java problem

Posted 29 July 2012 - 08:25 AM

I was working on a programming problem
that takes an integer N and simulates the motion of a random walker
for N steps. After each step, I am required to print the location of
the random walker, treating the origin position as(0,0).
Finally it asks to print the square of the distance from origin to the final point.

Although I have worked a little on this java problem. I cant seem to figure out
a method to print its location /final position after N step.
My code is here:

public class math { 
    public static void main(String[] args) {
      int N= Integer.parseInt(args[0]);
      int M=Integer.parseInt(agrs[1]);
     
              
        for (int t = 0; t < N; t++) {

            int x = 0, y = 0;   
            int[]a= new int[x][y];

            // repeatedly take a random step, unless you've already escaped
            while (x >= -M && x <= M && y >=  M && y <= M)  {

                double r = Math.random(); 
                if      (r < 0.25) 
                  x++;
                else if (r < 0.50) 
                  x--;
                else if (r < 0.75) 
                  y++;
                else if (r < 1.00) 
                  y--;
                a[x][y]= true;




I would be extremely extremely grateful of your help. Please note this is not a homework asssignment.
This problem is from a book that I am using to learn java over summers. Thanks

Kind Regards,
Ahsan

*** Edit ***
Please use code tags when posting code.
Posted Image

This post has been edited by GunnerInc: 29 July 2012 - 08:50 AM
Reason for edit:: Added code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Random Walk java problem

#2 GunnerInc  Icon User is online

  • "Hurry up and wait"
  • member icon




Reputation: 858
  • View blog
  • Posts: 2,281
  • Joined: 28-March 11

Re: Random Walk java problem

Posted 29 July 2012 - 08:49 AM

Moved to Java

and please use code tags when posting code.
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Random Walk java problem

Posted 29 July 2012 - 11:05 AM

 // what is the use of doing this N times
 for (int t = 0; t < N; t++) {  
             // if you reset x and y each time
             int x = 0, y = 0;     
             int[]a= new int[x][y]; 



this is invalid

int[]a= new int[x][y];

if you want a 2 dimension array you need

int[][]a= new int[x][y];

but as x and y == 0 you simply created an array[0][0] kind of useless

and
a[x][y]= true;
you can't store a boolean into a int
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1