How would i transfer a 2d array into a 1d array in java. I have the code for the 2d array but dont know where to start.
The output of the 2d array is a 8 by 10 grid with the numbers going from 1-80.
public class move
{
public static void main (String[] args)
{
int[][] twoarray = new int[8][10];
int i ;
int j ;
for(i =0; i < 8; i++)
{
for(j = 0; j < 10; j++)
twoarray[i][j] = (i * 10 + j+1);
}
for(i = 0; i < 8; i++)
{
for(j = 0; j < 10; j++)
{
System.out.print(twoarray[i][j]);
System.out.print(" ");
}
System.out.println();
}
int[] array = new int[80];
}
}
Using Java 8
int[] array = Stream.of(twoarray)
.flatMapToInt(IntStream::of)
.toArray();
Using Java 7 or older
int[] array = new int[80];
int index = 0;
for (int[] row : twoarray) {
for (int val : row)
array[index++] = val;
}
You can do in your for loop:
int[] array = new int[80];
int k=0;
for(i = 0; i < 8; i++){
for(j = 0; j < 10; j++){
array[k++]=twoarray[i][j];
}
}
Related
I searched some entries, but could not answer my question correctly myself.
I'm trying to fill a 2-dimensional array with values.
As a test I'm currently doing this by trying to fill the array with the int number 1.
I do not understand my mistake.
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Use index 0 to length-1 (as array index start with 0)
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
}
just debug it and you can see, that
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
i, and j change values from 0 to 6, it means that it get's out of arrays bounds ( you iterate over 7 lements, instead of 6 ), just remove = sign in loop bodies
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Your board array is of size 6x6 hence the board.length is 6.
When you run the loop for (int j = 0; j<=board.length; ij+) it will run from 0 up to 6 but the array indexing is from 0 to 5. So when j=6, ExceptionOutOfBounds occurs since it will be referring to index board[0][6].
Change the condition in both the loops from <=board.length to <board.length
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();
}
}
I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
for(j=0;j
{
if(j>i)
d1+=a[i][j];. // Above the diagon
else
if(i>j)
d2+=a[i][j];. // Below the diagonal
}
I created a function to multiply a matrix by itself which gets 2 parameters, one is the matrix, the other one is an int n. The problem is that I cant figure out where should I use the n in my code so that it multiplies the matrix by itself an n number of times (in other words matrix^n). At current stage it only does matrix^2;
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * array[x][j];
}
newArray[i][j] = sum;
}
}
return newArray;
}
Add a third for loop that goes from 1 < k < n . You will need to remain array untouched in order to maintain the values of the initial matrix, will also need a matrix newArray to keep the values of the previous multiplication and a temporary matrix tmp that just hold values during the multiplication itself and then is copied to newArray.
Take a look in the sample below.
FULL CODE
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Just holds values during multiplication between two matrices
int[][] tmp = new int[array.length][array.length];
// Initialize newArray to be equal to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
// Outer loop that multiplies as many times as you want
for (int k = 1; k < n; k++) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
tmp[i][j] = sum;
}
}
// Copy the result from multiplication to newArray and restart tmp
System.arraycopy(tmp, 0, newArray, 0, tmp.length);
tmp = new int[array.length][array.length];
}
return newArray;
}
Hope it helped!
You can create two methods for clarity: the first to multiply a square matrix, and the second to call the first n number of times.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = array;
for (int i = 0; i < n; i++) {
newArray = squareMatrixMultiplication(newArray);
}
return newArray;
}
public static int[][] squareMatrixMultiplication(int[][] array) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
for (int x = 0; x < array.length; x++) {
newArray[i][j] += array[i][x] * array[x][j];
}
}
}
return newArray;
}
Initialize newArray to be equal to array, then
add a loop around the matrix multiplication and use newArray in your nested loops: multiply newArray by array.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Add loops to initialize newArray to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
for (int j = 0; j < n; j++) { // Add this loop
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
newArray[i][j] = sum;
}
}
} // and this
return newArray;
}
public class MyClass {
public static void main(String args[]) {
int array[][] = new int[2][2];
array[0][0] = 1;
array[0][1] = 2;
array[1][0] = 3;
array[1][1] = 4;
int newArray[][] = new int[2][2];
//initialize array with these elements
newArray[0][0] = 1;
newArray[0][1] = 0;
newArray[1][0] = 0;
newArray[1][1] = 1;
int n = 5;
for (int i = 0; i < n; i++) {
newArray = lungimeDrumuri(array, newArray, i);
}
}
public static int[][] lungimeDrumuri(int[][] array, int newArray[][], int n) {
int newArray1[][] = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * newArray[x][j];
}
newArray1[i][j] = sum;
}
}
return newArray1;
}
}
Hope this one will help you.
I got homework "Take two given array(already sorted up, for example {1,2,3}) and create a new array contains both arrays and then sort him up", we have a function to sort up arrays so it's not the problem, however it gets a little bit complex to me, here is my code:
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int[] a = new int[3];
int[] b = new int[5];
Help_arr.scan(a);
Help_arr.scan(b);
Help_arr.print(peula(a, b));
}
public static int[] peula(int[] a1, int[] b1) {
int[] c = new int[a1.length + b1.length];
for (int i = 0; i < a1.length; i++)
c[i] = a1[i];
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
}
Help_arr.sortup(c);
return c;
}
Functions used from Help_arr class:
1) Scan an array:
public static void scan(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter number" + (i + 1));
arr1[i] = in.nextInt();
}
}
2) Print an array:
public static void print(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
}
3) Sort up an array:
public static void sortup(int[] arr1) {
int i, mini, temp, j;
for (j = 0; j < arr1.length; j++) {
mini = j;
for (i = j; i < arr1.length; i++) {
if (arr1[i] < arr1[mini])
mini = i;
}
temp = arr1[j];
arr1[j] = arr1[mini];
arr1[mini] = temp;
}
}
I get an error in the line c[i]=b1[i]; the array is going out of index bounds but I followed the code and this for will run until i=7 as the c.length is 8 and it is possible. But maybe I am missing something, here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arrays.PgRonTargilMivhan.peula(PgRonTargilMivhan.java:21)
at arrays.PgRonTargilMivhan.main(PgRonTargilMivhan.java:13)
The issue is with this code:
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
here b1 index should start with 0 but you are starting with a1.length. You should have a separate index for b1 or use b1[i-a1.length].
Please find the logic ..
you were using 'i' index for array b is the problem.
Solution is below. Good luck
int[] c = new int[a.length + b.length];
int i = 0;
for (i = 0; i < a.length; i++)
c[i] = a[i];
for (int j = 0; j < b.length; j++)
c[i] = b[j];
}