Tic Tac Toe game 10*10 board - Find Winner - java

I have to work on a project in my project I have to find TicTacToe game winner.
String [][]board=new String [10][10];
Where are 10 rows and 10 columns
I can find winner horizontally:
for (int I=0;I<10;I++){
String line1=new String();
for (int i=0;i<10;i++) {
line1+=index[I][i];
}
if (line1.equals("XXXXXXXXXX")) {
System.out.println("winner is X");///return here X
} else if (line1.equals("OOOOOOOOOO")) {
System.out.println("winner is O");//return here O
}
}
}
But I am not able to find a winner vertically, I have 1 option I can
hard code it but I want to code it logically like my code for
horizontally.

I have solved this problem, first rotate the array then again check using horizontally code
//first find the transpose of the index.
for (int i = 0; i < 10; i++){
for (int j = i; j < 10; j++){
String temp = index[i][j];
index[i][j] = index[j][i];
index[j][i] = temp;
}
}
//reverse each row
for (int i = 0; i< 10; i++){
for(int j = 0; j< 10/2; j++){
String temp = index[i][j];
index[i][j] = index[i][10 - 1 - j];
index[i][10 - 1 - j] = temp;
}
}
Now array is rotated and now i can use my Horizontally checking code.
for (int I=0;I<10;I++){
String line1=new String();
for (int i=0;i<10;i++) {
line1+=index[I][i];
}
if (line1.equals("XXXXXXXXXX")) {
System.out.println("winner is X");///return here X
}else if (line1.equals("OOOOOOOOOO")){
System.out.println("winner is O");//return here O
}
}

It's simply first rotate the array then again check using horizontally code
//first find the transpose of the index.
for (int i = 0; i < 10; i++){
for (int j = i; j < 10; j++){
String temp = index[i][j];
index[i][j] = index[j][i];
index[j][i] = temp;
}
}
//reverse each row
for (int i = 0; i< 10; i++){
for(int j = 0; j< 10/2; j++){
String temp = index[i][j];
index[i][j] = index[i][10 - 1 - j];
index[i][10 - 1 - j] = temp;
}
}

rotate the array then again check using horizontally code, it's easy
//first find the transpose of the index.
for (int i = 0; i < 10; i++){
for (int j = i; j < 10; j++){
String temp = index[i][j];
index[i][j] = index[j][i];
index[j][i] = temp;
}
}
//reverse each row
for (int i = 0; i< 10; i++){
for(int j = 0; j< 10/2; j++){
String temp = index[i][j];
index[i][j] = index[i][10 - 1 - j];
index[i][10 - 1 - j] = temp;
}
}

Related

How can I fill two-dimensional arrayList with one dimensional?

I have a problem that, whenever I try to fill two dimensional arrayList (5x5) with one dimensional, I get index out of bounds exceptions. I guess that's because the square Array doesn't have index 0 value yet, but I don't know how to fix it.
ArrayList<Character> c = new ArrayList<>();
// Copy character by character into arraylist
for (int i = 0; i < finalArray.length(); i++) {
c.add(i, finalArray.charAt(i));
}
ArrayList<ArrayList<Character>> square = new ArrayList<>();
//square.add(new ArrayList<>());
int k = 0;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
square.get(j).add(i, c.get(k));
k++;
}
}
Add a “row” List to the outer List before the inner loop. You are also using the wrong index for square.
int k = 0;
for(int i = 0; i < 4; i++){
square.add(new ArrayList<>()); // Initialize the row
for(int j = 0; j < 4; j++){
square.get(i).add(c.get(k++)); // get(i) not get(j)!
}
}
Note the other simplifications too.
It would be clearer to do this:
int k = 0;
for(int i = 0; i < 4; i++){
List<Character> row = new ArrayList<>();
square.add(row);
for(int j = 0; j < 4; j++){
row.add(c.get(k++));
}
}

How to reverse a triangle jagged array?

I have already done with normal jagged array, but I don't understand how to reverse it upside down. Also I have a question, how to shift the side of triangle from left side to right? Can I do this with loops or I need to write different quantity of whitespaces for every line of my array?
static int[][] triangle(int lines){
int[][] arr = new int[lines][];
for(int i = 0; i < arr.length; i++){
arr[i] = new int[i + 1];
}
int count = 0;
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
arr[i][j] = count++;
}
}
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
return arr;
}
Some kind of result:
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
You can quickly create a reversed triangle by changing the way you initialize your arr array.
static int[][] revTriangle(int lines) {
int[][] arr = new int[lines][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[lines - i]; // this line
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = count++;
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
return arr;
}
I get the following output:
0 1 2 3 4
5 6 7 8
9 10 11
12 13
14
Hope this helps!
If you need a more compact solution you can group some loops (basing on anacron answer):
static int[][] triangle( int lines, boolean straight)
{
int[][] arr = new int[lines][];
int count = 0;
for ( int i = 0; i < arr.length; i++ )
{
int start = (straight? i : lines);
int step = (straight? 1 : -i);
arr[i] = new int[start + step ];
for ( int j = 0; j < arr[i].length; j++ )
{
arr[i][j] = count++;
System.out.print( arr[i][j] + " " );
}
System.out.println();
}
return arr;
}

Using java cplex to solve TSP, getValues of variables gives an error

I use cplex to solve the travelling salesman problem (TSP).
Given that if x[i][j]=1, then the path goes from the city i to the city j, otherwise, ther is no path between these cities.
The corresponding matrix:
IloNumVar[][] x = new IloNumVar[n][];
for(int i = 0; i < n; i++){
x[i] = cplex.boolVarArray(n);
}
When cplex finishes solving, I want to get the values of x like this:
if(cplex.solve()){
double[][] var = new double[n][n];
for(int i = 0; i<x.length; i++){
for(int j = 0 ; j < x[i].length; j ++){
var[i][j] = cplex.getValue(x[i][j]);
if(var[i][j] ==1){
System.out.print(i + " "+ j);
}
}
}
}
but it gives an error. I will appreciate anyone who can give some advice.
the error is in :
var[i][j] = cplex.getValue(x[i][j]);
the explain is :
Exception in thread "main" ilog.cplex.IloCplex$UnknownObjectException: CPLEX Error: object is unknown to IloCplex
at ilog.cplex.IloCplex.getValue(IloCplex.java:6495)
the entire code is following:
import java.io.IOException;
import ilog.concert.*;
import ilog.cplex.IloCplex;
public class TSP {
public static void solveMe(int n) throws IloException, IOException{
//random data
double[] xPos = new double[n];
double[] yPos = new double[n];
for (int i = 0; i < n; i ++){
xPos[i] = Math.random()*100;
yPos[i] = Math.random()*100;
}
double[][] c = new double[n][n];
for (int i = 0 ; i < n; i++){
for (int j = 0 ; j < n; j++)
c[i][j] = Math.sqrt(Math.pow(xPos[i]-xPos[j], 2)+ Math.pow(yPos[i]-yPos[j],2));
}
//model
IloCplex cplex = new IloCplex();
//variables
IloNumVar[][] x = new IloNumVar[n][];
for(int i = 0; i < n; i++){
x[i] = cplex.boolVarArray(n);
}
IloNumVar[] u = cplex.numVarArray(n, 0, Double.MAX_VALUE);
//Objective
IloLinearNumExpr obj = cplex.linearNumExpr();
for(int i =0 ; i <n ; i++){
for (int j = 0; j< n ;j++){
if(j != i){
obj.addTerm(c[i][j], x[i][j]);
}
}
}
cplex.addMinimize(obj);
//constraints
for(int j = 0; j < n; j++){
IloLinearNumExpr expr = cplex.linearNumExpr();
for(int i = 0; i< n ; i++){
if(i!=j){
expr.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(expr, 1.0);
}
for(int i = 0; i < n; i++){
IloLinearNumExpr expr = cplex.linearNumExpr();
for(int j = 0; j< n ; j++){
if(j!=i){
expr.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(expr, 1.0);
}
for(int i = 1; i < n; i++){
for(int j = 1; j < n; j++){
if(i != j){
IloLinearNumExpr expr = cplex.linearNumExpr();
expr.addTerm(1.0, u[i]);
expr.addTerm(-1.0, u[j]);
expr.addTerm(n-1, x[i][j]);
cplex.addLe(expr, n-2);
}
}
}
//solve mode
if(cplex.solve()){
System.out.println();
System.out.println("Solution status = "+ cplex.getStatus());
System.out.println();
System.out.println("cost = " + cplex.getObjValue());
for(int i = 0; i<x.length; i++){
for(int j = 0 ; j < x[i].length; j ++){
System.out.print(cplex.getValue(x[i][j]));
}
}
}
//end
cplex.end();
}
}
Looking at this page at the IBM knowledge center, the argument to getValue() must be something that was used to construct the model you are solving, as in the example here. Since var is n x n, you should probably initialize x as IloNumVar[][] x = new IloNumVar[n][n];. At some point before calling solve(), each element of x should be added to your model.
In your setup, the diagonal elements of x are never referenced by the model. You will notice that all your setup loops have a condition if(i != j). To fix your issue, either add an else clause to at least one of the loops, or if that is meaningless (as I suspect it is), do your printout consistently with the input:
for(int i = 0; i<x.length; i++) {
for(int j = 0 ; j < x[i].length; j ++) {
if(i != j)
System.out.print(cplex.getValue(x[i][j]));
else
System.out.print("-");
}
}

Java - Selection Sort - only switching once

So the first switch definitely occurs between the lowest value 3, and 5, but it doesn't keep going after that. This makes me think there is something wrong with one of the for loops?
public class SelectionSort
{
public static void main (String[] args)
{
int [] list;
list = new int[5];
list[0] = 4;
list[1] = 5;
list[2] = 12;
list[3] = 9;
list[4] = 3;
for (int i = 0; i < list.length-1; ++i) {
int index = i;
for (int j = 1; j < list.length; ++j) {
if (list[j] < list[index]) {
int temp = list[j];
list[j] = list[index];
list[index] = temp;
}
}
}
for (int k = 0; k < list.length; ++k) {
System.out.print(list[k] + ", ");
}
}
}
Short versión:
for (int i = 0; i < list.length-1; i++)
for (int j = i+1; j < list.length; j++)
if (list[j] < list[i]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
for (int k = 0; k < list.length; k++) {
System.out.print(list[k] + ", ");
}
after if (list[j] < list[index]) {, you have to update index if boolean statement gets satisfied so you need to index = j and do the swap after
see follwing :
public class MySelectionSort {
public static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
for (int i = 0; i < list.length; ++i) {
int index = i;
for (int j = i + 1; j < list.length; ++j) {
if (list[j] < list[index]) {
index = j; }}
if (index != i) {
int temp = list[i];
list[i] = list[index];
list[index] = i; }}
To cut down on the number of swaps, the loop on j should only be looking the best item to swap with item i. There should be at most one swap for each value of i. (That's what makes it a Selection sort. If you do multiple swaps for each i, you might as well be doing Bubble Sort.
But that's for efficiency. The reason your code isn't working is that you start the loop on j at j = 1 instead of j = i + 1.

Reverse the rows of a 2d array

Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}

Categories

Resources