Sunday, January 22, 2017

TicTacToe AI with Minimax Algorithm

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class TicTacToeMinimax extends TicTacToeAI {
    public int []nextMove(int token) {
        int enemy = inverse(token);
        if(isWin(enemy)) return new int[]{-1,-1,-1};
        int []ret = null;
        int best = -2;
        for(int i=0;i<3;i++) for(int j=0;j<3;j++) {
            if(getBoardValue(i, j)==EMPTY) {
                setBoardValue(i,j,token);
                int []res = nextMove(enemy);
                int score = res==null ? 0 : -res[2];
                if(score > best) {
                    best = score;
                    ret = new int[]{i,j,best};
                }
                setBoardValue(i,j,EMPTY);
            }
        }
        return ret;
    }
}

Saturday, August 13, 2016

Online Tic Tac Toe Game With HTML5

Hi, I have created online Tic Tac Toe game using HTML5.
It comes with smart AI but not perfect, so there's a way that you can beat the computer.

Screenshot from the game:


The artificial intelligence logic based on my previous implementation using Java.
I created this using Canvas and some Javascript code. Since Javascript very similiar with Java, it's not hard for me to implement this game using Javascript.
In the future, I will post more games using HTML5.

Please check my another post related Tic Tac Toe game.




Feel free to add your comment and question.

Tuesday, August 9, 2016

Prime Number Program Java

Hi, it's have been long time since my latest post about Luhn Algorithm.
Today, I will show you how to create prime number program with Java.


What is prime number?
A prime number is a whole number greater than 1, whose only two whole-numberfactors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.


How to check if given number X is prime or not?
This method will return true if X is prime and return false if X is not prime.
Time complexity for this algorithm are O( sqrt(X) ).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public boolean isPrime(int x) {
 if(x<2) return false;
 if(x==2 || x==3) return true;
 if(x%2==0 || x%3==0) return false;
 for(int p=6; (p-1) * (p-1) <= x; p += 6) {
  if(x % (p-1) == 0 ) return false;
  if(x % (p+1) == 0 ) return false;
 }
 return true;
}


How to generate prime number between A and B inclusive?
A must be less than or equal B.
Time complexity for this algorithm are O( range * sqrt(range) ), where range = B - A

1
2
3
4
5
6
7
8
9
public List<Integer> genPrimes(int a, int b) {
 List<Integer> primes = new ArrayList<Integer>();
 if(a<= 2) primes.add(2);
 if(a % 2 == 0) a++;
 for(int p=a; p<=b; p+=2) {
  if(isPrime(p)) primes.add(p);
 }
 return primes;
}


If you want faster algorithm, please check my other post:


Feel free to add your question or comment. 
For urgent request please send email to algojava8@gmail.com