# Random Walk java problem

Page 1 of 1

## 2 Replies - 21580 Views - Last Post: 29 July 2012 - 11:05 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=287336&amp;s=63cf02ccee0853ef5c8a3688027b3a8d&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 ahmehmood

Reputation: 0
• 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.

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

• "Hurry up and wait"

Reputation: 917
• Posts: 2,358
• 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.

### #3 pbl

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

Reputation: 8378
• Posts: 31,956
• 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