Java Randomize - (minus) and + (plus)

Is there a way to randomize the plus or minus symbol? I have a program where a sprite moves across the screen and when you click it, it appears again in a different location. I also want the direction it was moving in to be randomized as well. At the moment I can only set it to left or right + or right to left -.

private int x = random.nextInt(150); 
    private int y = random.nextInt(500);    
    private int xSpeed = random.nextInt(10);//Horizontal increment of position (speed)
    private int ySpeed = random.nextInt(10);// Vertical increment of position (speed)

public void update() {
        x = x +- xSpeed;
        y = y +- ySpeed;
}

      

+3


source to share


6 answers


You can always make an option:



xSpeed = xSpeed * ( random.nextBoolean() ? 1 : -1 );
ySpeed = ySpeed * ( random.nextBoolean() ? 1 : -1 );

      

+4


source


a - b

also a + b * (-1)

, so you can randomize -1 or 1 and multiply it by xSpeed ​​/ ySpeed.



+1


source


Please note that there are two possibilities: plus or minus. So just create a random number with two possible results and use that to determine the sign (plus or minus):

public int getRandomSign() {
    Random rand = new Random();
    if(rand.nextBoolean())
        return -1;
    else
        return 1;
}

public void update() {
    x = x + xSpeed * getRandomSign();
    y = y + ySpeed * getRandomSign();
}

      

+1


source


replace xSpeed = random.nextInt(10)

withxSpeed = random.nextInt(19)-9

+1


source


Many have suggested multiplying the speed by 1 or -1, but there is an easier way to avoid the multiplication, which may be slightly more efficient. Probably not enough to make a noticeable difference in performance, but I thought I'd throw it away anyway.

public void update() {
    x = x + (random.nextBoolean() ? xSpeed : -xSpeed);
    y = y + (random.nextBoolean() ? ySpeed : -ySpeed);
}

      

+1


source


In the other answers, you have the correct solutions for randomly choosing between two values. I suggest you choose any of the values:

private static Random rd = new Random();
public static <T> T randomItem(List<T> elts) {
    return elts.get(rd.nextInt(elts.size());
}

      

-1


source







All Articles