minmax not efficient for connect 4 - java

Like many other person as I see, I have a problem with my implementation of the Minmax algorithm for the game Connect4. In the example below, the algorithm doesn't try to block the player two and I don't understand why. My evaluation function is really basic: a binary function. Maybe it's because of the depth, but I don't think so.
Code:
public class Moteur {
public static void addPawn(int[][] game, int column, int player) {
int i = 0;
while (i < 6 && game[i][column] == 0) {
i++;
}
game[(i==6)?5:i-1][column] = player;
}
public static void kickPawn(int[][] game, int column) {
int i = 0;
while (i < 6 && game[i][column] == 0) {
i++;
}
game[i][column] = 0;
}
public static void AI_play(int[][] game, int depth) {
int max = -10000;
int tmp = 0;
int maxj = -5;
int j;
for (j = 0; j < 7; j++) {
if(game[0][j] == 0) {
addPawn(game, j, 1);
tmp = Min(game, depth - 1);
if (tmp > max) {
max = tmp;
maxj = j;
}
kickPawn(game, j);
}
}
addPawn(game, maxj, 1);
}
public static int Max(int[][] game, int depth) {
if(depth == 0 || winner(game) != 0) {
return eval(game);
}
int max = -10000;
int j, tmp;
for(j = 0; j < 7; j++) {
if(game[0][j] == 0) {
addPawn(game, j, 2);
tmp = Min(game, depth - 1);
if(tmp > max) {
max = tmp;
}
kickPawn(game, j);
}
}
return max;
}
public static int Min(int[][] game, int depth) {
if(depth == 0 || winner(game) != 0) {
return eval(game);
}
int min = 10000;
int j, tmp;
for(j = 0; j < 7; j++) {
if(game[0][j] == 0) {
addPawn(game, j, 1);
tmp = Max(game, depth - 1);
if(tmp < min) {
min = tmp;
}
kickPawn(game, j);
}
}
return min;
}
public static int eval(int[][] game) {
int gameWinner, nb_pawns = 0;
for (int i = 0; i < game.length; i++) {
for (int j = 0; j < game[0].length; j++) {
if(game[i][j] != 0) {
nb_pawns++;
}
}
}
gameWinner = winner(game);
if(gameWinner == 1) {
return 1000 - nb_pawns;
} else if (gameWinner == 2) {
return -1000 + nb_pawns;
} else {
return 0;
}
}
public static int winner(int[][] game) {
Integ e = new Integ();
for (int j = 0; j < game[0].length; j++) {
if(game[5][j]!= 0 && testWinner(game, j, e)) {
return e.getI();
}
}
return 0;
}
public static boolean testWinner(int[][] game, int lastColumn, Integ e) {
int lastRow = 0;
while (lastRow < 6 && game[lastRow][lastColumn] == 0) {
lastRow++;
}
lastRow = lastRow;
int i = 0;
int j = 0;
int currentPlayer = game[lastRow][lastColumn];
e.setI(currentPlayer);
int sequence = 0;
i = lastRow;
boolean b = i < 3
&& game[i][lastColumn] == currentPlayer
&& game[i+1][lastColumn] == currentPlayer
&& game[i+2][lastColumn] == currentPlayer
&& game[i+3][lastColumn] == currentPlayer;
if(b) {
return true;
}
sequence = 0;
j = lastColumn;
do {
j--;
} while(0 < j && game[lastRow][j] == currentPlayer);
if(j < 0 || game[lastRow][j] != currentPlayer) {
j++;
}
while(j <= 6 && game[lastRow][j] == currentPlayer) {
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
sequence = 0;
i = lastRow;
j = lastColumn;
do {
i--;
j--;
} while(0 < i && 0 < j && game[i][j] == currentPlayer);
if(i < 0 || j < 0 || game[i][j] != currentPlayer) {
i++;
j++;
}
while(i <= 5 && j <= 6 && game[i][j] == currentPlayer) {
i++;
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
sequence = 0;
i = lastRow;
j = lastColumn;
do {
i++;
j--;
} while(i < 5 && 0 < j && game[i][j] == currentPlayer);
if (5 < i || j < 0 || game[i][j] != currentPlayer) {
i--;
j++;
}
while(0 <= i && j <= 6 && game[i][j] == currentPlayer) {
i--;
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
return false;
}
public static void main(String[] args) {
int[][] game = new int[6][7];
int depth = 5;
game[5][3] = 2;
game[4][3] = 2;
game[3][3] = 2;
AI_play(game, depth);
//game[4][0] = 2;
//AI_play(game, depth);
//game[5][2] = 2;
//AI_play(game, depth);
//game[5][3] = 2;
//AI_play(game, depth);
//game[1][0] = 2;
//AI_play(game, depth);
//game[5][4] = 2;
//AI_play(game, depth);
for (int i = 0; i < game.length; i++) {
for (int j = 0; j < game[0].length; j++) {
System.out.print(game[i][j]);
}
System.out.println("");
}
}
private static class Integ {
private int i;
public Integ() {
this.i = 0;
}
public void increment() {
this.i = this.i + 1;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}
}

Related

Java Code solves 3x3 and 5x5 magic squares but not 4x4 and 6x6

Hey guys new to programming here. I have a project on magic squares and my code can solve 3x3 and 5x5 but not 44 and 6x6 arrays for some reason. To give some info about the project we make a program that should give the user 4 option to solve a magic square (using an arraylist as a stack or as queue, a stack and a linked list as a queue). The code makes copies of the magic square and each of them has a new cell filled with a number according to the check methods and its i,j position. Each copy is created checked and filled if possible in the nextSuccessor() method. if at least a number can fill the cell the copy is returned to the main program to be stored in the data structure the user has chosen in the beginning of the program. If no number could fill the cell the method returns null. The program ends when either all the cells of a copy of a magic square are filled, or if the data structure gets empty.
ps: That first constructor that is in the MagicSquare class is what we were instructed to do so that's why i made the set method.
Here are the two classes:
public class MagicSquare{
int N;
int C;
int[][] magic; // NxN.
int numbers; //counts how many number have been used
boolean[] used; // NxN length
int row, col; //point the cell to be filled
int current_number; // the number that will be checked to fill the magic[row][col]
public MagicSquare(){
N=0;
magic = new int[N][N];
C = N*(N*N + 1)/2;
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
magic[i][j] = 0;
}
}
numbers = 0;
used = new boolean[N*N];
for (int i = 0; i < N*N; i++){
used[i] = false;
}
}
public MagicSquare(MagicSquare obj){
N = obj.N;
C = obj.C;
magic = new int[N][N];
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
magic[i][j] = obj.magic[i][j];
}
}
numbers = obj.numbers;
used = new boolean[N*N];
for (int i = 0; i < N*N; i++){
used[i] = obj.used[i];
}
}
public void setNandValues(int n, int[][] a){
N = n;
C = N*(N*N + 1)/2;
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
magic[i][j] = a[i][j];
if (magic[i][j] != 0) {
used[magic[i][j] -1] = true;
numbers++;
}
}
}
}
public void initialize_successor(){
row = -1;
col = -1;
int i = 0;
while (i < N && row == -1){
int j = 0;
while (j<N && col == -1){
if (magic[i][j] == 0){
this.row = i;
this.col = j;
}
j++;
}
i++;
}
current_number=0;
}
public boolean checkRow(){
int m = 0;
int s = current_number;
int a = 0;
int b = 0;
for (int i = 0; i < N; i++){
if (magic[row][i] == 0){
m++;
}
else s += magic[row][i];
}
m--;
if (m>0){
int i = 0;
int k = 0;
while(i<N && k<m){
if(i != current_number-1 && used[i] == false){
a += i+1;
k += 1;
}
i++;
}
/*while(i > 0){
if (used[k] == false){
a += (k+1);
i--;
if (k == current_number - 1){
a -= (k+1);
i++;
}
}
k++;
}*/
/*i = m;
k = 0;
while(i > 0){
if (used[N*N-k-1] == false){
b += (N*N-k);
i--;
if (k == current_number - 1){
b -= (N*N-k);
i++;
}
}
k++;
} */
i = 0;
k = 0;
while(i<N*N && k<m){
if(i != current_number-1 && used[N*N-i-1] == false){
b += N*N - i;
k += 1;
}
i++;
}
}
return (s+a<=C && s+b>=C);
}
public boolean checkCol(){
int m = 0;
int s = current_number;
int a = 0;
int b = 0;
for (int i = 0; i < N; i++){
if (magic[i][col] == 0){
m++;
}
else s += magic[i][col];
}
m--;
if (m>0){
int i = m;
int k = 0;
/*while(i > 0){
if (used[k] == false){
a += (k+1);
i--;
if (k == current_number - 1){
a -= (k+1);
i++;
}
}
k++;
}*/
while(i<N && k<m){
if(i != current_number-1 && used[i] == false){
a += i+1;
k += 1;
}
i++;
}
/*i = m;
k = 0;
while(i > 0){
if (used[N*N-k-1] == false){
b += (N*N-k);
i--;
if (k == current_number - 1){
b -= (N*N-k);
i++;
}
}
k++;
}*/
i = 0;
k = 0;
while(i<N*N && k<m){
if(i != current_number-1 && used[N*N-i-1] == false){
b += N*N - i;
k += 1;
}
i++;
}
}
return (s+a<=C && s+b>=C);
}
public boolean checkMainDiagonal() {
int m = 0;
int s = current_number;
int a = 0;
int b = 0;
for (int i = 0; i < N; i++){
if (magic[i][i] == 0){
m++;
}
else s += magic[i][i];
}
m--;
if (m>0){
int i = m;
int k = 0;
/*while(i > 0){
if (used[k] == false){
a += (k+1);
i--;
if (k == current_number - 1){
a -= (k+1);
i++;
}
}
k++;
}*/
while(i<N && k<m){
if(i != current_number-1 && used[i] == false){
a += i+1;
k += 1;
}
i++;
}
/*i = m;
k = 0;
while(i > 0){
if (used[N*N-k-1] == false){
b += (N*N-k);
i--;
if (k == current_number - 1){
b -= (N*N-k);
i++;
}
}
k++;
}*/
i = 0;
k = 0;
while(i<N*N && k<m){
if(i != current_number-1 && used[N*N-i-1] == false){
b += N*N - i;
k += 1;
}
i++;
}
}
return (s+a<=C && s+b>=C);
}
public boolean checkSecondaryDiagonal() {
int m = 0;
int s = current_number;
int a = 0;
int b = 0;
for (int i = 0; i < N; i++){
if (magic[i][N-i-1] == 0){
m++;
}
else s += magic[i][N-i-1];
}
m--;
if (m>0){
int i = m;
int k = 0;
/*while(i > 0){
if (used[k] == false){
a += (k+1);
i--;
if (k == current_number - 1){
a -= (k+1);
i++;
}
}
k++;
}*/
while(i<N && k<m){
if(i != current_number-1 && used[i] == false){
a += i+1;
k += 1;
}
i++;
}
/*i = m;
k = 0;
while(i > 0){
if (used[N*N-k-1] == false){
b += (N*N-k);
i--;
if (k == current_number - 1){
b -= (N*N-k);
i++;
}
}
k++;
}*/
i = 0;
k = 0;
while(i<N*N && k<m){
if(i != current_number-1 && used[N*N-i-1] == false){
b += N*N - i;
k += 1;
}
i++;
}
}
return (s+a<=C && s+b>=C);
}
public MagicSquare nextSuccessor(){
MagicSquare m;
while( current_number < N*N){
current_number++;
if( !used[ current_number -1]){
if(((this.row != this.col && this.row != N-this.col -1) && (this.checkRow() && this.checkCol())) ||
(this.row == this.col && this.row != N-this.col -1) && (this.checkRow() && this.checkCol() && this.checkMainDiagonal()) ||
(this.row != this.col && this.row == N-this.col -1) && (this.checkRow() && this.checkCol() && this.checkSecondaryDiagonal()) ||
(this.row == this.col && this.row == N-this.col -1) && (this.checkRow() && this.checkCol() && this.checkMainDiagonal() && this.checkSecondaryDiagonal())){
magic[row][col] = current_number;
used[current_number - 1] = true;
m = new MagicSquare();
m.setNandValues(N, magic);
return m;
}
}
}
return null;
}
/*
public MagicSquare nextSuccessor(){
MagicSquare m;
while( current_number < N*N){
current_number++;
if( !used[ current_number -1] && checkRow() && checkCol()){
magic[row][col] = current_number;
used[current_number - 1] = true;
m = new MagicSquare();
m.setNandValues(N, magic);
return m;
}
}
return null;
}
*/
public void display(){
for (int i =0; i<N; i++){
for(int j = 0; j<N; j++){
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
}
}
/*
public MagicSquare nextSuccessor(){
MagicSquare m;
while( current_number < N*N){
current_number++;
if( !used[ current_number -1] && checkRow() && checkCol()){
magic[row][col] = current_number;
used[current_number - 1] = true;
m = new MagicSquare();
m.setNandValues(N, magic);
return m;
}
}
return null;
}
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
import java.util.LinkedList;
import java.util.ArrayList;
public class MainSolver {
static int[][] pin;
static int N;
static ArrayList<MagicSquare> frontierAL;
static Stack<MagicSquare> frontierST;
static LinkedList<MagicSquare> frontierLL;
//String filename = args[0];
//int option = Integer.parseInt(args[1]);
static String filename = "/Users/panagiotispagonis/Documents/ΠΜΣ/ΠΛΣ 50/Εργασίες ΠΛ50/Εργασία 3/Εργασία 3 (code)/Thema1/p4-01.txt";
static int option;
static void readMagicSquare(String filename){
try {
File obj = new File(filename);
Scanner read = new Scanner(obj);
N = Integer.parseInt(read.nextLine());
pin = new int[N][N];
for(int i = 0; i<N; i++) {
String data = read.nextLine();
String[] row =data.split(" ");
for (int j= 0; j < N; j++){
pin[i][j] = Integer.parseInt(row[j]);
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
static void initialize_search(MagicSquare s, int datastructure) {
switch (datastructure) {
case 1:
case 2:
frontierAL = new ArrayList<MagicSquare>();
frontierAL.add(s);
break;
case 3:
frontierST=new Stack<MagicSquare>();
frontierST.push(s);
break;
case 4:
frontierLL=new LinkedList<MagicSquare>();
frontierLL.add(s);
break;
default:
break;
}
}
// arxikopoiei ti domi pou tha xrisimopoiithei apo to programma se kathe periptosi. auto krinetai apo to poia epilogi patise o xristis (option)
static void search(int datastructure) {
MagicSquare current = null, next;
switch (datastructure) {
case 1:
System.out.println("Search using ArrayList as a Stack");
break;
case 2:
System.out.println("Search using ArrayList as a Queue");
break;
case 3:
System.out.println("Search using Stack as a Stack");
break;
case 4:
System.out.println("Search using LinkedList as a Queue");
break;
default:
break;
}
boolean empty_frontier=false;
while (!empty_frontier) {
if (datastructure==1) {
current=frontierAL.get(frontierAL.size()-1);
frontierAL.remove(frontierAL.size()-1);
}
else if (datastructure==2) {
current=frontierAL.get(0);
frontierAL.remove(0);
}
else if (datastructure==3)
current=frontierST.pop();
else if (datastructure==4)
current=frontierLL.removeFirst();
current.initialize_successor();
while((next=current.nextSuccessor())!=null)
{
if (next.numbers==N*N)
{
System.out.println("\nSOLUTION FOUND ");
System.out.println("==============");
next.display();
return;
}
else
switch (datastructure) {
case 1: ;
case 2: {frontierAL.add(next);
break;}
case 3: { frontierST.push(next);
break;}
case 4:{ frontierLL.addLast(next);
break;
}
}
}
switch (datastructure) {
case 1:
if (frontierAL.isEmpty())
empty_frontier=true;
break;
case 2:
if (frontierAL.isEmpty())
empty_frontier=true;
break;
case 3:
if (frontierST.isEmpty())
empty_frontier=true;
break;
case 4:
if (frontierLL.isEmpty())
empty_frontier=true;
break;
}
}
System.out.println("\nPUZZLE CANNOT BE SOLVED");
}
public static void main(String[] args){
//Scanner input = new Scanner(System.in);
//String filename = args[0];
//int option = Integer.parseInt(args[1]);
readMagicSquare(filename);
MagicSquare sqr = new MagicSquare();
sqr.setNandValues(N, pin);
initialize_search(sqr, option);
search(option);
}
}
At first i thought i was missing something in my while loops so i wrote them as "childish" as possible. Still nothing... Everything i tried is as a comment in the classes' code.
So Any ideas?

How to find common numbers or an anomaly in a 2D array and cause it to trigger something else

I have a 2D array (a matrix of 10x10) with values ranging from 0 to -5.
I want a method to be triggered when there is a sequence of a value found within the array.
For example, there is a sequence of two negative 2. I want it to trigger an event/method that will give a bonus score of 4. This should happen only when there are two -2's and not if there is just one -2.
I tried achieving something like that but I cant figure out how to tell the program to only trigger when 'n' number of a value is found within the matrix.
public class Test {
static int board[][] = new int[10][10];
public static void Test() {
int i, j;
board[0][0] = -1;
board[0][1] = -1;
board[1][1] = -2;
board[1][2] = -2;
board[1][3] = -2;
board[1][4] = -2;
for (i = 0; i < board.length; i++) {
System.out.println("");
for (j = 0; j < board.length; j++) {
//board[i][j] = 0;
System.out.print(board[i][j]);
}
}
System.out.println();
}
public static void scanBoard() {
int i, j;
for (i = 0; i < board.length; i++) {
for (j = 0; j < board.length; j++) {
if (board[i][j] == -1) {
System.out.println("Hello");
}
}
}
}
public static void main(String[] args) {
Test(); //prints out whole array
scanBoard(); //scans for
}
}
public class Main {
static final int size = 10;
static int[][] matrix = new int[size][size];
public static void main(String[] args) {
System.out.println("The first matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 3 && j > 3) {
matrix[i][j] = -2; //-2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
System.out.println("\nThe second matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 9 && j > 5) {
matrix[i][j] = 2; //changed it from -2 to 2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
}
static void scanBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == -2 && (j + 3 < size)) {
if (matrix[i][j + 1] == -2 && matrix[i][j + 2] == -2 && matrix[i][j + 3] == -2) {
System.out.println("\nThere you go, a special effect!".toUpperCase());
}
}
}
}
}
}
I am not sure if this is the result you wished to see according to your request. I hope this helps you. And I did some changes in your code so it will be easier to read (In my opinion lol).
public class Main {
static final int size = 10;
static int[][] matrix = new int[size][size];
public static void main(String[] args) {
System.out.println("The first matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 9 && (j == 0 || j == 1)) {
matrix[i][j] = -2; //-2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
System.out.println("\nThe second matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 8 && (j == 5 || j == 6)) {
matrix[i][j] = 2; //changed it from -2 to 2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
}
static void scanBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == -2 && (j + 1 < size)) {
if (matrix[i][j + 1] == -2) {
//You can remove the '.toUpperCase()', it's just my personal preference
System.out.println("\nThere you go, a special effect!".toUpperCase());
}
}
}
}
}
}
From what I understood from the problem statement and comments, you want your scanBoard to behave like this:
public static void scanBoard(int value, int frequency) {
int i, j;
if (value <= 0 && value >= -5 && frequency >= 2 && frequency <= 10) {
for (i = 0; i < board.length; i++) {
int rowFrequency = 0;
for (j = 1; j < board.length; j++) {
if (board[i][j] == value && board[i][j - 1] == value) {
rowFrequency++;
} else {
rowFrequency = 0;
}
if (rowFrequency + 1 >= frequency) {
System.out.println("Hello");
}
}
}
}
}
public static void main(String[] args) {
Test(); //prints out whole array
scanBoard(-2, 4); //prints Hello once
scanBoard(-2, 3); //prints Hello twice
scanBoard(-2, 3); //prints Hello thrice
}

Can someone help me with my win scenario in my Gomoku program?

I have written a program for an assignment where we had to write a simple Gomoku program. I thought I had it all, but when I compile and run, it sets off the win scenario even if I only have 4 of a kind and even if they're not next to each other. (It should only set off a win if there are five in a row of one kind...X's or O's). I feel like I should be resetting my counter back to 0 before each turn, but I'm not sure where I should be doing that. Any tips would be appreciated!
import java.util.Scanner;
public class Gomoku1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
char[][] map = new char [19][19];
int row = 0;
int column = 0;
//fill game with dots
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map[i].length; j++)
{
map[i][j] = '.';
}
}
printMap(map);
char player1Choice = 'X';
char player2Choice = 'O';
int [] place;
while (true)
{
System.out.println("Player 1's turn!");
place = userTurn(map, player1Choice);
if (isValidMove(map, place[0], place[1]) == false)
{
System.out.println("Invalid move! Try again!");
place = userTurn(map, player1Choice);
}
if (isValidMove(map, place[0], place[1])) {
map[place[0]][place[1]] = player1Choice;
printMap(map);
}
if (isBoardFull(map) == true)
{
System.out.println("Board is full. Tied game.");
break;
}
if (hasPlayerWon(map, player1Choice) == true)
{
System.out.println("Player 1 Wins!");
break;
}
else
{
System.out.println("Player 2's turn!: ");
place = userTurn(map, player2Choice);
//System.out.println(isValidMove(map, row, column));
if (isValidMove(map, place[0], place[1]) == false)
{
System.out.println("Invalid move! Try again!");
place = userTurn(map, player2Choice);
}
if (isValidMove(map, place[0], place[1])) {
map[place[0]][place[1]] = player2Choice;
printMap(map);
}
if (isBoardFull(map) == true)
{
System.out.println("Board is full. Tied game.");
break;
}
if (hasPlayerWon(map, player2Choice) == true)
{
System.out.println("Player 2 Wins!");
break;
}
}
}
}
public static void printMap (char[][] map)
{
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map[i].length; j++)
{
System.out.printf("%2c", map[i][j]);
}
System.out.println();
}
}
public static int [] userTurn (char[][] map, char playerChoice)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter row: ");
int row = input.nextInt();
System.out.print("Enter column: ");
int column = input.nextInt();
int place [] = {row, column};
return place;
}
public static boolean isValidMove (char[][] map, int row, int column)
{
//System.out.println ("n is valid move");
if (row < 0 || row > 18 || column < 0 || column > 18 || map[row][column]=='O' || map[row][column]=='X')
{
return false;
}
else
{
return true;
}
}
public static boolean isBoardFull (char[][] map)
{
int openSpots = 0;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (!(map[i][j]=='.'))
openSpots++;
}
}
if (openSpots == 361)
{
return true;
}
return false;
}
public static boolean hasPlayerWon(char[][] map, int player)
{
if (isHorizontalWin(map, player) == true || isVerticalWin(map, player) == true || isDiagonalWin(map, player) == true)
{
return true;
}
return false;
}
public static boolean isHorizontalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 0;
c += 1;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
public static boolean isVerticalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 1;
c += 0;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
public static boolean isDiagonalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count++;
r += 1;
c += 1;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
}
You have problems in all three of the function that check win conditions: isHorizontalWin, isVerticalWin, and isDiagonalWin. All three increment the variable count, but this variable is never set back to zero. Additionally, the check to see if count == 5 should be made inside the loop. Here is an example on how to fix isHorizontalWin:
public static boolean isHorizontalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 0;
c += 1;
}
if (count == 5)
{
return true;
} else {
count = 0;
}
}
}
}
return false;
}

Java Table class structure

First time posting, have a question about a table class I'm working on. For some reason adding a new row doesn't add the correct number of rows. I've added the code
public void addRow(int i) {
if (i < 0 || i > rows()) throw new IndexOutOfBoundsException();
table.add(i, new ArrayList<T>());
for(int j = 0; j < cols(); j++) {
table.get(i).add(null);
}
}
public void addCol(int j) {
if (j < 0 || j > cols()) throw new IndexOutOfBoundsException();
if(rows() == 0) {
addRow(0);
}
for (int i = 0; i < rows(); i++) {
table.get(i).add(j, null);
}
}
These here are the methods I have to add a new row and column to the table. Below is what I'm using to test. For some reason it's adding a 5th row. Not sure where from.
Table<Integer> table = new Table<>(Integer.class);
for(int i = 0; i < 4; i++) {
table.addCol(table.cols());
}
for(int i = 0; i < 4; i++) {
table.addRow(table.rows());
}
Any help or ideas would be much appreciated, thanks!
Full Code:
public class Table<T> implements AbstractTable<T> {
List<List<T>> table;
public Table(Class<T> t) { table = new ArrayList<>(); }
public int rows() { return table.size(); }
public int cols() {
if(rows() == 0) {
return 0;
} else {
return table.get(0).size();
}
}
public T get(int i, int j) {
if (i < 0 || i > rows() - 1 || j < 0 || j > cols()-1)
throw new IndexOutOfBoundsException();
return table.get(i).get(j);
}
public T set(int i, int j, T x) {
if (i < 0 || i > rows() - 1 || j < 0 || j > cols()-1)
throw new IndexOutOfBoundsException();
return table.get(i).set(j, x);
}
public void addRow(int i) {
if (i < 0 || i > rows()) throw new IndexOutOfBoundsException();
table.add(i, new ArrayList<T>());
for(int j = 0; j < cols(); j++) {
table.get(i).add(null);
}
}
public void addCol(int j) {
if (j < 0 || j > cols()) throw new IndexOutOfBoundsException();
if(rows() == 0) {
addRow(0);
}
for (int i = 0; i < rows(); i++) {
table.get(i).add(j, null);
}
}
public void removeRow(int i) {
if (i < 0 || i > rows() - 1) throw new IndexOutOfBoundsException();
table.remove(i);
}
public void removeCol(int j) {
if (j < 0 || j > cols() - 1) throw new IndexOutOfBoundsException();
for (int i = 0; i < rows(); i++) {
table.get(i).remove(j);
}
}
public static void main(String[] args) {
Table<Integer> table = new Table<>(Integer.class);
for(int i = 0; i < 4; i++) {
table.addCol(table.cols());
}
for(int i = 0; i < 4; i++) {
table.addRow(table.rows());
}
System.out.println("rows: " + table.rows() + "\ncols: " + table.cols());
table.removeCol(1);
table.removeRow(1);
System.out.println("rows: " + table.rows() + "\ncols: " + table.cols());
}
}
If you used a debugger, you’d see that you are adding the extra row in addCol

How can I Implement Adaptive merge sort in hadoop mapreduce

I have written adaptive merge sort in java. But as a mapreduce program there are three class . one is map , two is reducer and third is driver . I am not understaing how to convert this code to mapreduce so that I can run this on hadoop multi node cluster?
here is the code :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws Exception {
MainClass mainClass = new MainClass();
MainClass.SortClass sortClass = mainClass.new SortClass();
sortClass.sortMainFunction();
}
public class Constant {
public static final int MAX = 10000;
public static final int max = 10000;
}
public class Values {
int st_index;
int ed_index;
boolean as_ds;
public Values(int st_index, int ed_index, boolean as_ds) {
this.st_index = st_index;
this.ed_index = ed_index;
this.as_ds = as_ds;
}
}
public class SortClass {
int[] a = new int[Constant.MAX];
int[] b = new int[Constant.MAX];
int index1 = 0;
int i = 0;
int numberOfItem = 0, first_ind, end_ind, tem, k, g, h;
boolean flag;
Values node[] = new Values[Constant.max];
int p, q, r, low, high, j;
void insert(int st_ind, int end_ind, boolean fl) {
node[index1] = new Values(st_ind, end_ind, fl);
index1++;
}
public void sortMainFunction() throws Exception {
addDataIntoArray();
first_ind = 0;
end_ind = 0;
flag = false;
tem = a[0];
k = 1;
while (true) {
while (true) {
if (k < i && tem >= a[k]) {
end_ind = k;
tem = a[k];
k++;
flag = true;
continue;
}
break;
}
if (flag) {
node[index1] = new Values(first_ind, end_ind, flag);
index1++;
first_ind = k;
end_ind = k;
if (k >= i) {
} else {
tem = a[k++];
}
}
while (true) {
if (k < i && tem <= a[k]) {
tem = a[k];
end_ind = k;
flag = false;
k++;
continue;
}
break;
}
if (!flag) {
insert(first_ind, end_ind, flag);
first_ind = end_ind = k;
if (k >= i) {
} else {
tem = a[k++];
}
}
if (end_ind == i)
break;
}
g = index1 - 1;
h = 0;
while (true) {
if (g / 2 <= 0) {
break;
}
g /= 2;
h++;
}
System.out.println(h);
h = (int) ((double) Math.log((double) index1 - 1) / (double) Math.log(2.0));
System.out.println(h);
p = 1;
for (q = 0; q <= h; q++, p *= 2) {
for (r = 0; r < index1; r++) {
if (2 * r * p + p >= index1)
break;
else {
low = 2 * p * r;
high = 2 * p * r + p;
k = node[low].st_index;
if (node[low].as_ds == false && node[high].as_ds == false) {
i = node[low].st_index;
j = node[high].st_index;
while (i <= node[low].ed_index && j <= node[high].ed_index) {
if (a[i] <= a[j])
b[k++] = a[i++];
else
b[k++] = a[j++];
}
if (i > node[low].ed_index)
while (j <= node[high].ed_index)
b[k++] = a[j++];
else
while (i <= node[low].ed_index)
b[k++] = a[i++];
} else if (node[low].as_ds == false && node[high].as_ds == true) {
i = node[low].st_index;
j = node[high].ed_index;
while (i <= node[low].ed_index && j >= node[high].st_index) {
if (a[i] <= a[j])
b[k++] = a[i++];
else
b[k++] = a[j--];
}
if (i > node[low].ed_index)
while (j >= node[high].st_index)
b[k++] = a[j--];
else
while (i <= node[low].ed_index)
b[k++] = a[i++];
} else if (node[low].as_ds == true && node[high].as_ds == false) {
i = node[low].ed_index;
j = node[high].st_index;
while (i >= node[low].st_index && j <= node[high].ed_index) {
if (a[i] <= a[j])
b[k++] = a[i--];
else
b[k++] = a[j++];
}
if (j > node[high].ed_index)
while (i >= node[low].st_index)
b[k++] = a[i--];
else
while (j <= node[high].ed_index)
b[k++] = a[j++];
} else if (node[low].as_ds == true && node[high].as_ds == true) {
i = node[low].ed_index;
j = node[high].ed_index;
while (i >= node[low].st_index && j >= node[high].st_index) {
if (a[i] <= a[j])
b[k++] = a[i--];
else
b[k++] = a[j--];
}
if (i < node[low].st_index)
while (j >= node[high].st_index)
b[k++] = a[j--];
else
while (i >= node[low].st_index)
b[k++] = a[i--];
}
for (k = node[low].st_index; k <= node[high].ed_index; k++)
a[k] = b[k];
node[low].ed_index = node[high].ed_index;
node[high].st_index = node[low].st_index;
node[low].as_ds = false;
node[high].as_ds = false;
}
}
}
BufferedWriter output = null;
File file = new File("output.txt");
output = new BufferedWriter(new FileWriter(file));
for (k = 0; k < numberOfItem; k++) {
String s = String.valueOf(a[k]);
output.write(s);
output.newLine();
}
if (output != null) {
output.close();
}
}
public void addDataInt
oArray() throws Exception {
Scanner scanner;
scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextInt()) {
a[i] = scanner.nextInt();
i++;
numberOfItem++;
}
}
}
}

Categories

Resources