The following code gives me the results but I want to make it more simple so i can learn logic of different scenario
public class Pyramid {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int x = 0; x < 5 - i; x++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
But now i want to make a triangle without inner stars and i am not getting a logic i am trying and thinking for hours i don't want full coding i just want a logic explanation so i can make it by my self it feels good
You want to print the first and last star in each row, so you need to check if k is the first or last value in your loop. Here's pseudocode:
for (int k = 0; k <= i; k++) {
[if k is first or last possible value]
[print star]
[else]
[print space]
}
Related
My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.
Thanks for taking the time to check out my question. I have to write some code in Dr. Java that takes in a word and then prints it out in a specific pattern. Basically here are some examples:
Input: fishy
Output: f
fifi
fisfisfis
fishfishfishfish
fishyfishyfishyfishyfishy
Basically, I'm just adding another character to the previous one and printing it out that many number of times.
Here is my attempt at my solution:
String wordcopy = word;
int size = wordcopy.length();
for (int i=1; i<=size; i+=1)
{
for (int j=0; j<i; j++)
{
System.out.print(word.substring(0,j+1));
}
System.out.println("");
}}
I have already set up my parameters so that's fine. The only thing I seem to be missing is the method itself that prints out what it's supposed to. Can anyone please help me with this problem and how I can go from here?
Thanks!
Replace word.substring(0,j+1) with word.substring(0,i):
String wordcopy = word;
int size = wordcopy.length();
for (int i = 1; i <= size; i += 1) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
There are some cleanup things you can do. For instance, this code yields the same result:
for (int i = 1; i <= word.length(); i++) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
I am making the Conway's Game of Life like almost every other beginner. The main problem I have is I have no clue how to implement the rules for the game, which are :a dead cell with exactly three live neighbors becomes alive, a live cell with exactly one live neighbor becomes dead, and a live cell with more than three live neighbors becomes dead. I've never manipulated a matrix before so I do not have any idea where to start. The class I'm in does not allow us to use non-static methods yet, and also we cannot use the java libraries. This is currently what I have:
public class Life {
public static boolean[][] origin(int a) {
boolean[][] randomMatrix = new boolean [a][a];
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
randomMatrix[i][j] = StdRandom.bernoulli();
}
}
return randomMatrix;
}
public static void print(boolean[][] a) {
int N = a.length;
StdOut.println(N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (a[i][j]) StdOut.print("1 ");
else StdOut.print("0 ");
}
StdOut.println();
}
}
public static void show(boolean[][] a, boolean which) {
int N = a.length;
StdDraw.setXscale(0, N-1);
StdDraw.setYscale(0, N-1);
double r = .5;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, N-i-1, r);
}
}
}
}
public static void main(String[] args) {
int a = 5;
boolean[][] b = origin(a);
int gens = 3;
for (int i = 0; i < gens; i++) {
System.out.println("Generation " + i + ":");
print(b);
show(b, true);
}
}
}
The output I'm receiving right now is what I need for the initial generation of the game. I think I need a new array to store the new generations, and maybe some if and else statements to check if the cells are alive or dead. Any help is appreciated.
HINTS
Recently I completed this example. So the right structure is:
Required 2 dimension arrays ("current" & "next")
Initialize "current" with random values
print "current"
Copy & Calculate each cell of the next generation in array "next"
After calculation, update the "current" array. Use function to update each cell
Set "current" with "next" generation values
Print "current" and go to step 4
Warning!!
Use different formula to check the cells that are on the edges.
So I'm working on for loops and nested for loops. So I need to stick to these as my main functions.
I've gotten stuck on one question. I can think of the logic of how I'd solve it...but I can't figure how I'd do it with for loops/nested for loops.
I've got to print Ascii codes in rows of 10
Example:
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
(from 32-122)
Here's my code so far:
public class chars{
public static void main(String[]args){
for( int j = 32; j < 122; j++){
System.out.print((char)j);
//Once above loop is performed 10*...execute a new line..using a for loop..??
System.out.println();
}
}
}
You're outer loop should control what row you're on, and the inner loop what column. Thus, just the outer loop looks like this (there are 9 rows):
for (int i = 1; i <= 9; i++)
{
System.out.println("");
}
This will print 9 newlines, giving you the 9 rows.
Now, your column logic goes inside, but before the println.
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
char print = (char)((i * 10) + 32 + j);
System.out.print(print);
}
System.out.println("");
}
This utilizes a small math trick to generate the numbers of the sequence. Row 1 = 32 to 41, 2 = 42 to 51, etc.
Note also that this is slightly more verbose than other possible answers because I used nested loops like you asked.
A straight forward approach could be to use an if statement as QuakeCore suggested. the code would come to look something like the following:
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char)j);
if (j % 10 == 1) {
System.out.println();
}
}
}
This leaves for some ugly code when working with the Modulus function in the if condition. The reason for it is that we are starting with the number 32 and incrementing from their, thus we get j % 10 == 1 instead of something nicer such as j % 10 == 0.
But, your question states you wish to solve it with For loop inside a for loop, making me think it's a school task. This can be solved by looking at for loops as functions to be performed within the 2D space. Such that the first for loop is handling the rows, while the inner for loop is handling columns (or y and x space respectively). From this we can solve the problem as follows:
public static void main(String[] args) {
// Increment row/counter by 10
for (int row = 32; row < 122; row += 10) {
for (int col = 0; col < 10; col++) {
System.out.print((char)(row + col));
}
System.out.println();
}
}
The syntax for a for loop is:
for ( initialization ; termination condition ; increment ) body
However, each of those items in italics above is optional. The initialization and increment parts can have multiple components, separated by a comma.
Since you know the total number of characters is a multiple of 10, here's what I would do:
public static void main(String[]args){
for( int j = 32; j < 122; /* don't increment j here */){
// print 10 chars per line
for (int col=0; col<10; col++, j++ /* increment j here instead */) {
System.out.print((char)j);
}
System.out.println();
}
}
Note that if the total number of characters wasn't a multiple of 10, then the inner loop might print some extras, since the outer loop's condition is only checked once every 10 characters.
This will print each char 10 times in a row ( with nested for loops ):
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
// print 10 times the same char in the same line
for (int i=0;i<=10;i++){
System.out.print((char) j);
}
// after 10 char : goto next line
System.out.println();
}
}
do it with for loops/nested for loops
Try this-
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char) j);
if((j-32)%10==0){
System.out.println();
}
}
}
Here the inner condition will take care of changing line when you have printed 10 values
If you must use nested loops, then maybe something like this would work:
int lineLength = 10;
int lineCount = (122 - 32) / lineLength;
for (int line = 0; line < lineCount; line++) {
for (int column = 0; column < lineLength; column++) {
int index = (line * lineLength) + column;
System.out.print((char)(32 + index) + " ");
}
System.out.println();
}
I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.