Define border around 2D array - Java - java

I have an array:
Cell[][] cells = new Cell[width+2][height+2];
Which is filled according to a certain input:
for (int i = 1; i < cells.length-1; i++) {
for (int j = 1; j < cells[i].length-1; j++) {
if (certain input) {
cells[i][j] = new Cell(true);
} else {
cells[i][j] = new Cell(false);
}
}
}
Now I still need to define the border cells which need to become false. I tried this with another for loop but somehow this does not seem to work.
Any help is appreciated!

Don't know if I understand you, but if you want to make a frame for the true cells you should do something like:
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (i== 0 || i == cells.length-1 || j== 0 || j == cells.length-1) {
cells[i][j] = new Cell(false);
}
}
}

Related

Errors in Four in a Row game in Java

I recently completed the code for a Four in a Row Game with 7 columns (represented by i below) and 6 rows (represented by j below), however, I keep getting out of bounds errors and I'm not sure why. If anyone can help spot and fix the errors, that would be awesome. Below is the code I have (the issues lie in the play, isGameOver and winner functions):
package hw4;
public class CFGame {
//state[i][j]= 0 means the i,j slot is empty
//state[i][j]= 1 means the i,j slot has red
//state[i][j]=-1 means the i,j slot has black
private final int[][] state;
private boolean isRedTurn;
{
state = new int[7][6];
for (int i=0; i<7; i++)
for (int j=0; j<6; j++)
state[i][j] = 0;
isRedTurn = true; //red goes first
}
public int[][] getState() {
int[][] ret_arr = new int[7][6];
for (int i=0; i<7; i++)
for (int j=0; j<6; j++)
ret_arr[i][j] = state[i][j];
return ret_arr;
}
public boolean isRedTurn() {
return isRedTurn;
}
public boolean play(int column) {
for(int j = 0; j < state[column].length; j++) {
if(state[column][j] != 0 || state[column][j] < 0 || state[column][j] > 6 ) {
return false;
}
}
return true;
}
public boolean isGameOver() {
for(int j = 0; j < state.length; j++) {
for(int i = 0; i < state[j].length; i++) {
if (state[i][j] != 0) {
return true;
}
}
}
return false;
}
public int winner() {
//Checking horizontal win
for(int j = 0; j < state.length; j++) {
for(int i = 0; i < state[j].length-3; i++) {
if(state[i][j] == state[i+1][j] && state[i][j] == state[i+2][j] &&
state[i][j] == state[i+3][j]) {
return state[i][j];
}
}
}
//Checking vertical win
for(int j = 0; j < state.length-3; j++) {
for(int i = 0; i < state[0].length; i++) {
if(state[i][j] == state[i][j+1] && state[i][j] == state[i][j+2] &&
state[i][j] == state[i][j+3]) {
return state[i][j];
}
}
}
//Checking diagonal(s) win
for(int j = 0; j < state.length - 3; j++) {
for(int i = 0; i < state[j].length - 3; i++) {
if(state[i][j] == state[i+1][j+1] && state[i][j] == state[i+2][j+2] &&
state[i][j] == state[i+3][j+3]) {
return state[i][j];
}
}
}
for(int j = 0; j < state.length - 3; j++) {
for(int i = 3; i <= state[j].length; i++) {
if(state[j][i] == state[j+1][i-1] && state[j][i] == state[j+2][i-2] &&
state[j][i] == state[j-3][i+3]) {
return state[i][j];
}
}
}
return 0;
}
}
To me, the code seems fine but when I run it, it brings up the error.
If you spot any other mistakes, kindly let me know too.
Any help is much appreciated.
You use index j and i differently in different loops. It looks like j should be the index for the first dimension and i is for the second, but you have state[i][j] in some places. That will definitely cause outofbound error because j can go as high as 6 but i is capped at 5 based on your code.

Make a square shape of asterisc around border of 2D Array

I am trying to fill with asterisks only the outside border of a 2D Array I have half of it done, but it seems that I cant get it to fill the last column and the last row in the 2D array.
so far I can do this
and here is my code:
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array.length; j++)
{
if (array[i][j] == array[0][j] || array[i][j] == array[i][0])
{
array[i][j] = "*";
}
}
}
but obviously I want to finish the Square shape around the 2D array, so I tried something like this.
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array.length; j++)
{
if (array[i][j] == array[array.length - 1][j]
|| array[i][j] == array[i][array.length - 1])
{
array[i][j] = "*";
}
}
}
My idea was just to go to the last valid position in the 2D array and simply print the column and the row but it doesn't seem to work. Thanks to all the help I can get, I really appreciate it as I'm a learner in Java.
#Ricki, your line of thinking was right, but what you didn't consider is that array[i][j] == array[array.length - 1][j] doesn't compare the "shell" per say, but the inner value of it, so, even if array[1][1] != array[2][1], if their values are null they are equals.
Try using this code:
int _i = 10;
int _j = 10;
String[][] array = new String[_i][_j];
for (int i = 0; i < _i; i++) {
for (int j = 0; j < _j; j++) {
if(i==0 || j == 0 || i == _i-1|| j == _j-1){
array[i][j] = "*";
}
}
}
What i've done is comparing the first row (i==0), the first column (j==0), the last row (i == _i-1) and the last column (j == _j-1).
And then:
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
you can do something likewise,
public static void main(String[] args) {
int n = 5;
String [][] array = new String[n][n]; // 2-dimension array define...
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if(i == 0 || (i == array.length-1 || j==0 || j==array.length-1)){ // if top,left,right,bottom line then this...
array[i][j] = "*|";
}else{ // if not border line then this...
array[i][j] = "_|";
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("");
}
}
OUTPUT :

Bidimentional Array

Hi all my program consist of an 2 Dimension array,im reading 2 cordinates in a loop and triying to check if those cordinates in the array are alredy been filled with a asterisc,if this is true y want to re-enicialize my array with the default value "-", and if there is not an asterisc in that specified position y want to fill it in with a asterisc,im not sure if im going for the correct aproach.
this is part of my code.
thanks all.
String[][] matrix = new String[5][5];
String asterisc = "*";
String defaultValue = "_";
Scanner sc = new Scanner(System.in);
int a, b;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = defaultValue;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.print(matrix[i][j] + "|");
}
System.out.println();
}
a = 0;
b = 0;
while (a >= 0 && b >= 0 && a < matrix.length && b < matrix.length) {
a = sc.nextInt();
b = sc.nextInt();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[a][b].equals(asterisc)) {
matrix[i][j] = defaultValue;
} else {
matrix[a][b] = asterisc;
}
}
}
}
There are unfortunately many things wrong with your code.
Also you have not explained what your algorithm is trying to do.
In brief, to set all asterisks to defaults, you can do
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if matrix[i][j].equals(asterisc){
matrix[i][j]=defaultValue;
}
}
System.out.println();
}
But
why are you using a while loop?
Why are you using a scanner?
Why are a and b initialised at zero, yet need to be greater than zero for the loop?
Are you really trying to re-initialise your whole array, every time the (a,b) item is asterisc?
I think it is not true.Suppose you have typed "6 6" in the terminal,then the variable a=6,and b=6,which is greater than the array length,and the program will throw a exception.I think the thing you may want to do can follow this codeļ¼š
while(true){
a = sc.nextInt();
b = sc.nextInt();
if(a<0||a>matrix.length||b<0||b>matrix.lenght)
break;
}

Java: Game of Life - issue with neighbours

I'm new to this forum so I hope I'm posting this question in the right way - otherwise, please let me know.
I'm trying to write the code for a simple Game of Life animation in Java, and most of it seems to work as intended.
However, there is a problem with one of the neighbour 'rules' that is supposed to "kill" a cell if it has less than 2 neighbours, meaning that cells can have one or no neighbours and still survive - can be seen here: http://peecee.dk/upload/view/435109. All other rules seem to work fine.
Can anyone help me figure out why it ignores the rule (Live cells are equal to '1', dead to '0'.):
if (this.state[i][j] == 1 &&
liveNeighbours(i, j) > 3 || liveNeighbours(i, j) < 2) {
this.tempState[i][j] = 0;
Thanks a ton in advance!
The code is as follows:
import java.util.*;
public class GameOfLife {
private int[][] state;
private int[][] tempState;
//Constructor that creates n x n grid of randomly placed live cells
public GameOfLife(int n) {
this.state = new int[n+2][n+2];
this.tempState = new int[n+2][n+2];
createRandomBoard(n);
}
//Sets up the initial state
public void createRandomBoard(int n) {
//Creates (n+2) x (n+2) grid of dead cells
for (int i = 0; i < n+2; i++) {
for (int j = 0; j < n+2; j++) {
this.state[i][j] = 0;
}
}
//Creates n x n grid of randomly placed live cells. Live cells are equal to '1', dead to '0'.
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < n + 1; j++) {
int a = (int)Math.round(Math.random());
this.state[i][j] = a;
}
}
drawBoard();
}
//Draws the live cells as dots based on current state
public void drawBoard() {
StdDraw.show(50);
StdDraw.clear();
for (int i = 1; i < this.state.length-2; i++) {
for (int j = 1; j < this.state.length-2; j++) {
StdDraw.setXscale(1,this.state.length-3);
StdDraw.setYscale(1,this.state.length-3);
StdDraw.setPenRadius((double)1/this.state.length);
if (this.state[i][j] == 1) {
StdDraw.point(i, j);
}
}
}
StdDraw.show(50);
}
//Determines which cells live or die in the next state
public void nextState() {
//Copies the state array to a temporary state(array) during killing/reviving
for (int i = 1; i < this.state.length-2; i++) {
for (int j = 1; j < this.state.length-2; j++) {
this.tempState[i][j] = this.state[i][j];
}
}
//Kills cells with more than 3 or less than 2 neighbours and revives dead cells with 3 neighbours
for (int i = 1; i < this.state.length-2; i++) {
for (int j = 1; j < this.state.length-2; j++) {
if (this.state[i][j] == 1 && liveNeighbours(i, j) > 3 || liveNeighbours(i, j) < 2) {
this.tempState[i][j] = 0;
}
else if (this.state[i][j] == 0 && liveNeighbours(i, j) == 3) {
this.tempState[i][j] = 1;
}
}
}
//Copies the modified temporary state array to the original state(array) again
for (int i = 1; i < this.state.length-2; i++) {
for (int j = 1; j < this.state.length-2; j++) {
this.state[i][j] = this.tempState[i][j];
}
}
drawBoard();
}
//Counts the number of live neighbours to a cell
private int liveNeighbours(int x, int y) {
int numLiveNeighbours = 0;
for (int i = x-1; i < x+2; i++) {
for (int j = y-1; j < y+2; j++) {
if (this.state[i][j] == 1) {
numLiveNeighbours++;
}
}
}
numLiveNeighbours --;
return numLiveNeighbours;
}
public String toString() {
return Arrays.deepToString(this.state);
}
public int[][] getState() {
return this.state;
}
}
Your condition doesn't seem to express what you want. You need to change it to:
if (this.state[i][j] == 1 && (liveNeighbours(i, j) > 3 || liveNeighbours(i, j) < 2))
Check operators precedence rules in Java. You were killing those cells being alive and having more than 3 neighbours or those cells with less than two of them.
With this change you will be killing those cells alive and with more than 3 or less than 2 neighbours.
I think your liveNeighbours has a little flaw too: Your are counting (x,y) neighbours and (x,y) itself. You should change it for:
private int liveNeighbours(int x, int y) {
int numLiveNeighbours = 0;
for (int i = x-1; i < x+2; i++) {
for (int j = y-1; j < y+2; j++) {
if (this.state[i][j] == 1 && (x != i || j != y)) {
numLiveNeighbours++;
}
}
}
return numLiveNeighbours;
}

Draw on Java console two squares (one inside of the other)

basically I need to input two numbers and they will be the side size of two squares (drawn one inside of the other, being the inside square positioned in the middle of the biggest square).
I really have no idea how to do this, and the only thing that I was able to come up with was inputing a value and having one drawn square:
package teste;
import java.util.Scanner;
public class Main {
private static Scanner sc;
public static void main(String a[])
{
int size=0;
System.out.print("Enter size: ");
sc = new Scanner(System.in);
size = sc.nextInt();
for(int i=1; i <= size; i++){
for(int j=1; j <= size; j++){
if(i==1 || i==size || j==1 || j==size)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
I know it is not much, but my java skills are limited. Can you guys show a way to do it? I have no idea how to draw the square inside.
Thanks in advance.
The simplest way i see is just make a buffer where you will fill the characters you want to draw in console
// init buffer
char buffer[][] = new char[size][];
for (int i = 0; i < size; i ++) {
buffer[i] = new char[size];
}
// borders of first square
final int sq1Start = 0;
final int sq1End = size-1;
// draw outer square
for(int i = sq1Start; i <= sq1End; i ++){
for (int j = sq1Start; j <= sq1End; j ++) {
if (i == sq1Start || i == sq1End || j == sq1Start || j == sq1End) {
buffer[i][j] = '*';
}
}
}
// borders of second square
final int sq2Start = size / 4;
final int sq2End = size * 3 / 4;
// draw inner square
for (int i = sq2Start; i <= sq2End; i++) {
for (int j = sq2Start; j <= sq2End; j++) {
if (i == sq2Start || i == sq2End || j == sq2Start || j == sq2End) {
buffer[i][j] = '*';
}
}
}
for (int i = 0; i < size; i ++) {
for (int j = 0; j < size; j ++) {
System.out.print(buffer[i][j]);
}
System.out.println();
}
Hope it would be helpful

Categories

Resources