The most efficient way to change int in X and Y direction

I have a set of key codes with values ​​(of course, 4), from 0 to 3, corresponding to the keys down, left, up, right, in that order. I need to convert these key codes in x and y directions, with a positive x indicating the location to the left of the origin, and a positive y indicating the location below the origin. As I see it, I have two ways to do this:

using arrays:

int [] dx = {0, -1, 0, 1};
int [] dy = {1, 0, -1, 0};
int x = dx[kc];
int y = dy[kc];

or using arithmetic:

int x = (kc%2)*(((kc/2)%2)*2 - 1);
int y = ((kc+1)%2)*(((kc/2)%2)*-2 + 1);

which would be more efficient?

+4
source share
4 answers

, . , . , , . 4 . ints 4 , 8- ! , , , -, .

(getDirection(), setDirection() ..), .

: woops, , . .

+1

, -. :

private static final int[][] directions = {
    {0, 1},
    {-1, 0},
    {0, -1},
    {1, 0}
};

:

x = directions[kc][0];
y = directions[kc][1];
+1

, , , . , . , , .

, , . - Google.

-, , ( ) (x &= 0xfffffffe , x%=2, , x int). 2 ( x < 1 x * 2).

+1
source

Here's another way to do the conversion.

package com.ggl.testing;

import java.awt.Point;

public class Convert {

    public Point convertDirection(int index) {
        // 0 to 3 corresponds to the keys down, left, up, right
        Point[] directions = { new Point(0, 1), new Point(-1, 0),
                new Point(0, -1), new Point(1, 0) };
        return directions[index];
    }

}
0
source

All Articles