Learning Java confused by "maze" pattern - java

Ok everyone i'm taking a free course on EDX and I can't get some of the activities earlier In lesson to work so I had to dive head first into this.
The program creates a "zig zag" pattern, the size of which depending on the int numTiles. I am confused by this because running through the program in my head I think it would way work waaay differently. I don't know why it prints 1 for the entire line depending on the numTiles. Wouldn't the program stop at the point? Why don't J and I increase everytime? What case would be the spaces? Do I or J ever go over the int numtiles? How does J ever equal 0 except in the first time it runs? Please help me wrap my head around this.
public class Main {
public static void main(String[] args) {
int numTiles = 8;
for(int i=0; i<numTiles;i++){
for(int j=0; j<numTiles;j++){
if(i%2==0){
System.out.print("1");
}else if ((i-1)%4==0 && j==numTiles-1){
System.out.print("1");
}else if((i+1)%4==0 && j==0){
System.out.print("1");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}

I think your misunderstanding may boil down to vague variable names and difficult-to-read code style. Here's how I would translate the program into a more understandable form:
public class Main {
public static void main(String[] args) {
int rows = 8;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < rows; col++) {
if (row % 2 == 0 ||
row % 4 == 3 && col == 0 ||
row % 4 == 1 && col == rows - 1) {
System.out.print("1");
}
else {
System.out.print(" ");
}
try { Thread.sleep(100); } // for demonstration purposes
catch (Exception e) {}
}
System.out.println();
}
}
}
The outer loop controls the printing of the rows. There will be 8 rows in the output in this case. The inner loop controls printing of the columns (also 8). Cells are printed left to right in each row.
Now, the only question left is for each cell, do we print a "1" or a blank space? The conditional says print a "1" if the row is an even number OR if the row is an odd number and the current column index is at one end or another. Otherwise, print a space.
I also added a Thread.sleep call which will delay printing, allowing you to watch the program run cell by cell. I hope this helps clarify matters for you.

Related

For() loop with constant variable isn't printing any output

The problem is that there is no output happening, not an extra println(). This is odd, because doing this programming without a static SIZE var, it works just fine.
public class SlashFigure2
{
public static final int SIZE = 4;
public static void main(String[] args)
{
for(int i = 1; i <= SIZE; i++)
{
for(int j = 1; j <= 2 * i - (2 * SIZE + 2); j++)
{
System.out.print("\\");
}
for(int j = 1; j <= -4 * i + (-4 * SIZE + 2); j++)
{
System.out.print("!");
}
for(int j = 1; j <= 2 * i - (2 * SIZE + 2); j++)
{
System.out.print("/");
}
System.out.println();
}
}
}
In case anyone needs it, here's what the program prints:
!!!!!!!!!!!!!!
\\!!!!!!!!!!//
\\\\!!!!!!////
\\\\\\!!//////
EDIT: Here's what the site keeps saying is the error
EDIT 2:
The site is practiceit.csu.washington.edu
Here is the question's wording:
Modify your DollarFigure program from the previous exercise to become
a new program called DollarFigure2 that uses a global constant for the
figure's height. (You may want to make loop tables first.) The
previous output used a constant height of 7. The outputs below use a
constant size of 3 (left) and 5 (right)
Here are the outputs below they are talking about
(You must solve this problem using only ONE public static final
constant, not multiple constants; and its value must be used in the
way described in this problem.)
Simply do this:
if (i != SIZE) {
System.out.println();
}
Because i will be equal to SIZE in the last iteration, and you want to skip the println() in that case.
UPDATE
From the comments and the image, it's clear that you're not supposed to define SIZE as a constant, apparently you should be able to pass n as a parameter to your program, it's not a hardcoded value. Check the rules of the "site" you keep referring to, how's the input supposed to be received?
You can make this change in your code to make it work.You should not execute the statement when i is equal to SIZE
if(i<SIZE){
System.out.println();
}
Somewhat Jeopardy to find out the actual problem/quest you want to solve by algorithmically print a specific ASCII-art only denoted by a constant ROW-size (e.g. 4 or 6 as depicted on the attached image).
Tests & sample output
Derived specification
Draw a specific figure varying only in its height:
only single parameter is passed: rows of ASCII-art to draw
figure to draw should resemble a downward-arrow
bordered by double-slashes left and right, i.e. \\ respective //
no border/slashes on the first row
inner/rest of the rows filled with exclamation-marks !!
at least 2 exclamation-marks !! on the inner last row
Java method with single parameter: ROWS
private static void drawAsciiArt(int rows) {
int columns = (rows-1)*4+2;
for(int i = 1; i <= rows; i++) {
int borderSize = (i-1)*2;
int fillSize = columns - borderSize*2;
for(int j = 1; j <= borderSize; j++) {
System.out.print("\\");
}
for(int j = 1; j <= fillSize; j++) {
System.out.print("!");
}
for(int j = 1; j <= borderSize; j++) {
System.out.print("/");
}
if (i < rows) {
System.out.println();
} // if not last row
} // end of row-loop
}
Try this online
Figured it out! It turns out that for both the '\' and '/' characters, I didn't need to use that (x * SIZE + y) formula after all. They both needed the regular formula while the '!' is the only character that needed the SIZE formula
public class SlashFigure2
{
    public static final int SIZE = 4;
//program works no matter what value SIZE holds
    public static void main(String[] args)
    {
        for(int i = 1; i <= SIZE; i++)
        {
            for(int j = 1; j <= 2 * i - 2; j++)
            {
                System.out.print("\\");
            }
            
            //note the SIZE formula in here
            for(int j = 1; j <= -4 * i + (4 * SIZE + 2); j++)
            {
                System.out.print("!");
            }
            
            for(int j = 1; j <= 2 * i - 2; j++)
            {
                System.out.print("/");
            }
            
            System.out.println();
        }      
    }  
    
}

How to loop through an array and get how many zeros there are

I have a 2D array and it's like a maze.
So I loop through the first row to see if there is a zero (This zero is the opening) and then I go down to see if there is another zero below that zero.
The problem is that after the first 2 rows I don't know how I can write code to check left,right or down of that zero and move there and continue until I cannot do so any longer.
import java.util.Scanner;
public class AssignmentTwo
{
//int[rows][columns]
int[][] gasCavern = {{1,1,1,1,1,0,1},
{1,0,0,1,1,0,1},
{1,1,1,0,0,0,1},
{1,1,0,0,1,1,1},
{1,0,1,0,1,0,1},
{1,0,1,0,0,0,1},
{0,0,0,1,1,1,0},
{1,1,1,0,0,0,1}};
int counter = 0;
boolean checked = false;
// forLoop that deals with the first 2 rows.
// First check 1st row for a zero.
// Then check down and increment counter which ultimately shows area.
for(int column = 0; column < gasCavern[0].length; column++)
{
//Checking for opening in 1st row
if(gasCavern[0][column]== 0)
{
counter++;
gasCavern[0][column] = 2;
if(gasCavern[1][column]==0)
{
counter++;
}
}
}
for(int i=1; i<gasCavern.length; i++)
{
for(int j=0; j < gasCavern.length; j++)
{
if(gasCavern[i][j])
{
//Looking left
if(gasCavern[i][j-1]==2)
{
gasCavern[i][j-1]=2;
counter++;
}
//Looking Right
if(gasCavern[i][j+1]==2)
{
gasCavern[i][j+1]=2;
counter++;
}
//Looking up
if(gasCavern[i+1][j]==2)
{
gasCavern[i+1][j]=2;
counter++;
}
//Looking down
if(gasCavern[i-1][j]==2)
{
gasCavern[i-1][j]==2
counter++;
}
}
}
}
public boolean checkedForZeros()
{
//If returning false,go through while loop again
}
}
This is the code I have so far. In case I wasn't clear this is what I want to happen:
http://imgur.com/YOr86xs
I think with a bit more thought you would have got it!
Think about it, all you have to do is check the adjacent elements in the row you are looking at, which are just the columns in each side. Therefore:
[column+1]
Would check the element to the right, and:
[column-1]
Would check the element to the left.
Just be sure you don't accidentally go out of bounds.
EDIT: Let us know how you get on, if you are still struggling, I will provide more code, but try first.
This should work:
for (int x = 0; x < gasCavern.length; x++) {
for (int y = 0; y < gasCavern[x].length; y++) {
int num = gasCavern[x][y];
if (num == 0) {
// if it is a zero
} else {
// if it's not a zero (a one)
}
}
}

Can someone explain to me the 2nd for loop .. I already understand the first one.. thanks

I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.

Create Isoceles Triangle using asterisks and only while loops

I need to create a triangle of at least 5 rows.
I know how to create the top and bottom but I can't figure out the middle part. I don't know how to find the algorithms to express the changes in spaces added to each subsequent row following the first. Can I get hints?
This problem is from my teacher.
You can think as this: suppose you want to paint a triangle of R rows. Then, for example, for R = 5, you would paint something like this:
*
**
***
****
*****
which is isosceles (and also right :)). So, the basic observation is that if the current row has i stars, the previous has i-1 and the next one i+1. So, you can initialize a variable with the current row, which also holds the number of stars to paint. Something like this:
int R = (...) // get this parameter from user or whatever
int r = 1; // current row, and number of stars to paint in the current line
while (r <= R) { // while you haven't painted more than R rows
int i = 1; // counter for painting r stars
while (i <= r) {
System.out.print('*');
++i; // next star
}
System.out.println(); // go to the next row (or line)
}
Hope it helped.
Edit: if your teacher is as skeptical as RealSkeptic down there in the comments, you can use the following observation. Suppose you want to paint a triangle like this:
*
**
***
**
*
That is, an isosceles triangle rotated, such that the len of the equal sides is R. For the example, R = 3. You can see that painting such triangle is like painting a rectangle with 2 different kinds of cells, like the following:
*00 (1 star, 2 zeroes)
**0 (2 stars, 1 zero)
*** (3 stars)
**0 (2 stars, 1 zero)
*00 (1 star, 2 zeroes)
You can note that the sequence grows and then decreases back. You can simulate such behavior with a counter that starts in negative values and runs until the same positive value. The code would be something like:
int R = (...) // get this parameter from user or whatever
int r = -R+1;
while (r <= R-1) {
int i = 1;
int rabs = r;
if (rabs < 0) rabs = -rabs; // take only the positive value
while (i <= R-rabs) {
System.out.print('*');
++i; // next star
}
System.out.println(); // go to the next row (or line)
++r;
}
EDIT2: watching the triangle you added to your question (which you should have added since the very beginning), you can follow the reasoning of the previous edit on the number of stars and spaces per row, and reach to a code like the following:
int R = (...) // get this parameter from user or whatever
int r = 1;
while (r < R) {
int i = 1;
while (i <= R-r) {
System.out.print(" ");
++i;
}
if (r>1) System.out.print("*"); // because there's only 1 star on first row always
i = 1;
while (i <= 2*r-3) { // the amount of spaces you need to paint
System.out.print(" ");
++i;
}
System.out.println("*");
++r;
}
// paint the last row separately
int last = R+R-1;
while (last > 0) {
System.out.print("*");
--last;
}
Good luck.
EDIT3: maybe this approach is more verbose, but easier to understand. The point is to save in variables how many spaces you need to print before the first star, and after the first star, in each row. The code would be like this:
int R = (...) // get this number from user or whatever
int spacesBeforeFirstStar = R-1;
int spacesAfterFirstStar = -1;
int r = 1;
while (r <= R) {
int i = 1;
while (i <= spacesBeforeFirstStar) { // paint the first spaces
System.out.print(" ");
++i;
}
if (r!=1) System.out.print("*"); // if not the first row, paint the first star
i = 1;
while (i <= spacesAfterFirstStar) { // paint the spaces inside the triangle
if (r==R) // if we are in the last row
System.out.print("*"); // we paint stars instead spaces
else
System.out.print(" "); // otherwise, we just paint spaces
++i;
}
System.out.println("*"); // print the second star
spacesBeforeFirstStar -= 1; // in the next row, we paint one space less
spacesAfterFirstStar += 2; // in the next row, we paint two spaces more
++r; // go to the next row
}
Here,
int n = 6;
int row = 0;
int col = 0;
int space = 0;
for(row = 1; row < n; row++) {
for(space = 0; space < n - row; space++) {
System.out.print(" ");
}
for(col = 1; col <= row; col++) {
if(row == (n-1)) {
System.out.print("* ");
} else {
if(col == 1 || col == row) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
It prints out the following:
As you can see it's an equilateral triangle. You can modify the code in the loop using conditional statements so that when it reaches at the time of creating the base for the triangle it will print this
I have left that one for you to ponder upon.

Comparing integers of rows and columns of a 2d array. Sudoku

Hey I'm having trouble getting my code to compare the integers of a given row or column and block to make sure there are no duplicates within those parameters. I don't know if it would be a good idea separating the three contraints in 3 different methods or just trying to attempt to do all at once.
public static rowCheck(int[][] nsudokuBoard) {
for (int i =0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// (nsudokuBoard)
}
}
}
this is my code im starting. before you guys bash on me for not even being able to compile this im stuck on how to compare all the values of a row of the 2d array.
You can compare all the values of the 2d array as shown in the code below:
void validate(final int[][] nsudokuBoard) {
final int width = nsudokuBoard[0].length;
final int depth = nsudokuBoard.length;
for (int i = 0; i < width; i++) {
int j = i;
int reference = nsudokuBoard[i][j];
do {
if (j < width) {
int current = nsudokuBoard[i][j];
if (current == reference) {
// invalid entry found do something
}
}
if (j < depth) {
// note reversed indexes
int current = nsudokuBoard[j][i];
if (current == reference) {
// invalid entry found do something
}
}
++j;
} while ((j >= width) || (j >= depth));
}
}
I haven't tried to compile this code, but it should give you an idea of how to accomplish your task. I would suggest that rather than passing in int[][] sudokuBoard that you should define a class which encapsulates the concept of a SudokuSquare and pass in SudokuSquare[][] , that way your validate method can return a List<SudokuSquare> containing all the offending entries.
I'll show how you might do it for one row, and then you can figure out the rest. I'm assuming your values are 1 through 9 inclusive, and that you don't have any zeroes or any "unfilled entries."
boolean isRowValid(int[][] grid, int row) {
boolean[] seen = new boolean[9];
int row; // chosen somewhere else
for (int col = 0; col < 9; col++) {
if (seen[grid[row][col] - 1]) { // if we've seen this value before in this row
return false; // there is a duplicate, and this is a bad sudoku
}
seen[grid[row][col] - 1] = true; // mark us as having seen this element
}
return true; // we're all good
}
return true; // this row is fine
make a class Cell with fields row,col,block,value; then make a class Matrix with field cells = cell[], fill matrix.
make a class checker with main method Matrix matrix = init(int[][]) and check(matrix), where init(·) fills the matrix.
boolean ok = check(matrix) where check(Matrix) does if(!rowcheck())return false; if(!colcheck()) return false etc;
create some methods like getrows(), getrow(r) and for(Cell cell: matrix.values()) to filter out the ones you want.
a bit tedious but i have done it and it is solid as rock.
As a note, filtering over matrix may seem stupid but computers are fast and the problem is O(1) since it is 9x9.

Categories

Resources