I am new to java and I am trying to optimize my code as far as possible.
I want to know what is the most efficient way for the machine to convert a number, lets say int or char, to a boolean.
I am implementing TicTacToe in java. I am using bitmaps to represent the state of the game. I am aware of the unreadability, but I don't want to optimize that. Code efficient < machine efficient.
import java.util.Scanner;
public class TicTacToe {
boolean swap = false;
char player1 = 0b000000000;
char player2 = 0b000000000;
static char[] winconditions = new char[]{0b111000000, 0b000111000, 0b000000111, 0b100100100, 0b010010010, 0b001001001, 0b100010001, 0b001010100};
Scanner scanner = new Scanner(System.in);
boolean evaluateWinner() {
char current = swap ? player2 : player1;
for (char condition : winconditions)
if ((condition == (current & condition))) return true;
return false;
}
int getInput() {
int field = player1 | player2;
while (true) {
System.out.println("Give Input: 0 1 ... 8 ");
int out = 1 << scanner.nextInt();
if ((out & field) == 0) return out;
}
}
public void start() {
do {
draw();
if (swap) player2 |= getInput();
else player1 |= getInput();
swap = !swap;
} while (evaluateWinner());
}
void draw() {
for (int i = 0; i < 9; i++) {
boolean isP1 = (player1 & 1 << i) != 0;
boolean isAny = (player2 & 1 << i) != 0 || isP1;
String out = isAny ? (is1 ? "X" : "O") : String.valueOf(i);
if (i % 3 == 2) out += "|\n";
System.out.print("|" + out);
}
}
}
Call var game = new TicTacToe(); game.start();
to run the game.
In TicTacToe.draw
I need to determine if a specific bit is set to 1 or 0. With a few bitwise operations I am getting a number. In C I wouldn't have to convert the number to boolean.
But in Java I have to. What is the most efficient way to do that?
- n != 0
boolean isP1 = (player1 & 1 << i) != 0;
boolean isAny = (player2 & 1 << i) != 0 || isP1;
- (boolean) n
boolean isP1 = (boolean) (player1 & 1 << i) ;
boolean isAny = ((boolean)(player2 & 1 << i))|| isP1;
Is it the same or are there more efficient ways to do convert numbers to a boolean?
If you have more ideas how to optimize the code in cpu runtime and in memory usage. Let me know. I don't think there is much more I can do. But proof me wrong if you want.
Kind reagards : )