Create Isoceles Triangle using asterisks and only while loops - java

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.

Related

How can you print a staircase out of stars from right to left and not the other way around like it does normally?

So I just have no idea how could i print a staircase from right to left...
Right now the code works but it prints from left.. (this code is in a method)
Here is the code:
int row = 1;
while (row <= size) {
printStars(row);
row = row + 1;
also i was supposed to create a method that would print a number of spaces:
int space= 0;
while (space < amount) {
System.out.print(" ");
space = space + 1;
}
To print your stars in the opposite order, you can simply reverse the logic of your loop such that it begins at size and approaches zero:
int row = size;
while (row > 0) {
printStars(row);
row = row - 1;
}

How do you print a grid of asterisks using multidimensional arrays?

I am new to programming and I have an exercise that's killing me. How can you print a grid (5-by-6) which consists of asterisks alone? [Later on, these asterisks will have to be replaced by letters which are read in with StdIn.readInt() and a switch statement, but for now I at least need to understand how to print the grid]. I would appreciate any help so much!
More specifically, the grid should look like this:
//THIS ISN'T THE CODE; JUST AN ILLUSTRATION OF WHAT SHOULD BE PRINTED
0 1 2 3 4 5
0 * * * * * *
1 * * * * * *
2 * * * * * *
3 * * * * * *
4 * * * * * *
//I AM SUPPOSED TO START WITH SOMETHING LIKE THIS:
public class Grid {
static int X = 6;
static int Y = 7;
public static void main(String[]args) {
int [][] grid = new int [X][Y];
This could have been done in many ways, but this is my way of doing it:
When you want to print a grid, you have to use 2 nested for loops.
Let's see what happens when you use 2 nested for loops:
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
}
}
We start with the first loop:
for i = 0, we will enter the second loop and iterate from 0 to 6.
for i = 1, we will enter the second loop and iterate from 0 to 6.
...
for i = 5, we will enter the second loop and iterate from 0 to 6.
What you should notice is that j will iterate and take values from 0 to 6 with each value of i.
Going back to your question, and comparing it by what i just showed, you should notice that for each line, you are printing 7 values (of a column).
Let's assume i is the number of lines, and j is the index of each value in that line (column).
public static void printGrid() {
for (int i = 0; i < 6; i++) {
System.out.println();
for (int j = 0; j < 7; j++) {
System.out.print("*");
}
}
}
This code prints on each line (i), 7 asterixes (j).
And each time i is incrementing, we are going back to the next line System.out.println(). That's why we put it inside the for loop with i.
In your situation, we have to tweak this code a little bit to be able to print the numbers on the sides, and that space at the top left corner.
The explanation is in the comments in my code.
public class Question_55386466{
static int X = 6;
static int Y = 7;
public static void printGrid() {
System.out.print(" "); // Printing the space on the top left corner
for (int i = 0; i < X; i++) {
if (i > 0) { // Printing the numbers column on the left, taking i>0 to start from the second line (i == 1)
System.out.println(); // Going to the next line after printing the whole line
System.out.print(i - 1);//Printing the numbers of the column. Taking i-1 because we start the count for i == 1 not 0
}
for (int j = 0; j < Y; j++) {
if (i == 0)
System.out.print(j + " ");//Print the first line numbers.
else
System.out.print(" * "); //if the line isn't the first line(i == 0), print the asterixes.
}
}
}
You can always edit the values of X and Y and get the desired result.
And later you can give this method your array as a parameter and print each element instead of the asterixes.

Java Sudoku brute force solver, how does it work?

So you find the code below here. Most of the code I understand, but there is one bit I don't. The place where we create the boolean array called digits and the bit after that 3 * (x / 3).
I think it's used to check if each square in the sudoku has 9 unique numbers as well, but I'm not sure on how I can explain this to let's say someone next to me.
Why do I need the array of boolean here? Can someone explain to me what it is doing and why?
Kind regards!
public int[][] solvePuzzle(int[][] matrix) {
int x, y = 0;
boolean found = false;
// First we check if the matrix contains any zeros.
// If it does we break out of the for loop and continue to solving the puzzle.
for (x = 0; x < 9; x++) {
for (y = 0; y < 9; y++) {
if (matrix[x][y] == 0) {
found = true;
break;
}
}
if (found) {
break;
}
}
// If the puzzle doesn't contain any zeros we return the matrix
// We now know that this is the solved version of the puzzle
if (!found) {
return matrix;
}
boolean digits[] = new boolean[11];
for (int i = 0; i < 9; i++) {
digits[matrix[x][i]] = true;
digits[matrix[i][y]] = true;
}
int boxX = 3 * (x / 3), boxY = 3 * (y / 3);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
digits[matrix[boxX + i][boxY + j]] = true;
}
}
// We loop over all the numbers we have to check if the next number fits in the puzzle
// We update the matrix and check recursively by calling the same function again to check if the puzzle is correct
// If it's not correct we reset the matrix field to 0 and continue with the next number in the for loop
for (int i = 1; i <= 9; i++) {
if (!digits[i]) {
matrix[x][y] = i;
if (solvePuzzle(matrix) != null) {
return matrix;
}
matrix[x][y] = 0;
}
}
// The puzzle can't be solved so we return null
return null;
}
I have added some explanation as comments inline:
//we need to know what digits are we still allowed to use
//(not used in this row, not used in this column, not used in
//the same 3x3 "sub-box")
boolean digits[] = new boolean[11];
//so we run through the rows/coumns around the place (x,y)
//we want to fill in this iteration
for (int i = 0; i < 9; i++) {
//take a used number from the row of x (matrix[x][i]) and mark it
// as used
digits[matrix[x][i]] = true;
//take a used number from the column of y (matrix[i][y]) and mark it
// as used
digits[matrix[i][y]] = true;
}
//find the top-left corner of the sub-box for the position (x,y) we
//want to fill in
//example: x is 8 -> 3 * 8/3 -> 6, so we start from 6
int boxX = 3 * (x / 3), boxY = 3 * (y / 3);
//iterate through the sub-box horizontally and vertically
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//take a used number from the sub-box and mark it
// as used
digits[matrix[boxX + i][boxY + j]] = true;
}
}
There seem to be two issues you are unclear on:
The boolean array - this array is used to track which digits have been used already on a specific row or column. So imagine a row of tick boxes each with a digit written next to it (the array index) - these boxes are checked or unchecked to show a digit has been used or not.
The expressions 3* (x/3) and 3 * (y/3) - what you need to remember here is that this is integer division (that means the result of the division is always rounded down to an integer. For example if x=1 then 3 (x/3) is 3 (1/3) is 3 * (0) =0 (whereas if this was float division the result would be 3*(0.3333)=1. So these maths expressions essentially change you number to the next lowest multiple of three - that is 1 -> 0, 2 -> 0, 3 -> 3, 4 -> 3 etc.

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.

JOptionPane.showmessagedialog

So i have to write a DrawKwin.java which will print the letter K with little stars(*).
The user gives an integer parameter, if the parameter is less than 4 or more than 30 the program will terminate.
With the parameter, the program will create as many lines as the parameter trying to print the letter K.
For example if the user types the number 6 , the program will print 6 lines trying to create the letter K.The input will be from a input panel with and the letter K will be printed in an output panel with joptionpane.showmessagedialog().
Here is the code without the output panel code:
package Askisi_A1;
import javax.swing.JOptionPane;
class DrawKwin {
public static void main(String[] L) {
int line=Integer.parseInt(L[0]); // make L an integer.
if(line <= 4)
{
System.out.println("Program end, wrong argument!");
System.exit(0);
}
else if(line >= 30)
{
System.out.println("Program end, wrong argument!");
System.exit(0);
}
do
{
int mid=line/2; // find the middle.
int gap=0; // 'gap' is for the gap between the stars .
for(int i=0;i<line;i++) //loop for the creation of letter K.
{
if(i==0) gap=mid;
if(i<mid) // if it is before the middle of letter K, start printing stars and gaps but start with gap=middle and the decrease the number of gaps as you change lines.
{
System.out.print("*");
for(int j=gap;j>0;j--) // placement of gaps between the stars.
{
System.out.print(" ");
}
System.out.println("*");
gap--;
}
else if(i==mid && i!=0) // if it is in the middle of letter K, it will print only one star.
{
System.out.println("*");
gap=1;
}
else // if it is past the middle section of letter K, it will continue printing gaps but now the gaps start from 0 and keep increasing at each line.
{
System.out.print("*");
for(int j=0;j<gap;j++) // placement of gaps between the stars.
{
System.out.print(" ");
}
System.out.println("*");
gap++;
}
}
line = Integer.parseInt(JOptionPane.showInputDialog( "Give me a number ",4)); // input from input panel.
}while(line>=4 && line<=30);
}
}
So , if the user gives the number 5 as an input, the output should be like this:
* *
* *
*
* *
* *
but i need this to be printed in an output panel with the help of joptionpane.showmessagedialog().
Can anybody help me please?
Sorry if my English is bad.
My deadline is in Monday.
Try something like this:
do {
int mid = line / 2; // find the middle.
int gap = 0; // 'gap' is for the gap between the stars .
for (int i = 0; i < line; i++) // loop for the creation of letter K.
{
if (i == 0)
gap = mid;
if (i < mid) // if it is before the middle of letter K, start
// printing stars and gaps but start with
// gap=middle and the decrease the number of
// gaps as you change lines.
{
output += "*";
for (int j = gap; j > 0; j--) // placement of gaps between
// the stars.
{
output += " ";
}
output += "*\n";
gap--;
} else if (i == mid && i != 0) // if it is in the middle of
// letter K, it will print only
// one star.
{
output += "*\n";
gap = 1;
} else // if it is past the middle section of letter K, it will
// continue printing gaps but now the gaps start from 0
// and keep increasing at each line.
{
output += "*";
for (int j = 0; j < gap; j++) // placement of gaps between
// the stars.
{
output += " ";
}
output += "*\n";
gap++;
}
}
JOptionPane.showMessageDialog(null, output);
line = Integer.parseInt(JOptionPane.showInputDialog(
"Give me a number ", 4)); // input from input panel.
output = "";
} while (line >= 4 && line <= 30);
Build your output string then showMessageDialog with output string.
Create a String at the beginning, eg.
String kLetter = "";
After every:
System.out.print("*");
add
kLetter += "*";
System.out.print(" ");
add
kLetter += " ";
System.out.println("*");
add
kLetter += "*\n";
then use
JOptionPane.showInputDialog(result, null);
to show result in dialog and remember to set result to empty string after you show it in dialog.
result = "";

Categories

Resources