Printing rectangle in java (there is hole in center) - java

I want create a rectangle which has hole in the middle. How can I import wallThick :) I define width, height, wallThick but I just write a rectangle. I can't press any hole. Could you help me please... Thanks for all...
if (width <= 0 || height <= 0 || wallThick <= 0)
{
System.out.println("Invalid value! Please enter positive integer.");
}else {
for ( y = 1; y <= height; y++)
{
for(x = 1; x <= width; x++)
{
System.out.print("*");
}
System.out.println();
}
what I want to do

Simplest solution: calculate the start and end "coordinates" of the hole. If you are within the hole coordinates, print a blank space.
int holeStartRow = wallThick + 1;
int holeStartCol = wallThick + 1;
int holeEndRow = height - wallThick;
int holeEndCol = width - wallThick;
Check if you're within the hole using:
if (y >= holeStartRow && y <= holeEndRow && x >=holeStartCol && x <= holeEndCol)
Sample code: here

Related

Counting (8 possible) neighbours in 2D array in conways Game Of Life

I have to count how many "alive" (in this case a char: 'O') neigbours each single cell has. Every cell has 8 neighbours. (It is for "The Game Of Life" from Conway)
"As you can notice, each cell has eight neighbors. We consider the universe to be periodic: border cells also have eight neighbors. For example: Neighbours from a "normal" cell
If cell is right-border, its right (east) neighbor is leftmost cell in the same row.
If cell is bottom-border, its bottom (south) neighbor is topmost cell in the same column.
Corner cells use both solutions." When a cell is border and when a cell is a top corner
The links are visualizations to how to check the cells in cases of "exceptions".
I found this on the internet:
for (int x = -1; x <= 1; x += 1) {
for (int y = -1; y <= 1; y += 1) {
int r = i + y;
int c = j + x;
if (r >= 0 && r < n && c >= 0 && c < n
&& !(y == 0 && x == 0)
&& currentUniverse[i][j] == 'O') {
neighbours++;
}
However that did not seem to work...
I can not come up with a tidy and most of all smart/handy/short piece of code to check how many alive neighbours a cell at a position (let's say currentUniverse[i][j]) has...
Has anyone suggestions, tips or some other help?
Give this one a shot. I am using n as the size of the array (assumes in square).
int n = 4;
System.out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int neighbours = 0;
for (int x = -1; x <= 1; x += 1) {
for (int y = -1; y <= 1; y += 1) {
if (!(y == 0 && x == 0)) {
int r = i + y;
int c = j + x;
//normalize
if (r < 0) r = n - 1;
else if (r == n) r = 0;
if (c < 0) c = n - 1;
else if (c == n) c = 0;
if (currentUniverse[r][c] == 0)
neighbours++;
}
}
}
System.out.print("\t" + neighbours);
}
System.out.println();
}

Java 2D array (rectangular matrix) sum path of diagonal moves until you hit a wall, repeat until you hit a corner

I need help with the following problem, I've been stuck on it for 2 whole days.
"I am given the numbers a and b. They form a matrix of the powers of 2. You start from the top left corner of the matrix and go with diagonal moves, until you hit a wall. When a wall is hit, you change direction. You do this, until the direction cannot be changed anymore, i.e. you hit a corner. Find the sum of this path."
So far I created the matrix, filled it with numbers and created 2 booleans for 1.when you hit a corner and 2. when you hit a wall.
I had several ideas how to continue, but none worked out.
for (int row = 0; row < a; row++) {
for (int col = 0; col < b; col++) {
boolean cornerHit = (row == 0 && col == 0) || (row == 0 && col == b - 1) ||
(row == a - 1 && col == b - 1) || (row == a - 1 && col == 0);
boolean hitWall = (row == 0 && (col > 0 && col < b - 1)) ||
(col == 0 && (row > 0 && row < a - 1)) ||
(row == a - 1 && (col > 0 && col < b - 1)) ||
(col == b - 1 && (row > 0 && row < a - 1));
Example: if a=3 and b=4.
here is what the matrix and the diagonal movement looks like for a =3, b=4
The path will be 1 4 16 16 4 4 4 and the sum 49.
Please help! :))
The idea is quite simple.
In essence you should walk until you reach a corner. That is a do/while construct.
We start in top left corner, so our start position is posx=0 and posy=0.
In every step we should move one(1) to the right and one down(1) so in x direction we have a deltax=1 and in the
y direction a deltay=1 for every move.
If a wall is hit we should change direction.
A wall in y direction is hit if posy=0(top) or posy is size-1(botom column) in that case the deltay changes its sign: deltay = -deltay.
Same for x: A wall in x direction is hit if posx=0(left) or posx is size-1(rightmost column) in that case the deltax changes its sign: deltax = -deltax.
For simplicity i did the sizex-1 and sizey-1 right at the the beginning(sizex--; sizey--;) so the test just checks for size.
This should stop when we hit a corner, that is when we hit walls in y and x direction.
I added a boolean that prints the individual steps if set to true.
[Maybe you want to add an additional check for invalid rectangles like diagonalWalk(-1,-1)]
public static int diagonalWalk(int sizex, int sizey, boolean showSteps) {
int posx = 0;
int posy = 0;
int sum = 1;
int deltay = 1;
int deltax = 1;
sizex--;//valid cols are: 0 - sizex-1
sizey--;//valid rows are: 0 - sizey-1
if (showSteps) {
System.out.println("At: 0/0:1");
}
do {
posx += deltax;
posy += deltay;
sum += Math.pow(2, posx) * Math.pow(2, posy);
if (showSteps) {
System.out.println("At: " + posy + "/" + posx + ":" + Math.pow(2, posx) * Math.pow(2, posy));
}
//wallhit left or right
if (posx == 0 || posx >= sizex) {
deltax = -deltax;
}
//wallhit top or bottom
if (posy == 0 || posy >= sizey) {
deltay = -deltay;
}
}while(!((posx == 0 || posx >= sizex) && (posy == 0 || posy >= sizey)));
return sum;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int sum = diagonalWalk(3,4, true);
System.out.println("result is:" + sum);
}
example run:
At: 0/0:1
At: 1/1:4.0
At: 2/2:16.0
At: 3/1:16.0
At: 2/0:4.0
At: 1/1:4.0
At: 0/2:4.0
result is:49

Splitting into Quandrants

I am trying to split my grid into four quadrants, but I keep getting errors. Basically, I am trying to say that my x coordinates are between 0 and 50 and same with my y coordinates.
Then from there, I want to split the grid with my x and y coordinates. My second x in the for code is saying I need to create a method(int,boolean). And all my integers after the returns have errors as well. I am brand new to Java, so any help or insight would be awesome!
GridValueLayer habitat = new GridValueLayer("habitat", 0.00, true, 50, 50);
context.addValueLayer(habitat);{
for (int x = 0; x >= 0, x <= 50){
for (int y = 0; y >= 0; y <= 50){
if(x > 0 && y > 0)
return 1;
else if(x < 0 && y > 0)
return 2;
else if(x < 0 && y < 0)
return 3;
else if (x<0 && y >0)
return 4;
}
}
First of all, there is no purpose in having the for loop because once you do return 1;, or any return, the whole method stops. What you can do is simply output the results there instead of doing return, or populate an object in an arraylist with the x and y coordinates. In any case, remove the return and output instead and it should work.
I am not certain what the errors are (or exactly what you want the code to do), but I don't think the code you have there will compile. The for loop syntax is an initial condition, when to stop, and an increment separated by semi-colons. For the increment you gave a condition. You also left out a semi-colon and have an extra curly bracket by addValueLayer. I still don't think this code will do what you want it to but this is a place to try to work from.
GridValueLayer habitat = new GridValueLayer("habitat", 0.00, true, 50, 50);
context.addValueLayer(habitat);
for (int x = 0; x >= 0; x++) {
for (int y = 0; y >= 0; y++) {
if(x > 0 && y > 0)
return 1;
else if(x < 0 && y > 0)
return 2;
else if(x < 0 && y < 0)
return 3;
else if (x<0 && y >0)
return 4;
}
}

Drawing a sqaure on an axis in Java

I'm currently trying to write a program that draws a sqaure.
The user will enter the size (in the length of the sides), the x-coordinate, and the y-coordinate of the bottom-left corner of the square on the grid as command-line parameters to program, in that order.
So an input of "run Question2Square 5 1 1"
draws a square of side length 5 whose bottom left corner is at the position (1, 1).
I've spent a few hours trying to just get the axes to show up correctly. I'm not even on the square yet.
My current code I have is this, but it's wrong:
import java.util.Scanner;
public class Question2square {
public static void main(String[] args) {
// Axis variables
int yAxismin = 0;
int yAxismax = 15;
int xAxismin = 0;
int xAxismax = 15;
//Loop through all coordinates on plane using for loops
for(int y = yAxismin; y >= yAxismin; y++)
{
for(int x = xAxismin; x >= xAxismin; x++)
{
//Draw the axis
if (Axis(x,y) != "") {
System.out.print(Axis (x,y));
}
}
System.out.println("");
}
}
// This method draws the 15x15 axis
public static String Axis(int x, int y)
{
// Each if and else if statement dictates what symbol needs to go where for the axes
// If there is nothing to be drawn, there will simply be a blank space
if (x == 15 && y== 0) return ">";
else if(x == 0 && y == 15) return "^";
else if (x == 0 && y == 0 )return ".";
else if(x == 0 && y >= 0) return "|";
else if(x >= 0 && y==0) return "-";
else return "";
}
}
All that does is run an infinite loop of '-' and I don't know exactly what's wrong.
Also, I need to figure out how I can extend the axes in either direction should an input that is greater than the 15x15 axes is entered.
If anyone could coach me through this, I would really appreciate it. I'm not asking for it to be done for me. I really want to figure this out but I'm a bit stuck right now and very frustrated.
Thanks in advance for any help!
Presumably you want to loop from yAxismin to yAxismax (and ditto for x)? Try
for(int y = yAxismin; y <= yAxismax; y++)
{
for(int x = xAxismin; x <= xAxismax; x++)
{
As you have it, the loop for(int y = yAxismin; y >= yAxismin; y++) will just go on for a very very long time. This as your expression says "start at yAxismin; loop while y is more than yAxismin; and on each iteration add one to y". You need it to stop when y reaches yAxismax.
Also, don't compare strings with == and !=. Use s1.equals(s2). You make this mistake on the line
if (Axis(x,y) != "") {
which should be
if (!Axis(x, y).equals("")) {
To extend the axes, just pass the limits to the Axis function:
public static String Axis(int x, int y, int maxX, int maxY)
{
if (x == maxX && y== 0) return ">";
else if(x == 0 && y == maxY) return "^";
else if (x == 0 && y == 0 )return ".";
else if(x == 0 && y >= 0) return "|";
else if(x >= 0 && y==0) return "-";
else return "";
}
...
// call it with
String drawThis = Axis(x, y, xAxismax, yAxismax);

Java minesweeper method to add numbers around bombs not working right

I wrote this method for my java minesweeper game, it is supposed to check spots surrounding a set of coordinates and then calculate how many bombs are near by.
public void numberMines(){
int count = 0;
int x = 0;
int y = 0;
int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
xMin = 0;
}
if (y == 0){
yMin = 0; //these restrictions take care of the spots in the edges
}
if (x == rows){
xMax = rows;
}
if (y == columns){
yMax = columns;
}
//first 2 loops go through every spot on the board
for (x=0; x<rows; x++){
for (y=0; y<columns; y++){
//if the spot selected is not a bomb, for loops check spaces surrounding it
if (mineBoard[x][y] != bomb){
for (int i = xMin; i <=xMax; i++){
for (int j = yMin; j <=yMax; j++){
if (mineBoard[i][j] == bomb){
count++;
}
}
}
}
if (count > 0){ //converts them characters
mineBoard[x][y] = (char)(count + '0');
count = 0;
}
}
}
}
Every time I run this method it returns 3,2,1, or empty so it does count how many bombs are around, but for some reason it is over looping and returning the same thing for every spot that is not a bomb after the first one. I really cant see where I messed up, please help!
Move this block of code:
int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
xMin = 0;
}
if (y == 0){
yMin = 0; //these restrictions take care of the spots in the edges
}
if (x == rows){
xMax = rows;
}
if (y == columns){
yMax = columns;
}
Inside of your for loops:
for (x=0; x<rows; x++){
for (y=0; y<columns; y++){
//Insert code here <---
Because at the moment, you're doing these calculations once, for x=0, y=0.
The code would probably also look cleaner if you moved the setting of count to 0 just before the i,j, loops, and not having it done once before all loops start, and again inside the conditional that displays the result.
Based on your comment - I think your valid indexes range from 0..(rows-1) and 0..(columns-1) - so you have a fencepost error also. Modify these lines:
if (x == rows-1){
xMax = rows-1;
}
if (y == columns-1){
yMax = columns-1;
}
But still have this entire block inside of your x/y loops. You don't get the out of bounds error when they're outside because you never calculate xMax and yMax when x and y are at their maximum values.
Avoid to declare all variables at the beginning of a method, better declare them close to when they are used. To fix your problem, you need to compute count, xMin, xMax, yMin and yMax in the loops like this:
public void numberMines(){
//first 2 loops go through every spot on the board
for (int x=0; x<rows; x++){
for (int y=0; y<columns; y++){
int count = 0;
//if the spot selected is not a bomb, for loops check spaces surrounding it
if (mineBoard[x][y] != bomb){
for (int i = (x == 0 ? 0 : x-1); i <= (x == rows ? rows : x+1); i++){
for (int j = (y == 0 ? 0 : y-1); j <= (y == rows ? rows : y+1); j++){
if (mineBoard[i][j] == bomb){
count++;
}
}
}
}
if (count > 0){ //converts them characters
mineBoard[x][y] = (char)(count + '0');
}
}
}
}
I have inlined the boundary checks, which is not necessary, but makes the code shorter to present here.

Categories

Resources