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");
}
}
Related
output
I'm getting these weird symbols while trying to display this char array. Same problem in online compiler too. what to do?
It happened once to me in C++ too. Either it shows nothing or this. It's making me crazy.
package com.avishkar;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String S = "aeroplane";
char[] arr = new char[S.length()];
for (int i = 0; i < S.length(); i++) {
arr[i] = S.charAt(i);
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr));
int count1 = 0, count2 = 0;
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
count2++;
} else {
count1++;
}
}
char[] con = new char[count1];
char[] vow = new char[count2];
int k = 0, l = 0;
for (int i = 0; i < count1; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
vow[l] = x;
l++;
} else {
con[k] = x;
k++;
}
}
System.out.println(Arrays.toString(con));
System.out.println(Arrays.toString(vow));
int x = 0, y = 0;
char[] finArr = new char[count1 + count2];
for (int i = 0; i < finArr.length; i++) {
if (count1 > count2) {
if (i % 2 == 0) {
finArr[i] = con[x];
x++;
} else {
finArr[i] = vow[y];
y++;
}
} else {
if (i % 2 == 0) {
finArr[i] = vow[y];
y++;
} else {
finArr[i] = con[x];
x++;
}
}
}
String ans = "";
for (int i = 0; i < finArr.length; i++) {
ans += finArr[i];
}
if (count1 - count2 > 1 || count2 - count1 > 1) {
System.out.println("-1");
}
System.out.println(ans);
}
}
I modified your code to print out the hexadecimal value of the characters, rather than the characters themselves.
The output looks like this:
0 0 0 0
61 61 65 65 0
61 0 61 0 65 0 65 0 0
Your "unprintable" characters are hexadecimal zero, which is unprintable.
Here's the modified code.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String S = "aeroplane";
char[] arr = new char[S.length()];
for (int i = 0; i < S.length(); i++) {
arr[i] = S.charAt(i);
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr));
int count1 = 0, count2 = 0;
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
count2++;
} else {
count1++;
}
}
char[] con = new char[count1];
char[] vow = new char[count2];
int k = 0, l = 0;
for (int i = 0; i < count1; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
vow[l] = x;
l++;
} else {
con[k] = x;
k++;
}
}
for (char c : con) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(Arrays.toString(con));
for (char c : vow) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(Arrays.toString(vow));
int x = 0, y = 0;
char[] finArr = new char[count1 + count2];
for (int i = 0; i < finArr.length; i++) {
if (count1 > count2) {
if (i % 2 == 0) {
finArr[i] = con[x];
x++;
} else {
finArr[i] = vow[y];
y++;
}
} else {
if (i % 2 == 0) {
finArr[i] = vow[y];
y++;
} else {
finArr[i] = con[x];
x++;
}
}
}
String ans = "";
for (int i = 0; i < finArr.length; i++) {
ans += finArr[i];
}
if (count1 - count2 > 1 || count2 - count1 > 1) {
System.out.println("-1");
}
for (char c : ans.toCharArray()) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(ans);
}
}
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 '';
}
}
Our assignment is to make a simple 'pac-man' game that just eats the trash inside a rectangle. The trash being "*".
My code so far:
public class Sweeper
{
public static void main(String[] args) throws InterruptedException
{
//************************************************************
// Variable set up
int sy = 10, sx= 10; // Box size
int x= 5, y= 5; // Start point
int maxmc = 8; // Max distance moving
char [] [] env = new char[sy][sx];
int right = sx - 2, top = sy - 2, left = sx - (right + 1) , bottom = sy - (top + 1);
//************************************************************
//************************************************************
// Filling the grid with Stars
for(int i=0; i<sy;i++)
{
for(int j =0; j < sx; j++)
{
env[i][j] = '*';
}
}
//************************************************************
int mc = 0, direction = 0, count = (right * top);
// The actual game
while(count != 0)
{
direction = (int)(Math.random() * 3);
// Display
//System.out.println("\n\n\n\n\n");
for(int i = 0; i < sy; i++)
{
for(int j= 0; j< sx; j++)
{
System.out.print(env[i][j]);
}
System.out.println();
}
System.out.println("\n\n\n");
Thread.sleep(700);
System.out.println(direction);
if((x <= right && x >= left && y <= top && y >= bottom))
{
if(env[x][y] == ' ')
{
// RIGHT
if(direction == 0)
{
env[y][x] = '#';
x--;
env[y][x+2] = ' ';
}
// left
else if(direction == 1)
{
env[y][x] = '#';
x++;
env[y][x-2] = ' ';
}
// TOP
else if(direction ==2)
{
env[y][x] = '#';
y--;
env[y+2][x] = ' ';
}
// bottom
else if(direction ==3)
{
env[y][x] = '#';
y++;
env[y-2][x] = ' ';
}
}
else
{
if(direction == 0)
{
env[y][x] = '#';
x--;
env[y][x+2] = ' ';
}
// left
else if(direction == 1)
{
env[y][x] = '#';
x++;
env[y][x-2] = ' ';
}
// TOP
else if(direction ==2)
{
env[y][x] = '#';
y--;
env[y+2][x] = ' ';
}
// bottom
else if(direction ==3)
{
env[y][x] = '#';
y++;
env[y-2][x] = ' ';
}
// Keeps track of the trash
count--;
}
}
}
}
}
My problem:
It copies the '#' and stops moving sometimes.
Im trying to make it move aorund until all the inside 8x8 star symbols are all gone.
Just to clean your code: your moving algorithm is duplicated the (4 if/else statements) . You need to put only count-- in a if(! env[x][y] == ' ') statement.
For your problem: your badly checkin your bounds condition, you do
env[y][x] = '#';
x--;
env[y][x+2] = ' ';
But if x=1, then after the code it's 0, and because you have
if((x <= right && x >= left && y <= top && y >= bottom))
With x=0 and right=0, then it never enter the statement, count cannot change, and it loops infinetly.
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");
}
}
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("");