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

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.

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();
        }      
    }  
    
}

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.

Java For Loop Practice

Was doing some Java practices and I got stuck at this particular question, I am given the following code:
public class DistanceSeparator {
public static void main(String[] args) {
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
public static void printSeparatorSequence(int numberOfElements) {
for () {
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
And I am supposed to modify the code using A SINGLE FOR LOOP to show that:
If numberOfElements = 5
1 3 7 13 21
If numberOfElements = 7
1 3 7 13 21 31 43
Each showing an increment of + 2, +4, +6, +8, +10 and +12
The final output is to be this:
1 3 7
1 3 7 13 21
1 3 7 13 21 31 43 57
I just can't seem to get my head around how to get that outcome, and this is after 2hours of trying (yes I am that bad). Any help, please?
edit This was what I had, before deciding to seek help, it's obviously not working.
int j = 0;
for (int i = 1; i <= numberOfElements; i++) {
j = i * 2; // + by how much
int z = i + j; //sum
System.out.print(z + "");
}
edit 2 now I get it, oh my, to think I was so close. Guess I was too cluttered after being stuck for some time. Thanks a ton!
Here is the code to accomplish result you expected.
int current = 1;
for(int i = 0; i < numberOfElements; i++) {
current += i*2;
System.out.print(current + " ");
}
You just need to keep another variable to keep track of the difference (the change), and then constantly update it by the power of 2 of the iteration, i.e. for the first loop only increase it by 2^1, then by 2^2, then 2^3 and so on).
An example of how to achieve that:
for (int i = 0, diff = 0; i < numberOfElements; i++, diff += 2*i) {
System.out.print((1 + diff) + " ");
}
UPDATE: After you've edited your question with your code segment, you can see your problem was with this line:
int z = i + j; //sum
Since both i and j advance with each iteration, you lose your offset (you constantly reset it). You need to keep it static (like in my example: 1), and only update j by 2*i each iteration, otherwise your "base" for calculation is constantly changing and the formula doesn't hold anymore.
In your case, you are regenerating int z everytime the loop is called,
All you have to do is define z outside the loop and instantiate z as 1 and also, you are not retaining the previous values of z so that's why it wasn't working. So it should be z = z + j and put this line below the print statement and you are done.
Here is an snippet of code which would help you my way:
int j = 1;
for(int i=1; i<=numberOfElements; i++) {
System.out.println(j);
j = j + 2*i;
}
And, here is an snippet of code which would help you your way:
int j = 0;
int z = 1;
for (int i = 1; i <= numberOfElements; i++)
{
j = i * 2; // + by how much
System.out.print(z + " ");
z = z + j; //sum
}
Note the trend.
You are adding a multiple of 2 to the previous number to get the next number. The multiple of 2 to be added depends upon the position of the number. For example, to get the 1st number, you add 2 x 0 to 1. To get the 2nd number, you add 2 x 1 to the previous number (that gives 3). To get the 3rd number, you add 2 x 2 to the previous number (that gives 7). To get the 4th number, you add 2 x 3 to the previous number (that gives 13).
To get the number at nth position, you add 2 x (n-1) to the previous number.
Now take a look at the example below, keeping the above explanation in mind.
public static void printSeparatorSequence(int numberOfElements) {
int number = 1;
for (int i = 0; i<numberOfElements;i++) {
number = number + 2 * i;
System.out.print(number);
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
This is the solution of your problem. I have discussed the code by the comment lines given within the code.
public class DistanceSeparator
{
/* Main Method */
public static void main(String[] args)
{
/* printSeparatorSequence Function is Called */
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
/* printSeparatorSequence Function Definition */
public static void printSeparatorSequence(int NumberOfElements)
{
/* variable j is used to get the multiples of
2 by multiplying with variable i within the for loop
and variable sum is used to get the total value */
int j=2,sum=1;
for(int i=0;i<NumberOfElements;i++)
{
sum=sum+(j*i);
/* Here total sum is printed with a space */
System.out.print(sum+" ");
}
/* It is used for new line */
System.out.println();
}
}

How to create an histogram of asteriks from a Java array of number repetitions? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an array with repetitions of numbers and I need to show them in an "histogram" made by "*". The histogram should looks like this:
*
* *
* * *
* * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
1 2 3 4 5 6 7 8 9 10
I have this array
int[] repetition = new int[] {4,6,4,4,6,5,7,4,3,3};
and I was able to print it horizontally like this:
1*****
2******
3****
4****
5******
6*****
7*******
8****
9***
10***
How can I create the vertical histogram?
First you compute the maximum height of the histogram.
max=0;
for(int i: repetition)
if(i>max)
max=i;
Then, you print like this, from top to bottom:
for(j=max;j>=1;j--){ //For each possible height of the histogram.
for(k=0;k<repetition.length;k++) //Check height of each element
if(repetition[k]>=j)
System.out.print("*"); //Print * if the k-th element has at least a height j.
else
System.out.print(" "); //Else, do print blank space
System.out.println(); //Newline after every row.
}
PS: This is just an idea, not a complete working code, and it works only for positive height values!
It sounds like you have code to "bin" the data, effectively creating the histogram. Add some code to track the maximum count across all the bins. So, in your example above, the maximum would be 8 (from bin 7).
Then, set a threshold, starting at that maximum, and counting down to one. On each iteration, print lines with asterisks in the columns corresponding to the bins that meet or exceed the threshold. So on the first line, only column 7 would get an asterisk, because it's the only bin that meets the current threshold of 8. The next line (threshold 7), columns 5 and 7 would get asterisks. And so on.
Hopefully that's enough help to write the code yourself.
Integer is used to use the Collections max function.
public static void main(String[] args) {
Integer[] repetition = new Integer[] { 4, 6, 4, 4, 6, 5, 7, 4, 3, 3 };
int maxValue = Collections.max(Arrays.asList(repetition));
System.out.println("Maximum: " + maxValue);
for (int i = maxValue; i > 0; i--) {
for (int j = 0; j < repetition.length; j++) {
if (repetition[j] >= i) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
for (int j = 0; j < repetition.length; j++) {
System.out.print(" " + (j + 1) + " ");
}
}
I am not going to give you any code, but I can give you an idea to start off of.
For the vertical histogram, even though it looks like it is being printed top to bottom, it's not; you just can't print vertically. Using a loop (the highest value in the array being the starting value, 0 being the sentinel value, and decrementing by 1 every iteration) where every iteration represents a horizontal line on the histogram, you should determine which x-label's asterisk(s) need to be printed on that line, and for those labels that don't have an asterisk on that line, place a space there instead (for formatting).Then, create another loop and use it to list all the x-labels at the bottom.
Hope this helps!
public static final void printHistogram(int[] coll) {
int max = coll[0];
for (int i : coll)
max = i > max ? i : max;
boolean[][] array = new boolean[max][coll.length];
for (int i = coll.length - 1; i >= 0; i--) {
for (int j = 0; j < coll[i]; j++) {
array[j][i] = true;
}
}
for (int i = array.length - 1; i >= 0; i--) {
boolean[] booleans = array[i];
for (boolean b : booleans) {
System.out.print(b ? '*' : ' ');
}
System.out.println();
}
for (int i = 1; i <= array.length; i++) {
System.out.print(i);
}
}
This works as expected.

how to print a number triangle in java

I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)  
{          
System.out.print(i); 
}      
System.out.print("\n");        
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){

Categories

Resources