Choose between 2 defined numbers randomly - java

So I have this piece of code
if (x >= gameView.getWidth()) { //if gone of the right side of screen
x = x - gameView.getWidth(); //Reset x
y = random.nextInt(gameView.getHeight());
xSpeed =
ySpeed =
}
but I need to get both xSpeed and ySpeed to choose between two values, either '10' or '-10' and only those two numbers, nothing in between.
Everywhere I've looked says use the random.nextInt but that also chooses from the numbers in between -10 and 10...

You may try using
xSpeed = (random.nextInt() % 2 == 0) ? 10 : -10;
ySpeed = (random.nextInt() % 2 == 0) ? 10 : -10;
Good luck

How about this:
if(random.nextBoolean()){
xSpeed = 10;
}
else xSpeed = -10;

What about this? Math.random() returns values between 0.0 (include) and 1.0 (exclude).
public class RandomTest {
public static void main(String[] args) {
int xSpeed = 0;
int ySpeed = 0;
if (Math.random() >= 0.5) {
xSpeed = -10;
} else {
xSpeed = 10;
}
if (Math.random() >= 0.5) {
ySpeed = -10;
} else {
ySpeed = 10;
}
}
}

Lets suppose your random.nextInt(gameView.getHeight()); distributes evenly between even and odd numbers, then you could write something like this:
y = random.nextInt(gameView.getHeight()) % 2 == 0 ? 10 : -10;

Related

Shortening many if statements in a while loop in Java

How can I shorten many subtractions of the exact same nature in a while loop in Java? I feel like it's very redundant and there can definitely be a shorter way.
while (x != 0) {
if (x - 100 >= 0) {
x -= 100;
}
if (x - 50 >= 0) {
x -= 50;
}
if (x - 25 >= 0) {
x -= 25;
}
...
First of all, you don't need to subtract and compare to zero, instead just compare to the number you are subtracting.
while (x != 0) {
if (x >= 100) {
x -= 100;
}
if (x >= 50) {
x -= 50;
}
if (x >= 25) {
x -= 25;
}
...
Secondly, what you're asking is a case by case problem. You could shorten the code above like this:
int[] nums = {100, 50, 25};
while (x != 0) {
for (int num : nums) {
if (x >= num) {
x -= num;
}
}
}

How do you search around any index in a 2D array?

So I'm making a program that takes in a 2D array of 5x5, and lists all the characters around any given index of the array. For example, if I input list[1][1], it will give the indexes: [0][0], [0][1], [0][2], [1][0], [1][2], [2][0], [2][1] ,[2][2].
I can print out all the letters around the indexes except for the ones on the edges such as index [0][0]. I can't seem to figure out how to get past that.
private static void checkSurrounding(char[][] list, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
for(int dy = -1; dy <= 1; dy++) {
if(!(dx == 0 && dy == 0)) {
System.out.print(list[x + dx][y + dy]);
}
}
}
}
Your code is almost correct! You exclude the middle point here:
private static void checkSurrounding(char[][] list, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
for(int dy = -1; dy <= 1; dy++) {
if(!(dx == 0 && dy == 0)) {
System.out.print(list[x + dx][y + dy]);
}
}
}
}
The only thing you miss is to avoid getting out of bounds. Just make sure that you do not get out of bounds and it should work impeccably:
private static void checkSurrounding(char[][] list, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
if ((x + dx >= 0) && (x + dx < list.length)) {
for(int dy = -1; dy <= 1; dy++) {
if ((y + dy >= 0) && (y + yd < list[x + dx].length) && (!(dx == 0 && dy == 0))) {
System.out.print(list[x + dx][y + dy]);
}
}
}
}
}

Largest prime factor

I have a little problem with my java code! The question is: The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My code somehow doesn't work!! What's wrong? Thanks for your help!
public class Example_1 {
public static void main (String[] args){
{
System.out.println(largestPrimeFactor(600851475143));
}
}
private static long largestPrimeFactor(long number) {
long result = 0;
for(long x = 2;x<number;x++){
if(number % x == 0){
for( long y = 2; y < x ; y++ ){
if( x % y == 0){
break;
}
else{
result = x;
}
}
}
}
return result;
}
}
for( long y = 2; y < x ; y++ ){
if( x % y == 0){
break;
}
else{
result = x;
}
}
Here you are trying to test whether x is prime. However, if you follow this loop logic through, you will see that it translates to the following:
If any y is found not to be a factor of x before it is discovered whether or not x is prime, then x is prime.
Refactor the else to outside the loop.
boolean xIsPrime = true;
for( long y = 2; y < x ; y++ ){
if( x % y == 0){
xIsPrime = false;
break;
}
}
if( xIsPrime ){
result = x;
}
Compilation problems:
The method largestPrimeFactor appears to be outside of a class.
The constant 600851475143 is too large for an int. Postfix with L: 600851475143L.
Note that the algorithm you've written is suboptimal and that is why it may run for a long time when given large inputs.
public class Example_1 {
public static void main (String[] args){
System.out.println(largestPrimeFactor(600851475143L));
}
private static long largestPrimeFactor(long number) {
long result = 0;
if (number % 2 == 0){
result = 2;
while (number % 2 == 0)
number /= 2;
}
for(long x = 3; number > 1; x += 2)
if (number % x == 0){
result = x;
while (number % x == 0)
number /= x;
}
return result;
}
}

Most efficient method of performing &&?

I've got a common situation where you have two variables (xSpeed and ySpeed) which I want to independently set to zero when they fall below minSpeed, and exit when they're both zero.
What would be the most efficient method? Currently I have two methods (Method 2 being cleaner), but I was wondering if you guys knew a better way....
Method1:
bool isZeroX = Math.abs(xSpeed)< minSpeed;
bool isZeroY = Math.abs(ySpeed)< minSpeed;
if(isZeroX && isZeroY) return -1;
else if(isZeroX) xSpeed = 0;
else if(isZeroY) ySpeed = 0;
Method2:
if(Math.abs(xSpeed)< minSpeed) xSpeed = 0;
if(Math.abs(ySpeed)< minSpeed) ySpeed = 0;
if(ySpeed==0 && xSpeed==0) return -1;
I prefer your second example because it is the most readable. Prefer readability over efficiency unless you can prove that you should be optimising.
You can do
if(-minSpread < xSpeed && xSpeed < minSpeed) {
xSpeed = 0;
if(-minSpread < ySpeed && ySpeed < minSpeed) {
ySpeed = 0;
return -1;
}
} else if(-minSpread < ySpeed && ySpeed < minSpeed) {
ySpeed = 0;
}
Perhaps make an elegant boolean method to see if the object is moving/stopped:
boolean isStopped() {
if(Math.abs(xSpeed)< minSpeed) xSpeed = 0;
if(Math.abs(ySpeed)< minSpeed) ySpeed = 0;
return (ySpeed==0 && xSpeed==0);
}

Java creation of a spiral [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Looping in a spiral
I'm creating a program to populate a 3 by 3 matrix. I want to result in something looking like this
5 4 3
6 1 2
7 8 9
As you have probably noticed it is a spiral.
Now the algorithm I'm using is this: I have a 2-d array where the values represent the coordinates of the number. First I assign that every number coordinate in this array will have a value of 10. Then starting at 9 I decrease my x coordinate and assign the value of the coordinate to currentnum - 1 until it reaches the end or its value is not 10; Then I do the same thing except I increase the value of Y; Then decrease the value of x; Then of Y;
The reason I assign 10 to every number is so like it acts as a road for my program. Since current num will never exceed 9. If the value of a square is 10 it is like a green light. If it is not 10 meaning a value has been assigned to that square it breaks out of it.
Here is my code, please note it is written in Java
public class spiral {
/**
* #param args
*/
public static void main(String[] args) {
int spiral [] [] = new int[3][3];
for(int i = 0; i <= 2; i++){
for(int j = 0; j <= 2; j++){
spiral[i][j] = 10;
}
}
//0 is x value, 1 is y value
spiral[0][0] = 9;
int x = 1;
int y = 1;
int counter = 1;
int currentnum = 9;
int gridsquare = 3;
for(int i = 0; i <= 8; i++){
if(counter == 5){
counter = 1;
}
if(counter == 1){
System.out.println(x + " " + y);
for(int j = 0;j <= 1;j++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
x += 1;
}
else{
y += 1;
break;
}
}
}
if(counter == 2){
for(int k = 0; k <= 0; k++){
System.out.print(x + " " + y);
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
y += 1;
}
else{
x -= 1;
break;
}
}
}
if(counter == 3){
for(int z = 0; z <= 0; z++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
x -= 1;
}
else{
y -= 1;
break;
}
}
}
if(counter == 4){
for(int b = 0; b <= 0; b++){
if(spiral[x][y] == 10){
spiral[x][y] = currentnum;
currentnum--;
y -= 1;
}
else{
x += 1;
break;
}
}
}
counter++;
}
System.out.print(currentnum);
}
}
I'm getting this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at spiral.main(spiral.java:44)
Since I'm new to Java would someone please suggest a posible fix for this. Also if you see any problems with my algorithm please do inform me.
You do not need to pre-fill with 10: zero works just as well.
I think the best approach to solving the spiral is to think of how you do it manually: start in a corner, and go horizontally until you hit non-zero or an edge of the array. Then you turn right. Stop when the current number goes past N*N.
Now let's look at what each part of the algorithm means:
Starting in the corner means setting x=0 and y=0.
Going in a straight line means x=x+dx, y=y+dy, where either dx or dy is zero, and dy or dx is 1 or -1.
Turning right means assigning dx to dy and -dy to dx.
Here is how it looks in the code:
int current = 1;
// Start in the corner
int x = 0, y = 0, dx = 1, dy = 0;
while (current <= N*N) {
// Go in a straight line
spiral[x][y] = current++;
int nx = x + dx, ny = y + dy;
// When you hit the edge...
if (nx < 0 || nx == N || ny < 0 || ny == N || spiral[nx][ny] != 0) {
// ...turn right
int t = dy;
dy = dx;
dx = -t;
}
x += dx;
y += dy;
}
You've incremented x or y to 3 which is past the end of one of your arrays.
Step through your program with the debugger or add System.out.println statements before each if (counter) to find out where you're doing this.

Categories