Two-dimentional arrays [duplicate] - java

This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
Closed 3 years ago.
I am working with 2-D arrays and I require help on this topic. My task is to create a 2-D array such that it is n by n (i.e. the number of rows and columns are equal). Fill the array with alternating 0's and 1's
void setup()
{
int n=3;
// code to populate the array
// code to display the output of array in a table format
/* output should be as follows:
The expected result when n=3 should be as the following:
1 0 1
0 1 0
1 0 1
*/
}

Solution:
class test{
public static void main(String[] args) {
int n = 3;
int[][] arr = setup(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
static int[][] setup(int n){
int[][] arr = new int [n][n];
boolean even = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = even ? 1 : 0;
even = !even;
}
}
return arr;
}
}
Output:
0 1 0
1 0 1
0 1 0

This should work.
You can replace the 3 that is given to n with any number you want as the 2D-Array's length.
void setup(){
int n = 3;
int count = 0;
int[][] myArray = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(count % 2 == 0){
myArray[i][j] = 1;
}
else{
myArray[i][j] = 0;
}
System.out.print(myArray[i][j] + " ");
count++;
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0

It's not complex, you just have to iterate two loops, that's it. Although you can get the solution on different ways.
public static void main(String[] args) {
int n = 3;
int [][] arr = new int[n][n];
int val = 1;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
arr[i][j] = val;
val = (val == 0) ? 1 : 0;
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0

A simple implementation:
void setup()
{
int n=3;
final int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((n * i + j) % 2 == 0) {
array[i][j] = 1;
}
}
}
}

Here is how you can approach your logic , create a counter and negate each time after it prints value.
public static void main(String[] args) {
int counter = 0;
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(counter==0?1:0);
counter = ~counter;
}
System.out.println();
}
}
Output
101
010
101
Here is Online source code.

Related

ArrayIndexOutOfBound Exception when reversing array order with multidimensional arrays:

So I'm currently playing around with multidimensional arrays (2D) and I'm trying to reverse the order of each array in a 2-d array.
So I have a 2D-array set as:
int firstArray[][] = {{5,6,7,8,9,10}, {11,12,13,14,15,16}}
I have manually looked through the issue to see where I may have went wrong, to see which part of my code would end up going out of bounds in regards to my for-loops. The -1 part also caught me off guard.
I have began doing reverses on a regular 1-d array, and tried to apply the same concept to multidimensional arrays.
class Test2 {
public static void main (String[] args) {
int firstArray[][] = {{5,6,7,8,9,10}, {10,11, 12, 13, 14, 15}};
System.out.println("FIRST ARRAY");
display(firstArray);
}
public void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num.length-1-j];
num[i][num.length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
}
I want the output using my display method to basically be a reverse of the arrays in my 2-d array:
10 9 8 7 6 5
15 14 13 12 11 10
The issue that I'm getting is an
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
ArrayIndexOutOfBoundsException: -1
at Test2.display(Test2.java:30)
at Test2.main(Test2.java:20)
You are using the length of the wrong dimension.
With num.length you are using the number of rows and not the number of columns of the current row.
You need to change that to num[i].length.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
Notice you wrote num[i][num.length-1-j];
num.length-1-j is basically 2 - 1 -j.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2 ; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}

copy min columns of 2d array to 1d array java

I want to create a 1D array that saves the min columns from my 2D array, but I get wrong the min values. My theseisLine array is a copy from my intP array that I store there the column numbers, so theseisLine shows the min from each column.
package themab2018;
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
public class THEMAB2018 {
static void displayP(int intP[][]) {
System.out.println("intP2D");
for(int i = 0; i < intP.length; i++) {
for(int j = 0; j < intP[i].length; j++)
System.out.print(intP[i][j] + " ");
System.out.println();
}
}
static void findMinCol(int intP[][] ,int n) {
int theseisLine[] = new int[n];
if(theseisLine.length < intP.length)
for(int i = 0; i < theseisLine.length; i++)
theseisLine[i] = intP[0][i];
else
for(int i = 0; i < intP.length; i++)
theseisLine[i] = intP[0][i];
int min = theseisLine[0];
System.out.println();
System.out.println("Min Array");
for(int i = 0; i < theseisLine.length; i++) {
if(theseisLine[i] < min) {
min = theseisLine[i];
}
System.out.print(min + " ");
}
}
public static void main(String[] args){
int m , n;
System.out.println("Import m , n");
do {
System.out.print("Give m ");
m = scannerUserInput.getInteger();
System.out.print("Give n ");
n = scannerUserInput.getInteger();
} while (m < 1 && n < 1);
int intP2D[][] = new int [m][n];
int theseisLine[] = new int[n];
for(int i = 0; i < intP2D.length; i++){
for(int j = 0; j < intP2D[i].length; j++) {
intP2D[i][j] = (int) (Math.random() * (10 - 1)+1)+1;
}
}
displayP(intP2D);
findMinCol(intP2D, m);
}
}
The result that I get example :
Import m , n
Give m 3
Give n 4
intP2D
3 9 7 2
8 9 7 6
5 8 8 7
Min Array
3 3 3
The result that i want in this example :
Import m , n
Give m 3
Give n 4
intP2D
3 9 7 2
8 9 7 6
5 8 8 7
Min Array
3 8 7 2
Firstly, while calling findMinCol(intP2D, m); you need to pass the count of column i.e. n and not count of row.
Secondly, while calculating the min element in the column, you are comparing all element with int min = theseisLine[0]; which might not be correct.
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
public class THEMAB2018 {
static void displayP(int intP[][]) {
System.out.println("intP2D");
for(int i = 0; i < intP.length; i++) {
for(int j = 0; j < intP[i].length; j++)
System.out.print(intP[i][j] + " ");
System.out.println();
}
}
static void findMinCol(int intP[][] ,int n) {
int theseisLine[] = new int[n];
for(int i = 0; i < theseisLine.length; i++)
theseisLine[i] = intP[0][i];
System.out.println();
System.out.println("Min Array");
for(int i = 0; i < theseisLine.length; i++) {
for (int j = 1; j < intP.length; j++) {
if (intP[j][i] < theseisLine[i]) {
theseisLine[i] = intP[j][i];
}
}
System.out.print(theseisLine[i] + " ");
}
}
public static void main(String[] args){
int m , n;
System.out.println("Import m , n");
m = 3; n = 4;
int intP2D[][] = new int [m][n];
int theseisLine[] = new int[n];
for(int i = 0; i < intP2D.length; i++){
for(int j = 0; j < intP2D[i].length; j++) {
intP2D[i][j] = (int) (Math.random() * (10 - 1)+1)+1;
}
}
displayP(intP2D);
findMinCol(intP2D, **n**);
}
}
the output I am getting:
intP2D
2 5 8 7
10 6 9 3
7 9 3 8
Min Array
2 5 3 3
I don't know what you want to check in your finding method with the if-else block. You don't need it anyway to find the minimum of each column, that's why I removed it. A simple nested for loop solves your problem.
Additionally, you don't need to pass the number of columns as a parameter, because it can be easily queried from the matrix. I still left it in to avoid having to change the method call.
static void findMinCol(int intP[][] ,int n) {
int rows = intP.length;
int cols = intP[0].length;
int[] result = new int[cols];
for(int i = 0; i < cols; i++){
int min = Integer.MAX_VALUE;
for(int j = 0; j < rows; j++){
if(min > intP[j][i]){
min = intP[j][i];
}
}
result[i] = min;
}
for(int i = 0; i < result.length; i++) {
System.out.print(result[i] + " ");
}
}

Scanner Two-dimensional array (n x n)

import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < 0; j++)
if (i == j)
num[i][j] = 1;
else
num[i][j] = 0;
for (int[] a : num) {
for (int b : a)
System.out.print(b + " ");
System.out.println();
}
}
}
i want to make
1 0 0
0 1 0
0 0 1
but my answer come out like
0 0 0
0 0 0
0 0 0
It looks like your code is kicking out of the inner loop, the one using j as the variable. You initialize j = 0, and then if j < 0 it will execute. However, 0 < 0 is false so it never iterates thru the inner loop. Try changing that line to
for (int j = 0; j < n; j++) and I'll expect you'll get the result you are looking for.
you need to loop through all elements in 2d array not just the 0th element. see modified for loop.
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i == j)
num[i][j] = 1;
else
num[i][j] = 0;
for (int[] a : num) {
for (int b : a)
System.out.print(b + " ");
System.out.println();
}
}
}

Adding Data File into Two Seperate 2D Arrays in Java

I am having some trouble with a Java program. I have a txt data file, which I will display, that I need to add into two separate arrays. The text file is 8 lines long that is supposed to go into two separate 4x4 matrices. A little background info on this program, reads in two arrays, compares them and outputs the largest elements of the same index and outputs them in a separate array. I somehow cannot seem to figure out how to add the data file into two separate arrays. My code is below, thanks in advance.
Data File:
2 7 6 4
6 1 2 4
9 7 2 6
8 3 2 1
4 1 3 7
6 2 3 8
7 2 2 4
4 2 3 1
Code:
public class prog465a
{
public static void main(String[] args) {
Scanner inFile = null;
try
{
inFile = new Scanner(new File("prog465a.dat.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File not found!");
System.exit(0);
}
int[][] firstData = new int[4][4];
int[][] secondData = new int[4][4];
int[][] finalData = new int[4][4];
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
{
if (i < 4 && j < 4){ //Trying to add first four lines to one matrix
firstData[i][j] = inFile.nextInt();
} else if (i >= 4 && j >= 4)
{
secondData[i][j] = inFile.nextInt();
}
}
}
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
{
if (firstData[i][j] >= secondData[i][j])
{
firstData[i][j] = finalData[i][j];
}
else if (secondData[i][j] >= firstData[i][j])
{
secondData[i][j] = finalData[i][j]
}
}
}
for ( int c = 0 ; c < finalData.length ; c++ )
{
for ( int d = 0 ; d < finalData.length ; d++ )
{
System.out.print(finalData[c][d]+" ");
}
System.out.print("\n");
}
}
}
The problems is that you are trying to parse a file with 8 rows and 8 column..
change this:
int[][] finalData = new int[4][4];
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
to:
int[][] finalData = new int[4][4];
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 4; j++)
that means 8 rows of file with 4 column each.
Also on the second part of your forloop again you are trying to get 8x8 matrix it should be 4x4..
change:
for (int i = 0; i< 8; i++)
{
for(int j = 0; j < 8; j++)
{
if (firstData[i][j] >= secondData[i][j])
{
firstData[i][j] = finalData[i][j];
}
else if (secondData[i][j] >= firstData[i][j])
{
secondData[i][j] = finalData[i][j]
}
}
}
to:
for (int i = 0; i< 4; i++)
{
for(int j = 0; j < 4; j++)
{
if (firstData[i][j] >= secondData[i][j] )
{
finalData[i][j] = firstData[i][j];
}
else if (secondData[i][j] >= firstData[i][j])
{
finalData[i][j] = secondData[i][j] ;
}
}
}

sorting elements in a row in a 2D array

I have to sort elements in each row and then display the array.
For example, if the input array is:
5 1 3 1 3 5
INPUT: 7 6 4 OUTPUT: 4 6 7
9 8 2 2 8 9
My code for that was:
for (int i = 0; i < size; i++) { //"size" is the size of the square matrix
for (int j = 0; j < size; j++) {
for (int k = 0; k < size - 1; k++) {
for (int l = 0; l < size - k - 1; l++) {
if (arr[i][j] > arr[i][j+1]) { //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
}
}
}
Any suggestions?
for (int i = 0; i < size; i++){ //"size" is the size of the square matrix
for (int j = 0; j < size; j++){
for (int k = j+1; k < size; k++){
if (arr[i][j] > arr[i][k]){ //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][k];
arr[i][k] = temp;
}
}
}
}
I don't think you need 4th loop
I would do it simpler
for(int[] r : arr){
Arrays.sort(r);
}
I would create a method to sort rows, and then just iterate through the rows in the matrix and sort them one at a time. For example:
public static int[] sortRow(int[] row) // selection sort
{
for (int i = 0; i < row.length - 1; i++) {
for (int j = i + 1; j < row.length; j++) {
if (row[i] > row[j]) {
int temp = row[i];
row[i] = row[j];
row[j] = temp;
}
}
}
return row;
}
public static void main(String args[])
{
int[][] arr = {{5, 1, 3}, {7,6,4}, {9,8,2}};
for (int r = 0; r < arr.length; r++) { // for every row in the matrix
arr[r] = sortRow(arr[r]); // set the row to be the sorted row
}
// print out the array to the console
for (int r[] : arr) {
for (int c : r)
System.out.print(c + " ");
System.out.println();
}
}
Output:
1 3 5
4 6 7
2 8 9

Categories