My goal to to make three different 2D arrays, and for the last two replace all zeroes in the array values for blank spaces instead. I've tried using printf("%s","[]") but instead of replacing the zeros they just add the brackets above the array. i believe it has something to do with the placement of my else statement.
public class arrayprgm1{
public static int[][] Table(int x, int y){//creating first 2D array
int[][] array = new int[x][y];
for (int row= 0; row < array.length; row++){// using for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
array[row][column]=(row+column)*3;// algorithm used for first 2D array
}
}
int sum = 0;//declaring integer to sum up all of the values created by array
for (int row=0; row < array.length; row++){
for (int column=0; column < array[row].length; column++){
sum = sum + array[row][column];// algorithm used to sum up values of first array
}
}
System.out.printf("The total of all the numbers added together is: %2d\n", sum);// using format print to display sum
return array;//return array created to the main method
}//end of Table method
public static int[][] Odds(int x, int y){//creating second 2D array
int[][]array = new int[x][y];
for (int row= 0; row < array.length; row++){// using for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
{
if ((row + column)%2 !=0){ // if statement used to determine if value is odd or even
array[row][column]=(row+column)*3;// algorithm used for second array
}
else
System.out.printf("%s","[]");
}
}
}
int sum = 0;//declaring integer to sum up all of the values created by array
for (int row=0; row < array.length; row++){
for (int column=0; column < array[row].length; column++){
sum = sum + array[row][column];// algorithm used to sum up all odd values
}
}
for(int row=0; row< array.length;row++){
for(int column=0;column<array[row].length;column++){
}
}System.out.printf("The total of all the odd numbers added together is: %2d\n", sum);//format print used to display sum of all odd numbers
return array;
}//end of Odds Method
public static int[][] Evens(int x, int y){ //Creating the third 2D array that will hold all even values
int[][] array = new int[x][y];
for (int row= 0; row < array.length; row++){//for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
{
if ((row + column)%2 ==0){//if statement used to determine if value is odd or even
array[row][column]=(row+column)*3;//algorithm used for third array
}
else
System.out.printf("%s","[]");
}
}
}
int sum = 0;// declaring integer to sum up all the even values
for (int row=0; row < array.length; row++){//for loop to create array
for (int column=0; column < array[row].length; column++){//nested for loop
sum = sum + array[row][column];// algorithm used to sum up all even numbers
}
}
System.out.printf("The total of all the even numbers added together is: %2d\n", sum);// format print used to display sum of all even numbers
return array;
}//end of Evens method
public static void main(String[] args){//main method
int[][]array = new int[15][15];//create array to pass to arrays method
array = Table(15,15);
for(int row=0; row < array.length; row++){ //for loop to properly display array in a square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
System.out.printf("\n");
array = Odds(15,15);
for(int row=0; row < array.length; row++){//for loop to properly display array in square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
System.out.printf("\n");
array = Evens(15,15);
for(int row=0; row < array.length; row++){//for loop to properly display array in square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
}//end of main method
}//end of public class arrayprgm1
You can't replace a zero with a character like space in an array containing integers as you intend to do it. Instead what you need to do this is handle this when you output the array and check for zero values there.
For instance
for(int row=0; row < array.length; row++){
for(int column=0; column<array[row].length;column++){
int value = array[row][column];
if (value == 0) {
System.out.printf(" ");
else {
System.out.printf("%4d",value);
}
}
}
Related
I made this code in order to swap places with the first column and the last column in a 3x3 Matrix. I would need to use 2 different methods, one to print the original matrix and one to print the modified matrix.
I was able to do the first one, but I have problems with the second.
public class SwapMatrix {
public static void main(String[] args) {
int matrix [][] =
{{3, 4, 5},
{7, 8, 9},
{1, 2, 3}};
System.out.println("\n Normal Matrix:");
print(matrix);
//int matrixModified [][] = swap(matrix);
//System.out.println("\n New Matrix:");
//print(matrixModified);
}
public static void print (int matrix[][]){
for (int i=0; i<matriz.length; i++){
for (int j=0; j<matrix[0].length; j++){
System.out.print(matriz [i][j]+ "\t");
}
System.out.println();
}
}
}
If you want to print the matrix backwards, all you have to do is to count reverse in your loop.
public static void printReverse (int matrix[][]){
for (int i=0; i<matrix.length; i++){ // lines
for (int j=matrix[0].length-1; j>=0; j--){ // columns backwards
System.out.print(matrix [i][j]+ "\t");
}
System.out.println();
}
}
You can implement the swap() method in two ways: either by creating a new matrix or by swapping the columns of the given matrix in place.
1. Firstly, you need to create a new matrix.
And then iterate over it with a nested for loop assigning the elements of each row in the new matrix in reversed order. I.e. the value of the first element of the row at position 0 would be assigned to the element at position matrix[0].length - 1 and vice versa (the same hold true for all other elements).
public static int[][] swap(int[][] matrix) {
int[][] result = new int[matrix.length][matrix[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
result[row][(matrix[0].length - 1) - col] = matrix[row][col];
}
}
return result;
}
2. To swap the given matrix in place, you need to create a nested for loop. Iteration in the inner loop should happen only until the middle of the array representing each row (that's important, if'll iterate over the full length of a row elements will get swapped twice and the matrix will remain the same).
public static int[][] swapInPlace(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length / 2; col++) {
int temp = matrix[row][(matrix[0].length - 1) - col];
matrix[row][(matrix[0].length - 1) - col] = matrix[row][col];
matrix[row][col] = temp;
}
}
return matrix;
}
Sidenote: although int matrix[][] is a valid syntax inherited from the C language, it's not a good practice to use it because this notation mixes two completely different notions: a variable name and a type. The preferred way to define an array int[][] matrix.
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'm trying to convert a two-dimensional array to a one-dimensional array in Java.
I cannot use any additional data structures, ArrayLists, collections etc. for temporary storage.
Only one array can be allocated - the one that will be returned from the method.
There are three tests with arrays inputed into the method to validate the program. Test one has a 2D array with 3 rows and columns, test two has a 2D array with 3 rows and 1 column, and test three is empty.
My current code is:
public static int[] twoDConvert(int[][] nums) {
int index = 0;
int[] combined = new int[nums.length*3];
if (nums.length == 0) return combined;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums.length; col++) {
combined[index] += nums[row][col];
index++;
}
}
return combined;
}
The first test works correctly, but for some reason the 2nd test throws ArrayIndexOutOfBoundsException (Index 1 out of bounds for length 1).
This occurs no matter how large or small the combined array length is.
How can I fix this?
We create a single Integer array with a length determines by the size method. Size takes the 2-dimensional array and finds the sum of all columns in each row and returns that sum. We check if the length is 0, and if so, we return. We then loop through all rows, followed by a loop through all columns in that row. We then assign the value at that row and column to that next index in the array. Unfortunately we can't do any math (to my knowledge) to determine the index based of row/column since they could be variable sizes.
public static int[] twoDConvert(int[][] nums) {
int[] combined = new int[size(nums)];
if (combined.length <= 0) {
return combined;
}
int index = 0;
for (int row = 0; row < nums.length; row++) {
for (int column = 0; column < nums[row].length; column++) {
combined[index++] = nums[row][column];
}
}
return combined;
}
private static int size(int[][] values) {
int size = 0;
for (int index = 0; index < values.length; index++) {
size += values[index].length;
}
return size;
}
I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me
I'm trying to figure out how to print out a second array that is based off my first one but only displays values that are greater than the value to its left and less than the value to it's right and displaying these values by row in the row that they are in the original array. Here's my code so far.
public static void main(String[] args)
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
row = 3;
col = 6;
// enter array elements.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.println("Enter a value: ");
arr[i][j] = scan.nextInt();
}
}
// the 2D array is here.
System.out.print("Matrix Display :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
}
}
You won't know how many of the elements fit your criteria, so you need to use a mutable object. Since each row might have a different number of matching numbers, you won't be able to make a normal array without null values in it most of the time.
Use a 2D ArrayList, scan through your original 2D array, and add the value that match your criteria to the corresponding row of your ArrayList.
You could do something like this:
int width = arr[0].length-1;
ArrayList<ArrayList<Integer>> listoflists= new ArrayList<ArrayList<Integer>>();
// Scan array for matching values
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
listoflists.add(new ArrayList<Integer>());
if(j==0 && arr[i][0]<arr[i][1])
listoflist.get(i).add(arr[i][0]);
else if(j==width && arr[i][width]>arr[i][width-1]
listoflist.get(i).add(arr[i][width]);
else if( #this is the last condition to check from both sides)
listoflist.get(i).add(arr[i][j]);
}
}