I want to move false elements in empty space (just like in Schelling's Model of Segregation).
This is the array ..(the elements in the array are placed randomly)
'X*''O'' ''X''O*'
'O''O'' '' ''X'
'O'' ''X''X''O*'
'X'' '' ''X''X'
'X''X''O*''X''O*'
the element at (0,0),(0,4),(2,4),(4,2),(4,4) are false because it does no have similar elements around it.(i have * next to it is easier for you to see). I want to move those false elements to blank location ' ' in the array. It can be moved to any empty location in the array.
' ''O''X''X'' '
'O''O''O'' ''X'
'O''O''X''X'' '
'X''O''O''X''X'
'X''X'' ''X'' '
This is my code.
//isArrGood is a method that checks if the element is false or true
//arr is 2D array that is being passed in the method
//store the false elements
char[] falseEle = new char[arr.length * arr[0].length];
for(int i=0; i<arr.length; i++){
for(int j=0; j<arr[i].length; j++){
if(!isArrGood(arr,i,j)){
falseEle[i] = arr[i][j];
}
}
}
//finds the blank space and replaces it with a false cell and finds a false cell and
//replace it with a blank space
for(int x=0; x<arr.length; x++){
for(int y=0; y<arr[x].length; y++) {
if (arr[x][y] == ' ') {
arr[x][y] = falseEle[x];
}
if(!isArrGood(arr,x,y){
arr[x][y] = ' ';
}
}
}
This is the what i get.
the current array(arr) being send in the method is. The false elements in this array are at
(1,0),(2,2),(3,2)
' ' 'X' 'X' 'X' 'X'
'O' ' ' 'X' 'X' ' '
' ' 'X' 'O' ' ' 'X'
'O' 'O' 'X' ' ' 'O'
'O' 'O' ' ' 'O' ' '
And this is what I get
'' 'X' 'X' 'X' 'X'
'O' 'O' 'X' 'X' 'O'
'O' 'X' 'O' 'O' 'X'
'O' 'O' 'X' 'X' 'O'
'O' 'O' '' 'O' ''
The array on the very top is just a example of what I am trying to do.
Could you post more code i.e. a Minimal, Complete, and Verifiable example of your problem?
For the problem "Schelling's Model of Segregation" you could use the code I wrote to learn from:
import java.util.Random;
public class ShellingSegregationModel
{
public static final int EMPTY = 0;
public static final int BLUE = 1;
public static final int RED = 2;
// number of elements for random
public static final int ELEMENTS = 3;
public static final double THRESHOLD = 0.15;
//size of the field
public int size;
int[][] field;
// temporary field for the iteration
int[][] temporary;
public int iteration;
public ShellingSegregationModel(int size)
{
Random random = new Random();
this.size = size;
field = new int[size][size];
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
field[y][x] = random.nextInt(ELEMENTS);
}
}
}
public int getSize()
{
return size;
}
public void setField(int[][] field)
{
this.field = field;
}
public int[][] getField()
{
return field;
}
public void setTemporary(int[][] temporary)
{
this.temporary = temporary;
}
public int[][] getTemporary()
{
return temporary;
}
public int getIteration()
{
return iteration;
}
public void setIteration(int iteration)
{
this.iteration = iteration;
}
public double getThreshold()
{
return THRESHOLD;
}
//how many neighbors needed for threshold
public double getCalculatedThreshold()
{
return getThreshold()*8;//8 is the neighbors count total possible
}
public static String getSymbolFor(int x)
{
String s = "";
switch (x)
{
case BLUE:
s = "x";
break;
case RED :
s = "o";
break;
case EMPTY:
default:
s = " ";
}
return s;
}
public boolean isEmpty(int x, int y)
{
return get(x,y) == EMPTY;
}
/**
* Prints field
*/
public void print(String message)
{
System.out.println(message);
for (int y = 0; y < getSize(); y++)
{
StringBuilder row = new StringBuilder();
for (int x = 0; x < getSize(); x++)
{
row.append("'").append(getSymbolFor(get(x,y))).append("' ");
}
System.out.println(row.toString());
}
}
public void printSameNeighorsCount(String message)
{
System.out.println(message);
for (int y = 0; y < getSize(); y++)
{
StringBuilder row = new StringBuilder();
for (int x = 0; x < getSize(); x++)
{
row.append("'").append(sameNeighbors(x, y)).append("' ");
}
System.out.println(row.toString());
}
}
public int get(int x, int y)
{
return getField()[y][x];
}
private int add(boolean c)
{
return c ? 1 : 0;
}
public int sameNeighbors(int x, int y)
{
return isEmpty(x,y) ? 0 :
add(isSame(get(x,y),x ,y-1))
+ add(isSame(get(x,y),x-1,y-1))
+ add(isSame(get(x,y),x-1,y ))
+ add(isSame(get(x,y),x-1,y+1))
+ add(isSame(get(x,y),x ,y+1))
+ add(isSame(get(x,y),x+1,y+1))
+ add(isSame(get(x,y),x+1,y ))
+ add(isSame(get(x,y),x+1,y-1));
}
private static void copyArray(int[][] src, int[][] dest)
{
for (int i = 0; i < src.length; i++)
{
dest[i] = new int[src[i].length];
System.arraycopy(src[i], 0, dest[i], 0, src[i].length);
}
}
private void duplicateToTemporary()
{
setTemporary(new int[getField().length][]);
copyArray(getField(),getTemporary());
}
//
private void assignFromTemporary()
{
setField(new int[getField().length][]);
copyArray(getTemporary(), getField());
}
public void iterate(int iterations)
{
for (int i = 0; i < iterations; i++)
{
duplicateToTemporary();
for (int y = 0; y < getSize(); y++)
{
for (int x = 0; x < getSize(); x++)
{
if (!isHappy(x,y))
{
swap(x,y);
}
}
}
assignFromTemporary();
}
setIteration(getIteration()+iterations);
}
//Swaps with empty random from temporary
public void swap(int i, int j)
{
Random random = new Random();
boolean swapped = false;
//skip a random number of empty
int skip = random.nextInt(100);
while (!swapped)
{
for (int y = 0; !swapped && y < getSize(); y++)
{
for (int x = 0; !swapped && x < getSize(); x++)
{
if (getTemporary()[y][x] == EMPTY && 0 >= --skip)
{
getTemporary()[y][x] = getTemporary()[j][i];
getTemporary()[j][i] = EMPTY ;
swapped = true;
}
}
}
}
}
public boolean isHappy(int x, int y)
{
return getCalculatedThreshold() < sameNeighbors(x, y);
}
public boolean isSame(int me, int x, int y)
{
return
//check bounds
x >= 0 && y >= 0 && x < getSize() && y < getSize()
//check element
&& get(x,y) == me;
}
public static void main(String[] args)
{
ShellingSegregationModel ssm = new ShellingSegregationModel(10);
ssm.print("Randomly generated field");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(5);
ssm.print("Field after 5 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(5);
ssm.print("Field after 10 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(5);
ssm.print("Field after 15 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(50);
ssm.print("Field after 65 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
}
}
Related
I am coding a simple tic-tac-toe for a high-school mini project, but I need it to be within a strict data volume (not more than 112 lines). I thought checking for each row, column and cross would be long, so is there any alternative to do so (You should see a [[[HERE]]] comment)? (Btw, I already know it looks awful) Thanks in advance!
public class TTTGame {
//OPTIONS v
public static final String draw = "DRAW"; // <- Definitions for different states
public static final String circles = "CIRCLES"; // BOT
public static final String crosses = "CROSSES"; // PLAYER
public static final String getCrosses = "X"; //<- Symbols to display
public static final String getCircles = "O";
//OPTIONS ^
//DO NOT MODIFY UNDER THIS LINE (Just kidding, do whatever u want) v
public static int[][] board = {
{0,0,0},
{0,0,0},
{0,0,0},
};
public static final int empty = 0; // Definition of the values
public static final int cross = 1;
public static final int circle = 2;
public static int turns = 0; //Just here to count turns, nothing special
public static void main(String[]args) { //Main process
board[1][1] = circle;
display();
while (true) {
PlayerTurn();
if (checkStop()||checkWinner()!=null) {display();GStop();break;}
BotTurn();
if (checkStop()||checkWinner()!=null) {display();GStop();break;}
display();
turns += 1;
}
}
private static void GStop() { //Force stop the match function
System.out.println("Winner : " + checkWinner());
System.exit(1);
}
private static boolean checkStop() { //Check if match is already full / completed (Draw)
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
if (board[x][y]==empty) return false;
return true;
}
#Nullable
private static String checkWinner() { //Check Winner
// [[[ HERE ]]] ---------------
return null;
}
private static void PlayerTurn() { //Player turn
int x; Scanner c = new Scanner(System.in);
while (true) {
x = c.nextInt();
x = x-1;
if ((x>=0)&&(x < 9)) {
if (board[x / 3][x % 3] == empty) {
board[x / 3][x % 3] = cross;
break;
} else System.out.println("Already chosen");
} else System.out.println("Invalid");
}
}
private static void BotTurn() { //Bot turn -> (Modify these to change the AI behaviour, here's a very simple one);
boolean choose = true;
for (int y = 0; y < 3 ; y++)
for (int x = 0; x < 3; x++)
if (board[y][x] == empty&&choose) {
board[y][x] = circle;
choose = false;
}
}
private static void display() { //Display the board
int nn = 1;
String a = "z";
for (int y = 0; y < 3 ; y++) {
for (int x = 0; x < 3; x++) {
if (board[y][x] == 0) a = "*";
if (board[y][x] == 1) a = getCrosses;
if (board[y][x] == 2) a = getCircles;
System.out.print(a + " ");
}
System.out.print(" "); //Indications
for (int xn = 0; xn < 3; xn++) {
System.out.print(nn);
nn+=1;
System.out.print(" ");
}
System.out.println(" ");
}
}
}
How about this idea: (neither the only nor the best nor the most performant solution... just an idea)
You can use the sum of each row, diagonal and column to determine if the either player one (all 1s) or player two (all 2s) wins. Therefore you only need to set the empty field to be higher than 6.
For example let's say your board looks like this:
7 1 1 -> 7+1+1 = 9 // no one wins
2 2 2 -> 2+2+2 = 6 // player two wins, he has 3 * 2 in a row
1 7 2 -> 1+7+2 =10 // no win here
if all three numbers where 1s (sum == 3) your player one wins.
It is "cumbersome" to implement, but as I said it is just an idea:
// first we check every column
for( int x=0; x<board[y].length; x++){
int sum = 0;
for( int y=0; y<board.length; y++){
sum += board[y][x];
}
if(sum == 3 || sum == 6){
return true;
}
}
// then every row
for( int y=0; y<board.length; y++){
int sum = 0;
for( int x=0; x<board[y].length; x++){
sum += board[y][x];
}
if(sum == 3 || sum == 6){
return true;
}
}
// and finally the diagonals (if we ever reach that part)
int sum= board[0][0] + board[1][1] + board[2][2];
if(sum == 3 || sum == 6){
return true;
}
sum= board[0][2] + board[1][1] + board[2][0];
if(sum == 3 || sum == 6){
return true;
}
you could also return 1 when the sum == 3 and the first player wins or 2 when player two wins.
I am working on solution for the CCC 2018 Robo Thieves Problem, it a simplified version of the original problem. My problem is that it will give me this "Index 5 out of bounds for length 5" when I executed my code and I'm not sure why it is happening. Half of my program executes and then this error occurs.
import java.util.*;
public class RoboThieves {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> rowPos = new ArrayList<Integer>();
ArrayList<Integer> colPos = new ArrayList<Integer>();
int sRow = -1; // robot pos
int sCol = -1;
int dotCounter = 0;
int stepCounter = 0;
int rowSize = sc.nextInt();
int colSize = sc.nextInt();
char[][] factoryGrid = new char[rowSize][colSize];
for (int i = 0; i < rowSize; i++) {
String rowChars = sc.next().toUpperCase();
for (int j = 0; j < colSize; j++) {
factoryGrid[i][j] = rowChars.charAt(j);
}
}
// check to see if the grid was inputted properly (with square brackets)
/*
* for (char [] row: factoryGrid) { System.out.println(Arrays.toString(row)); }
*/
// check to see if the grid was inputted properly (as inputted)
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
System.out.print(factoryGrid[i][j]);
}
System.out.println();
}
// locate dots and store their row and col in arraylists
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (factoryGrid[i][j] == '.') {
rowPos.add(i);
colPos.add(j);
dotCounter++;
}
}
}
// print dot location to check
for (int i = 0; i < rowPos.size(); i++) {
System.out.println("Dot Position = " + "(" + rowPos.get(i) + "," + colPos.get(i) + ")");
}
// locate robot position
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (factoryGrid[i][j] == 'S')
sRow = i;
sCol = j;
}
}
// print camera location to check
System.out.println("Camera Position = " + "(" + sRow + "," + sCol + ")");
//System.out.println(dotCounter); // test to see if counter works
char above = getAbove(factoryGrid, sRow, sCol);
char right = getRight(factoryGrid, sRow, sCol);
char below = getBelow(factoryGrid, sRow, sCol);
char left = getLeft(factoryGrid, sRow, sCol);
if (above == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
sRow = sRow - 1;
// sCol = sCol;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (right == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
// sRow = sRow;
sCol = sCol + 1;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (below == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
sRow = sRow + 1;
// sCol = sCol;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (left == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
// sRow = sRow;
sCol = sCol - 1;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else {
System.out.println(
"The robot cannot move to any spaces try inputting a factory layout that can produce an answer.");
} // end if above dot (yes)
System.out.println(stepCounter);
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
System.out.print(factoryGrid[i][j]);
}
System.out.println();
}
} // end main method
public static char getLeft(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow][(cCol - 1)];
}
public static char getAbove(char[][] factGrid, int cRow, int cCol) {
return factGrid[(cRow - 1)][(cCol)];
}
public static char getBelow(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow + 1][cCol];
}
public static char getRight(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow][(cCol + 1)];
}
public static boolean check360(char[][] factGrid, int cRow, int cCol) {
boolean canMove = true;
char left = getLeft(factGrid, cRow, cCol);
char above = getAbove(factGrid, cRow, cCol);
char right = getRight(factGrid, cRow, cCol);
char below = getBelow(factGrid, cRow, cCol);
if (left == 'C' || above == 'C' || right == 'C' || below == 'C') {
canMove = false;
}
return canMove;
}
} // end main program
Upon first look, I expect that the issue may lie in your getLeft(), getAbove(), getRight(), and getBelow() methods.
In these methods, you give it a value for cRow and cCol and add or subtract 1. However, you need to make sure that the index you are querying does not exceed the size of the double array factGrid, or go below 0.
For example, in your getRight() method, you might try:
public static char getRight(char[][] factGrid, int cRow, int cCol) {
if(factGrid[0].length > (cCol + 1)) {
return factGrid[cRow][(cCol + 1)];
} else {
return '';
}
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
all code
package ubung;
import java.util.Random;
//-------------------------------------------------------------- a)
public class Sudoku {
final int n = 3;
final int gridsize = n*n;
int[][] field = new int[gridsize][gridsize];
Random random = new Random();
public Sudoku() {
int[] firstRow = {1,2,3,4,5,6,7,8,9};
//h): int[] firstRow = randomRow();
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
field[i][j] = (i*n + i/n + j) % gridsize + 1;
//h): field[i][j] = firstRow[(i*n + i/n + j) % gridsize];
System.out.println(this);
}
//------------------------------------------------------------- g)
public Sudoku(int permutationCount) {
this();
randomPermutation(permutationCount);
}
//-------------------------------------------------------------- b)
/**Die Methode gibt ein Sudoku-Objekt als einen String zurueck
* #return der String eines Sudoku-Objektes
*/
public String toString() {
String str = line(25);
for(int i = 0; i < 9; i++){
str += "|";
for(int j = 0; j < 9; j++){
str += " " + get(i,j);
if(j == 2 || j == 5 || j == 8)
str += " |";
}
str += "\n";
if(i == 2 || i == 5 || i == 8){
str += line(25);
}
}
return str;
}
/**
* Getter for single entries
*/
private String get(int i, int j) {
if(i < 0 || i > gridsize + 1 || j < 0 || j > gridsize + 1) {
return " ";
}
int m = field[i][j];
if(m == 0)
return " ";
return ""+m;
}
private String line(int n){
String str = "";
for(int i = 0; i < n; i++)
str += "-";
return str+"\n";
}
//-------------------------------------------------------------- c)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions. ?????????????????????????
*/
private void permutateRows(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
for(int i = 0; i < gridsize; i++) {
int temp = field[i][a-1];
field[i][a-1] = field[i][b-1];
field[i][b-1] = temp;
}
}
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions. ????????????????????
*/
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
//-------------------------------------------------------------- d)
/**
* Two stacks are swapped. This produces 3! as much solutions.
*/
private void permutateStacks(int a, int b) {
if(b < a) {
permutateStacks(b,a);
return;
}
if(a == 1 && b == 2) {
permutateColumns(1,4);
permutateColumns(2,5);
permutateColumns(3,6);
}
else if(a == 1 && b == 3) {
permutateColumns(1,7);
permutateColumns(2,8);
permutateColumns(3,9);
}
else if(a == 2 && b == 3) {
permutateColumns(4,7);
permutateColumns(5,8);
permutateColumns(6,9);
}
}
/**
* Two bands are swapped. This produces 3! as much solutions.
*/
private void permutateBands(int a, int b) {
if(b < a) {
permutateBands(b,a);
return;
}
if(a == 1 && b == 2) {
permutateRows(1,4);
permutateRows(2,5);
permutateRows(3,6);
}
else if(a == 1 && b == 3) {
permutateRows(1,7);
permutateRows(2,8);
permutateRows(3,9);
}
else if(a == 2 && b == 3) {
permutateRows(4,7);
permutateRows(5,8);
permutateRows(6,9);
}
}
//-------------------------------------------------------------- e)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions.
*/
private void permutateRows() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateRows(a+block*3,b+block*3);
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions.
*/
private void permutateColumns() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateColumns(a+block*3,b+block*3);
}
private void permutateStacks() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateStacks(a,b);
}
private void permutateBands() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateBands(a,b);
}
//-------------------------------------------------------------- f)
/**
* The matrix is transposed. This produces double as much solutions.
*/
private void transpose() {
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < i; j++) {
int temp = field[j][i];
field[j][i] = field[i][j];
field[i][j] = temp;
}
}
//-------------------------------------------------------------- g)
private void randomPermutation(){
switch(random.nextInt(5)) {
case 0: permutateRows(); break;
case 1: permutateColumns(); break;
case 2: permutateStacks(); break;
case 3: permutateBands(); break;
case 4: transpose();
default:
}
}
private void randomPermutation(int n){
for(int i = 0; i < n; i++)
randomPermutation();
}
//-------------------------------------------------------------- h)
/**
* Returns random row of digits. Used to relabel digits in the initial matrix
* This yields 9! as much solutions.
*/
private int[] randomRow(){
boolean[] used = new boolean[gridsize];
int[] row = new int[gridsize];
for(int i = 0; i < gridsize; i++) {
int candidate = random.nextInt(gridsize);
if(!used[candidate]){
used[candidate] = true;
row[i] = candidate+1;
}
else {
i--;
}
}
return row;
}
//-------------------------------------------------------------- i)
private void hide(int n) {
if(n < 0)
n = 0;
if(n > 81)
n = 81;
for(int k = 0; k < n; k++) {
int i = random.nextInt(9); //在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值。
int j = random.nextInt(9);
if(field[i][j] != 0)
field[i][j] = 0;
else
k--;
}
}
/*****************************************/ //gegeben
public static void main(String[] args){
Sudoku s = new Sudoku(100000);
System.out.println(s);
s.hide(50);
System.out.println(s);
}
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
If we notate the indices of the 2D array as field[x][y], the provided solution code uses x as the column index and y as the row index. It is important to note that the provided method is not the only correct solution. It would be just as correct to implement x as the row index and y as the column index, so long as the methods were implemented correctly.
I want to move false elements in empty space (just like in Schelling's Model of Segregation).
This is the array ..(the elements in the array are placed randomly)
'X' 'X' ' ' 'O' 'X'
'X' ' ' 'X' ' ' 'O'
'X' 'O' ' ' 'O' 'O'
' ' 'O' ' ' ' ' ' '
' ' ' ' ' ' ' ' ' '
the element at (0,4),(1,2),(2,1),(3,1) are false because it does no have similar elements around it or does not have enough cells around it. I want to move those false elements to blank location ' ' in the array and make those false location blank ' '. The false element can be moved to any empty location in the array to make it look something like this
'X' 'X' 'X' 'O' ' '
'X' 'X' ' ' 'O' 'O'
'X' ' ' 'O' 'O' 'O'
' ' ' ' ' ' ' ' ' '
' ' ' ' ' ' ' ' ' '
This is what I get
'X' 'X' 'X' 'O' 'X'
'X' 'X' 'X' 'X' 'O'
'X' 'O' 'O' 'O' 'O'
'O' 'O' 'O' 'O' 'O'
'' '' '' '' ''
This is my code.
//isArrGood is a method that checks if the element is false or true
//arr is 2D array that is being passed in the method
char[] falseCell = new char[arr.length * arr[0].length];
for(int row=0; row<arr.length; row++){
for(int col=0; col<arr[row].length; col++){
if(!isArrGood(arr,row,col)){
falseCell[row] = arr[row][col];
arr[row][col] = ' ';
}
}
}
for(int i=0; i<arr.length; i++){
for(int j=0; j<arr[0].length; j++){
if(arr[i][j] == ' '){
arr[i][j] = falseCell[i];
}
}
}
Could you post more code i.e. a Minimal, Complete, and Verifiable example of your problem?
For the problem described you could use the code I wrote to learn from:
import java.util.Random;
public class ShellingSegregationModel
{
public static final int EMPTY = 0;
public static final int BLUE = 1;
public static final int RED = 2;
// number of elements for random
public static final int ELEMENTS = 3;
public static final double THRESHOLD = 0.15;
//size of the field
public int size;
int[][] field;
// temporary field for the iteration
int[][] temporary;
public int iteration;
public ShellingSegregationModel(int size)
{
Random random = new Random();
this.size = size;
field = new int[size][size];
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
field[y][x] = random.nextInt(ELEMENTS);
}
}
}
public int getSize()
{
return size;
}
public void setField(int[][] field)
{
this.field = field;
}
public int[][] getField()
{
return field;
}
public void setTemporary(int[][] temporary)
{
this.temporary = temporary;
}
public int[][] getTemporary()
{
return temporary;
}
public int getIteration()
{
return iteration;
}
public void setIteration(int iteration)
{
this.iteration = iteration;
}
public double getThreshold()
{
return THRESHOLD;
}
//how many neighbors needed for threshold
public double getCalculatedThreshold()
{
return getThreshold()*8;//8 is the neighbors count total possible
}
public static String getSymbolFor(int x)
{
String s = "";
switch (x)
{
case BLUE:
s = "x";
break;
case RED :
s = "o";
break;
case EMPTY:
default:
s = " ";
}
return s;
}
public boolean isEmpty(int x, int y)
{
return get(x,y) == EMPTY;
}
/**
* Prints field
*/
public void print(String message)
{
System.out.println(message);
for (int y = 0; y < getSize(); y++)
{
StringBuilder row = new StringBuilder();
for (int x = 0; x < getSize(); x++)
{
row.append("'").append(getSymbolFor(get(x,y))).append("' ");
}
System.out.println(row.toString());
}
}
public void printSameNeighorsCount(String message)
{
System.out.println(message);
for (int y = 0; y < getSize(); y++)
{
StringBuilder row = new StringBuilder();
for (int x = 0; x < getSize(); x++)
{
row.append("'").append(sameNeighbors(x, y)).append("' ");
}
System.out.println(row.toString());
}
}
public int get(int x, int y)
{
return getField()[y][x];
}
private int add(boolean c)
{
return c ? 1 : 0;
}
public int sameNeighbors(int x, int y)
{
return isEmpty(x,y) ? 0 :
add(isSame(get(x,y),x ,y-1))
+ add(isSame(get(x,y),x-1,y-1))
+ add(isSame(get(x,y),x-1,y ))
+ add(isSame(get(x,y),x-1,y+1))
+ add(isSame(get(x,y),x ,y+1))
+ add(isSame(get(x,y),x+1,y+1))
+ add(isSame(get(x,y),x+1,y ))
+ add(isSame(get(x,y),x+1,y-1));
}
private static void copyArray(int[][] src, int[][] dest)
{
for (int i = 0; i < src.length; i++)
{
dest[i] = new int[src[i].length];
System.arraycopy(src[i], 0, dest[i], 0, src[i].length);
}
}
private void duplicateToTemporary()
{
setTemporary(new int[getField().length][]);
copyArray(getField(),getTemporary());
}
//
private void assignFromTemporary()
{
setField(new int[getField().length][]);
copyArray(getTemporary(), getField());
}
public void iterate(int iterations)
{
for (int i = 0; i < iterations; i++)
{
duplicateToTemporary();
for (int y = 0; y < getSize(); y++)
{
for (int x = 0; x < getSize(); x++)
{
if (!isHappy(x,y))
{
swap(x,y);
}
}
}
assignFromTemporary();
}
setIteration(getIteration()+iterations);
}
//Swaps with empty random from temporary
public void swap(int i, int j)
{
Random random = new Random();
boolean swapped = false;
while (!swapped)
{
for (int y = 0; !swapped && y < getSize(); y++)
{
for (int x = 0; !swapped && x < getSize(); x++)
{
//swap semi-randomly
if (getTemporary()[y][x] == EMPTY && random.nextBoolean())
{
getTemporary()[y][x] = getTemporary()[j][i];
getTemporary()[j][i] = EMPTY ;
swapped = true;
}
}
}
}
}
public boolean isHappy(int x, int y)
{
return getCalculatedThreshold() < sameNeighbors(x, y);
}
public boolean isSame(int me, int x, int y)
{
return
//check bounds
x >= 0 && y >= 0 && x < getSize() && y < getSize()
//check element
&& get(x,y) == me;
}
public static void main(String[] args)
{
ShellingSegregationModel ssm = new ShellingSegregationModel(10);
ssm.print("Randomly generated field");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(5);
ssm.print("Field after 5 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(5);
ssm.print("Field after 10 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(5);
ssm.print("Field after 15 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
ssm.iterate(50);
ssm.print("Field after 65 iterations");
ssm.printSameNeighorsCount("Same neighbors count");
}
}
im creating a code for Minesweeper and trying to implement a GUI. But the problem is that when i run the code and play the game, the position i click on the board reveals the y,x coordinate of that location on the answer board rather than the x, y coordinate. Ive been trying to fix this but i cant see to figure it out. i think it maybe is the way i create the board, but i tried everything i could think of.
class Board{
public MsGUI gui;
private static char[][] userBoard;
private static char[][] solutionBoard;
private static int boundSize = 5;
public Board(){
userBoard = new char[][] {{'-','-','-','-','-'},
{'-','-','-','-','-'},
{'-','-','-','-','-'},
{'-','-','-','-','-'},
{'-','-','-','-','-'}};
solutionBoard = new char[][] {{'0','2','B','2','0'},
{'0','3','B','3','0'},
{'1','3','B','3','1'},
{'B','1','3','B','2'},
{'1','1','2','B','2'}};
return;
}
private static void printBoard(char[][] board){
for (int x = 0; x < boundSize; x++){
for(int y = 0; y < boundSize; y++){
System.out.print(" " + Character.toString(board[x][y]));
}
System.out.println("");
}
System.out.println("");
}
public void flagCell(int xCoordinate, int yCoordinate){
userBoard[xCoordinate][yCoordinate] = 'F';
}
public boolean isFlagged(int xCoordinate,int yCoordinate){
if(userBoard[xCoordinate][yCoordinate] == 'F'){
return true;
}
else{
return false;
}
}
public int getHeight() {
return userBoard.length;
}
public int getWidth(){
return userBoard[0].length;
}
public char getValue(int xCoordinate, int yCoordinate) {
return userBoard[xCoordinate][yCoordinate];
}
private static boolean checkIfAlreadyMarked(int xCoordinate, int yCoordinate)
{
boolean marked = false;
if (Character.toString(userBoard[xCoordinate][yCoordinate]).equals("-") == false)
{
marked = true;
}
return marked;
}
public void revealCell(int xCoordinate, int yCoordinate){
int count = 0;
for(int i = 0;i < userBoard.length;i++){
for(int J = 0;J < userBoard[i].length;J++){
if(userBoard[i][J] != '-'){
count = count + 1;
}
}
if(count == 19){
gui.win("you won");
return;
}
}
if(solutionBoard[xCoordinate][yCoordinate] == 'B'){
userBoard[xCoordinate][yCoordinate] = solutionBoard[xCoordinate][yCoordinate];
gui.lose("You lost. Better luck next time!");
return;
}
if(solutionBoard[xCoordinate][yCoordinate] != '0'){
userBoard[xCoordinate][yCoordinate] = solutionBoard[xCoordinate][yCoordinate];
}else{
userBoard[xCoordinate][yCoordinate] = solutionBoard[xCoordinate][yCoordinate];
for(int i = 1; i > -2; i--){
if(xCoordinate-i >= solutionBoard.length || xCoordinate-i < 0)
continue;
for(int z = 1; z > -2; z--){
if(yCoordinate-z >= solutionBoard[xCoordinate].length || yCoordinate-z < 0)
continue;
else if(userBoard[xCoordinate-i][yCoordinate-z] == 'F' || userBoard[xCoordinate-i][yCoordinate-z] != '-')
continue;
else{
revealCell(xCoordinate-i, yCoordinate-z);
}
}
}
}
}
public void unflagCell(int xCoordinate, int yCoordinate){
userBoard[xCoordinate][yCoordinate]='-';
}
public static void main(String[] args){
Board b = new Board();
b.gui = new MsGUI(b);
b.gui.setVisible(true);
}
}
The way you are initializing the solutionBoard is not what you expect it to be.
If you get solutionBoard[0], you're not accessing the first column(which would be consistent with what I think is your understanding), but the first row(first item of the two-dimensional array): {'0','2','B','2','0'}
So if you want to have x for a row index and y for a column index and still keep this "readable" initialization, you'll have to swap the indices whenever you access the array.
But this will only help you with one problem - human readable array assignment in the beginning, but I think you'll regret this decision in the future.
EDIT:
You can have the array initialized as you want and still use readable format like this:
String readableBoard =
"0 2 B 2 0;" +
"0 3 B 3 0;" +
"1 3 B 3 1;" +
"B 1 B B 2;" +
"1 1 2 B 2";
char[][] board = initBoard(readableBoard);
....
private char[][] initBoard(String readableBoard){
char[][] board = new char[5][5];
String[] rows = readableBoard.split(";");
String[] fields = null;
for (int y = 0; y<rows.length;y++){
fields = rows[y].split(" ");
for (int x = 0; x<fields.length; x++){
board[x][y]=fields[x].charAt(0);
}
}
return board;
}
Now when you call
board[2][0]
You'll get 'B'
If you look at your nested for loops, you're printing off the columns instead of what I assume to be the desired rows. Try switching your for loops to iterate over y, then x.
for (int y = 0; y < boundSize; y++){
for(int x = 0; x < boundSize; x++){
System.out.print(" " + Character.toString(board[x][y]));
}
System.out.println("");
}
System.out.println("");