How to get the first column's contents from a 2D array - java

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

Related

Printing a half pyramid from array elements

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

drawing Diamond of numbers with 2D array in java

So I need to make a diamond_look of numbers using 2D array in Java. I got my results but with null before the diamond. For drawNumDiamond(9) I have to get a diamond look that goes until 5 and back. I know I can make it without using array, but I want to learn more about 2D arrays :this is how it should look like and what are my results
public class Example1{
private static void drawNumDiamond(int h) {
if(h%2 != 0) {
int size = h/2 +1;
int count = 1;
int loop = 1;
String[][] dijamant = new String[h][];
for(int row = 0; row < dijamant.length; row++) {
dijamant[row] = new String[row+1];
for(int kolona=0; kolona<=row; kolona++) {
dijamant[0][0] = "1";
for(int i=0; i< loop;i++) {
dijamant[row][kolona]+= count;
}
}
count++;
loop+=2;
}
for (int k = 0; k < size; k++) {
System.out.printf("%" + h + "s", dijamant[k]);
h++;
System.out.println();
}
h--;
for (int q = size - 2; q>=0; q--) {
h--;
System.out.printf("%" + h + "s", dijamant[q]);
System.out.println();
}
}
}
public static void main(String[] args) {
drawNumDiamond(9);
}
}
The issue is in this line :
dijamant[row][kolona] += count;
if dijamant[row][kolona] is null and count is 2, the result of the string concatenation will be "null2". Try adding the following if statement before to initialize with an empty string :
if (dijamant[row][kolona] == null) {
dijamant[row][kolona] = "";
}
This will get your code working, but there are still things to think about. E.g. you keep setting dijamant[0][0] = "1"; in the loop.

Java 2d array counts zeros in column

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

2D Array Methods & Demo

I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.

simple Inplace square matrix clockwise rotation in java - what is wrong with my code

class RotateMat {
static Integer[] swap(int x, int y) {
int a=x;
int b=y;
a=a^b;
b=a^b;
a=a^b;
return new Integer[]{a,b};
}
static int[][] rotate(int[][] arr) {
assert arr.length == arr[0].length;
int m = arr.length;
for (int i=0; i<m;i++) {
for (int k=0; k<m;k++) {
//int[] temp_arr = swap(arr[i][k], arr[k][i]);
//arr[i][k] = temp_arr[0];
//arr[k][i] = temp_arr[1];
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
}
}
print(arr);
return arr;
}
static void print(int[][] arr) {
int n=arr[0].length;
int m=arr.length;
assert m==n;
//System.out.println(m + " " + n);
for (int i=0; i<m;i++) {
for (int j=0; j<n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
int arr[][] = { {1,2,3}, {4,5,6}, {7,8,9}};
print(arr);
arr = rotate(arr);
print(arr);
}
}
I am a C user and trying to practice more java programming. I understand pass by value in java and that is the reason I try to return rotated array from rotate() function and assign it again to arr variable.
I get the same array printed even after I rotate....What am I doing wrong here?
In your second for loop, you are using the wrong variable. Change this:
for (int i=0; i<m;i++) {
for (int k=0; k<m;k++) {
^
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
To this:
for (int i=0; i<m;i++) {
for (int k=i; k<m;k++) {
^
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
This will produce output:
123
456 < First print statement in main method
789
147
258 < Print statement inside rotate method
369
147
258 < Second print statement in main method
369
(Note: I added the spaces between the print statements)
As you originally start with k = 0, you actually rotate the whole way round (which can be seen if you add debugging print statements).
You are actually rotating it twice, since you inner loop in rotate method works through the entire length.
Try for (int k=0; k<i; k++) instead.
You need to swap elements beneath the diagonal with those that are above.

Categories