I'm pretty new to Java, just started learning it. I've got an array of numbers, with array length origArraySize:
29.50 10.80 16.40 87.80 12.20 63.70 13.90 25.00 77.40 97.40
I'm trying to arrange them in this format:
29.50
10.80 16.40
87.80 12.20 63.70
13.90 25.00 77.40 97.40
While I've seen similar half Pyramid questions, i just can't seem to figure out how to implement an array to print the numbers. Here's what I got so far, just a method of class rn:
public String toString() {
String t = "";
for (int i = 0; i < this.origArraySize; i++) {
t += String.format("%8.2f", array[i]);
for (int j = 0; j < i; j++) {
System.out.println(t + "\n");
}
}
}
I know it includes nested for loops but I just can't seem to get it. The method toString() has to return String value, and I'm not sure how to implement that at the end either, but for now I tried with t.
You do not want an inner loop, you just need a couple of counters
double arr[] = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};
int loop = 0;
int printAtNum = 0;
for (double d : arr) {
System.out.printf("%8.2f", d); // always print
if (loop == printAtNum) {
System.out.println(); // only print if loop is equal
// to incremented counter
loop = 0; // reset
printAtNum++; // increment
} else {
loop++;
}
}
output
29.50
10.80 16.40
87.80 12.20 63.70
13.90 25.00 77.40 97.40
You can use two nested for loops. The internal action is to print and increment a single value:
public static void main(String[] args) {
double[] arr = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};
printHalfPyramid(arr);
}
public static void printHalfPyramid(double[] arr) {
int i = 0; // counter, index of an element in an array
for (int row = 1; row < Integer.MAX_VALUE; row++) {
for (int el = 0; el < row; el++) {
// print a number and increment a counter
System.out.print(arr[i++] + " ");
// if the last element
if (i == arr.length) return;
}
// line break, next row
System.out.println();
}
}
Output:
29.5
10.8 16.4
87.8 12.2 63.7
13.9 25.0 77.4 97.4
Related
I have assignment where I have to print and fill an array consisting of 50 indices with random integers then print the values out. Then below that print a list of the numbers in the reverse index with a histogram next to each value. Im supposed to use a nested for loop to solve this and only could get the first section of the problem so far. This is my first time using stackoverflow and I am not expecting an upright answer but if someone could help me understand nested for loops a little more, it would be greatly appreciated.
public static void main(String[] args) {
Random ranGen = new Random();
int[] ranArray = new int [SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for(int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
for(int j = 0; j < ranArray[i]; j++) {
System.out.println("Histrogram");
System.out.println(ranArray[i] );
}
}
}
}
How the output of the code should look like
For the second section, you can iterate on each random number again and for each number, print it with System.out.printf("%-5d", number) ("%-5d" pads the number with spaces to the right) and have a nested loop from 0 to number-1 and print the start with System.out.print(stars).
public static void main(String[] args) {
int SIZE = 5;
Random ranGen = new Random();
int[] ranArray = new int[SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for (int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
}
System.out.println("-------------------------");
System.out.println("Histograms:");
for (int i = ranArray.length - 1; i >= 0; i--) {
System.out.printf("%-5d", ranArray[i]);
for (int j=0; j<ranArray[i]; j++) {
System.out.print(stars);
}
System.out.println();
}
}
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.
I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}
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.
How can I pull the first column from my 2D array? I am initialising my array in a method like this
//Initialise the array with the values from the file
public static float[][] data(float[][] data, Scanner scan){
int count = 0;
for (int i=0;i<data.length;i++){
for (int j=0;j<data[0].length;j++){
count++;
if(count<data.length*data[0].length){
for(int k=0;k<2; k++){
data[i][j] = (float) IOUtil.skipToDouble(scan);
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
}
return data;
}
This is the contents of my test file. (Please bare in mind the file could be any length)
13.97 2.2
12.05 1.9
9.99 1.5
8.0 1.3
6.0 0.9
4.0 0.6
2.0 0.3
0.0 0.0
-2.0 -0.3
-4.0 -0.6
-6.02 -0.9
-8.0 -1.3
-9.99 -1.6
-12.03 -1.9
-13.98 -2.2
on the terminal but the problem is when I try to call the left column I am getting the right column. I am not sure if this is because the values on the right are the only ones getting stored or not.
//should print x but actually prints y
public static void printX(float[][] data){
for (int i=0;i<data.length;i++){
for (int j=0;j<data[0].length;j++){
System.out.println(data[i][j]);
}
}
}
which outputs
2.2
1.9
1.5
1.3
0.9
0.6
0.3
0.0
-0.3
-0.6
-0.9
-1.3
-1.6
-1.9
-2.2
0.0
Can anyone clarify how I could best get the data on the left hand column from the 2D array ? Or if there is some other method for achieving this sort of thing?
You need to use the debugger on you IDE and step through your code to see exactly what is going on. The short answer to me looks like you are clobbering the same field with read data twice for k=0 and k=1.
EDIT
Also in your update, I think you are looking for this in your second print loop (not that it matters, could just as easily be 2, but this is better IMO):
for (int j=0;j<data[i].length;j++){
EDIT Here is the code I think you want explicitly:
//Only print X
public static void printX(float[][] data){
for (int i=0;i<data.length;i++){
System.out.println(data[i][0]);
}
}
//Only print Y
public static void printY(float[][] data){
for (int i=0;i<data.length;i++){
System.out.println(data[i][1]);
}
}
//Print both
public static void printBoth(float[][] data){
for (int i=0;i<data.length;i++){
System.out.println(data[i][0] + ", " + data[i][1]);
}
}
//Print any number in array:
public static void printAll(float[][] data){
for (int i=0;i<data.length;i++){
for (int j=0;j<data[i].length;j++){
System.out.print(data[i][j];
if (j+1 < data[i].length) {
System.out.print(", ");
} else {
System.out.println();
}
}
}
}
Finally, Your array is initializing incorrectly, which is why you are having so much trouble: You are actually writing both values to the X component, so the first time you loop in k you write a the X value to i,j (eg data[0][0]) and print it out. The second time you loop k you write the Y value to the same i,j (eg data[0][0]) again and print it out. This looks like you are printing the array you want, but actually you are writing both values to the same column. You really want something without the k loop:
//Initialise the array with the values from the file
public static float[][] data(float[][] data, Scanner scan){
int count = 0;
for (int i=0;i<data.length;i++){
for (int j=0;j<data[0].length;j++){
count++;
if(count<data.length*data[0].length){
data[i][j] = (float) IOUtil.skipToDouble(scan);
System.out.print(data[i][j] + " ");
}
}
System.out.println();
}
return data;
}
If you want to enforce 2 columns which I think k is doing, something like:
public static float[][] data(float[][] data, Scanner scan){
for (int i=0;i<data.length;i++){
for (int j=0;j<2;j++){
data[i][j] = (float) IOUtil.skipToDouble(scan);
System.out.print(data[i][j] + " ");
}
System.out.println();
}
return data;
}
count is also unnecessary as it is just a different way of controlling the total size of the array which it already handled / limited by looping each column (or in the second example where you know it is two wide) by the data.length / data[0].length
EDIT Added by the OP:
To clarify for anyone who still does not get it who maybe is confused about the same thing I was: I misunderstood where the values were being stored so this is why I set the problem up wrong and none of the short answers were making any sense.
I took the whole thing a bit too literally, assuming that the value[here][] was holding the values from the first column and the value[][here] was holding the values from the second column.
I am not sure why I held onto this, but I think it has something to do with how I had been using 1D arrays (without needing to tell them to have a column).
Don't understand your code, but I hope this helps:
float[][] data = new float[10][2];
// ... fill the array with data
// print 'left' column:
for (int i = 0; i < data.length; i++) {
System.out.println(data[i][0]);
}
What are you trying to do with this part of your code?
for(int k=0;k<2; k++){
data[i][j] = (float) IOUtil.skipToDouble(scan);
System.out.print(data[i][j] + " ");
}
You are writing into data[i][j] twice, and thus overwrite the first value returned by
(float) IOUtil.skipToDouble(scan);
It's hard to tell what the code should be without seeing your input file, but I think you are looking for something like this:
public static float[][] data(float[][] data, Scanner scan){
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = (float) IOUtil.skipToDouble(scan);
System.out.print(data[i][j] + " ");
}
System.out.println();
}
return data;
}
While putting data in 2D array you are overwriting the content
of array twice within the for loop for(int k=0;k<2; k++). For
example:consider the case when i = 0:
At k = 0, data[0][0] = 13.97
At k = 1, data[0][0] = 2.2 (Overwrites 13.97) Whereas, the desired result that you are looking for is data[0][0] = 13.97 and
data[0][1]=2.2
You should use the following code to fill the 2D array:
public static float[][] data(float[][] data, Scanner scan){
int count = 0;
for (int i=0;i<data.length;i++){
for (int j=0;j<data[0].length;j++){
count++;
if(count<data.length*data[0].length){
for(int k=0;k<2; k++){
data[i][j] = (float) IOUtil.skipToDouble(scan);
System.out.print(data[i][j] + " ");
j = j+1;
}
System.out.println();
}
}
}
return data;
}
And following Code to read the data:
public static void printX(float[][] data)
{
for (int i=0;i<data.length;i++)
{
System.out.println(data[i][0]);
}
}
Also If condition if(count<data.length*data[0].length) fails for some value of i then in that case you will have data[i][0] = 0 and
data[i][1] = 0 . You should also consider this fact and should expect
0 as some of the outputs by printX .
Check this solution
public static void main(String[] arg) {
int a[][] = { { 1, 2, 3 }, { 4, 9, 6 }, { 5, 7, 9 } };// new int[3][3];
for(Values val:getValues(a, 1)){
fillRow(a, val.row);
fillCol(a, val.col);
}
printAll(a);
}
private static List<Values> getValues(int a[][], int ele){
List<Values> list = new ArrayList<Values>();
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
if(a[i][j] == ele){
list.add(new Values(i,j));
}
}
}
return list;
}
private static class Values{
public Values(int i, int j) {
row = i;
col = j;
}
int row;
int col;
}
private static void printAll(int a[][]){
for(int i[]:a){
for(int j:i){
System.out.print(" "+j);
}
System.out.println("\n");
}
}
private static void fillRow(int a[][], int row){
for(int i=0;i<a.length;i++){
a[i][row] = 0;
}
}
private static void fillCol(int a[][], int col){
for(int i=0;i<a.length;i++){
a[col][i] = 0;
}
}