随机数 - 增加/减少1

时间:2013-11-06 08:54:43

标签: java random sequential

我正在研究一种方法,该方法在3-3之间采取步骤。我的程序不会按照数字顺序打印出步骤,我不知道该怎么做,我在其他地方找不到任何东西。

public static final int SENTINEL = Math.abs(3); 
public static void randomWalk(Random rand) {
    int walk = 0;
    while (walk != SENTINEL) {
        walk = (rand.nextInt((3 - (-3)) + 1) - 3);
        System.out.println("Position = " + walk);
    }
}

4 个答案:

答案 0 :(得分:1)

如果您正在寻找:

int walk = 0;
int randomStep = 0;
Random rand = new Random();
while (Math.abs(walk) != 3) {
    randomStep = rand.nextInt(2) > 0 ? 1 : -1; // -1 or 1 with 50% probability
    walk += randomStep;
    System.out.print(walk + " ");
}
//sample output: -1 -2 -1 0 1 2 1 2 3

答案 1 :(得分:0)

public static void randomWalk(Random rand) {
  int walk = 0;
  while (walk != SENTINEL) {
     walk += rand.nextInt(3) - 1;
     if(walk>3) walk = 3;
     if(walk<-3) walk = -3;
     System.out.println("Position = " + walk);
     }
}

答案 2 :(得分:0)

我想你想要这个。

while (walk != SENTINEL) {
                int walk = 0;
                walk = (rand.nextInt((3 - (-3)) + 1) - 3);
                System.out.println("Walk is  = " + walk);
                int temp = walk;

                if (walk >= -3) {
                    System.out.println("Wlak plus = " + (temp + 1));
                    System.out.println("Wlak minus =" + (temp - 1));

                }

            }

答案 3 :(得分:0)

这可能是你想要的吗? package com.stackoverflow.random;

import java.util.Random;

public class Walking {

    private final int bounds;
    public Walking(int bounds) {
        this.bounds = bounds;
    }

    private boolean isWithinBounds(int walk) {
        return Math.abs(walk) < bounds;
    }
    public String randomWalk() {
        int walk = 0;
        StringBuilder sb = new StringBuilder();
        while(isWithinBounds(walk)) {
            sb.append(walk);
            walk = getNextStep(walk);
        }
        return sb.toString();
    }

    private Random random = null;
    private int getNextStep(int walk) {
        if (random == null)
            random = new Random();
        boolean increase = random.nextBoolean();
        return increase?++walk:--walk;
    }


    public static void main(String[] args) {
        Walking app = new Walking(3);
        System.out.println("walking: " + app.randomWalk());
    }
}
相关问题