Storing twodimensional array into single dimensional array - java

Please help me to fix this. I just want to store a two dimensional array into a single dimensional array is it possible. what I'm trying is that I have to store two dimensional integer array which will be created dynamically.

Try like this:
int[][] arr = new int[Rows][Cols];
int[] arr1D= new int[Rows * Cols];
Rows = arr.length;
if (Rows > 0) {
Cols = arr[0].length;
} else {
Cols = 0;
}
for (int row = 0, count = 0; row < Rows; row++) {
for (int col = 0; col < Cols; col++) {
arr1D[count] = arr[row][col];
count++;
}
}

One way of doing it
import java.util.ArrayList;
public class Test1 {
public static void main(String[] args) {
int[][] twoDArrays={{10,5},{4,6},{9,8}};
ArrayList<Integer> oneDArray= new ArrayList<Integer>();
for(int i=0; i<twoDArrays.length;i++){
for(int j=0;j<twoDArrays[i].length;j++){
oneDArray.add(twoDArrays[i][j]);
}
}//printing onedArray
for(Integer s:oneDArray){
System.out.println(s);
}
}
}
Output:
10
5
4
6
9
8

Related

How to find largest 10 elements in multi dimentional array?

I hope this will print one largest value. but it need 10 largest elements in an 3D array.
public class foo{
Public static void main(String[] args){
int row,col,dep=3;
int[][][] value=new int[row][col][dep];
/* insert the value from user or initialize the matrix*/
int max=0;
for(row=0;row<3;row++)
for(col=0;col<3;col++)
for(dep=0;dep<3;dep++)
if(value[row][col][dep]>max)
max=value[row][col][dep];
System.out.println(max);
}
}
You can add all integers into a List<Integer>, sort it, and then get the X max numbers of it:
public class foo {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
List<Integer> listWithAll = new ArrayList<>();
/* insert the value from user or initialize the matrix*/
int max = 0;
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
for (dep = 0; dep < 3; dep++)
listWithAll.add(value[row][col][dep]);
listWithAll.sort(Collections.reverseOrder());
for (int i = 0; i < 10; i++) {
System.out.println(listWithAll.get(i));
}
}
}
which prints:
15 10 0 0 0 0 0 0 0 0
or using Java 8 streams only:
List<Integer> max10 = listWithAll.stream()
.sorted(Collections.reverseOrder())
.limit(10)
.collect(Collectors.toList());
max10.forEach(System.out::println);
Here is a way to do it with streams. I used a complete 2 x 2 x 2 array to make it easier but it would work with any int[][][] array. Instead of using nested loops, I just flatMapped the arrays.
Initialize the array.
int[][][] v = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
Now get the top4 values (or top N values) and put them in a list.
int top4 = 4;
List<Integer> top4Max =
Arrays.stream(v).flatMap(Arrays::stream).flatMapToInt(
Arrays::stream).boxed().sorted(
Comparator.reverseOrder()).limit(top4).collect(
Collectors.toList());
System.out.println(top4Max);
Prints
8 7 6 5
The Arrays.stream strips one level of array. The flatMap takes those and further flattens them into a single dimenion array. The flatMapToInt flattens that into a stream of ints where they are sorted and processed into a limited collection.
If required, you could also put them in an array instead of a list.
Alternatively, one could create a small array and use it as with a normal findmax function.
public class Array_3D {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
int[] topten = new int[10]; //array to hold max values
int count = 0;
int candidate = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < dep; k++) {
if (count < 10) { //start with first ten values
topten[count] = value[i][j][k];
count++;
}
else {
candidate = value[i][j][k];
for (int x = 0; x < 10; x++) { //loop for loading top values
if (candidate > topten[x]) {
topten[x] = candidate;
break; //exit on first hit
}
}
}
}
}
}
for (int i = 0; i < 10; i++) {
System.out.print(topten[i] + " ");
}
System.out.println();
}
}
I don't know which method is faster for large 3D arrays; here we have to run a small loop at every point in the 3D array, vs creating an entirely new list and sorting it. Clearly this wins in memory usage, but not sure about speed. [Edit note this returns an unsorted array of the top ten values as is].

Remove rows and columns from the matrix

"Find the maximum element (s) in the matrix and remove from the matrix all the rows and columns containing it".
I made the methods. In one, I find the largest number in the matrix. And in the second, I delete from the matrix the row and column that contains the largest number. But it works correctly only if the largest number is the only one. How to make, that deleted all lines and all columns in which the greatest number contains?
private void deleteRowCol() {
int[][] matrix = getMatrix();
int max = matrix[0][0];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (max < matrix[i][j]) {
max = matrix[i][j];
}
}
}
int[] m = findIdMax(matrix, max);
int[][] outMatrix = new int[matrix.length - 1][matrix[0].length - 1];
int r = 0;
for (int i = 0; i < outMatrix.length; i++) {
if (i > m[0] - 1) {
r = 1;
}
int c = 0;
for (int j = 0; j < outMatrix[0].length; j++) {
if (j > m[1] - 1) {
c = 1;
}
outMatrix[i][j] = matrix[i + r][j + c];
}
}
System.out.println(" ");
outputMatrix(outMatrix);
}
private int[] findIdMax(int[][] matrix, int max) {
int[] id = {0, 0};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (max == matrix[i][j]) {
id[0] = i;
id[1] = j;
}
}
}
return id;
}
expected output:
with this matrix
4 2 0 -3
4 -1 4 1
0 2 -4 3
-4 -1 -4 -2
should bring
-2 3
-1 -2
I haven't been able to find a fix for your current code. One issue is that you always assume 1 row and 1 column are deleted with int[][] outMatrix = new int[matrix.length - 1][matrix[0].length - 1];. If I put a loop around your code it would fail if the max is for example at positions 1,2 and 1,4 in the matrix (which should remove only 1 row, but 2 columns).
So perhaps someone else could take a closer look at your implementation and see a straight-forward fix without changing too much. Instead, I've thought about the use case from scratch and tried to complete the task myself. I ended up with the following code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Main{
private Set<Integer> rowsToDelete,
columnsToDelete;
public static void main(String[] a){
Main program = new Main();
int[][] matrix = program.getMatrix();
System.out.println("Before:");
program.prettyPrintMatrix(matrix);
System.out.println();
int[][] modifiedMatrix = program.deleteRowCol(matrix);
System.out.println("After:");
program.prettyPrintMatrix(modifiedMatrix);
}
private int[][] getMatrix(){
// Test:
return new int[][]{
{ 4, 2, 0,-3},
{ 4,-1, 4, 1},
{ 0, 2,-4, 3},
{-4,-1,-4,-2}
};
}
private int[][] deleteRowCol(int[][] matrix) {
int max = findMax(matrix);
determineCoordinatesMax(matrix, max);
// Some debug prints:
System.out.println("Maximum: "+max);
System.out.println("Rows to delete: "+rowsToDelete);
System.out.println("Columns to delete: "+columnsToDelete);
System.out.println();
int[][] modifiedMatrix = deleteRows(matrix);
modifiedMatrix = deleteColumns(modifiedMatrix);
return modifiedMatrix;
}
private int findMax(int[][] matrix){
int max = matrix[0][0];
for(int[] row : matrix){
for(int value : row){
if(value > max){
max = value;
}
}
}
return max;
}
private void determineCoordinatesMax(int[][] matrix, int max) {
rowsToDelete = new HashSet<>();
columnsToDelete = new HashSet<>();
for(int r=0; r<matrix.length; r++){
for(int c=0; c<matrix[r].length; c++){
if(matrix[r][c] == max){
rowsToDelete.add(r);
columnsToDelete.add(c);
}
}
}
}
private int[][] deleteRows(int[][] matrix){
int rowsToLeave = matrix.length - rowsToDelete.size();
int[][] modifiedMatrix = new int[rowsToLeave][];
int i = 0;
for(int r=0; r<matrix.length; r++){
if(!rowsToDelete.contains(r)){
modifiedMatrix[i] = matrix[r];
i++;
}
}
return modifiedMatrix;
}
private int[][] deleteColumns(int[][] matrix){
int columnsAlreadyDeleted = 0;
for(int columnToDelete : columnsToDelete){
// Delete the columns one by one:
int[][] modifiedMatrix = new int[matrix.length][matrix[0].length - 1];
for(int r=0; r<matrix.length; r++){
int i=0;
for(int c=0; c<matrix[r].length; c++){
if(c != columnToDelete - columnsAlreadyDeleted){
modifiedMatrix[r][i] = matrix[r][c];
i++;
}
}
}
columnsAlreadyDeleted++;
matrix = modifiedMatrix;
}
return matrix;
}
private void prettyPrintMatrix(int[][] matrix){
for(int[] row : matrix){
System.out.println(Arrays.toString(row));
}
}
}
The deletion of the columns could use some tweaking, since I now have three nested loops (loop over the columns to delete; inner loop over the matrix-rows; inner loop over the matrix-columns). But it works, and removes the rows and columns of the int[][] as expected.
You can see it in action here: Try it online.

Problem in extracting Even Columns from 2D Array

I'm trying to extract the entries of EVEN columns from the given 2D array.
The Code I have written is:
public static void main(String[] args) {
int [][] rearra = new int[5][3];
int[][] arra = { {01,02,03,04,05,06},
{11,12,13,14,15,16},
{21,22,23,24,25,26},
{31,32,33,34,35,36},
{41,42,43,44,45,46}};
rearra = method(arra);
for(int i=0; i<rearra.length; i++)
{
for(int j=0; j<rearra[0].length; j++)
System.out.println(rearra[i][j]);
}
}
static int[][] method(int [][] arr)
{
int temp = 3;
int [][] narra = new int[5][3];
//int nrow=0;
int ncol=0;
for (int row=0; row<5; row++){
for (int col=0; col<6; col++)
{
if ((arr[row][col]) % 2 == 0) {
narra[row][ncol] = (arr[row][col]);
ncol++;
}
}
}
return narra;
}
Now the output I want from this code should like this:
02 04 06
12 14 16
22 24 26
32 34 36
42 44 46
Can anyone guide me what's the problem in my program?
Move int ncol=0; inside outer loop:
for (int row=0; row<5; row++){
int ncol=0;
for (int col=0; col<6; col++)
{
Your idea is generally good, but you should also strive to write clean and understandable code. I will provide you with example that works for any array size and prints it nicely.
Your three main actions were all extracted into methods of their own, and thanks to that you can run it with any array.
Variable names have been replaced with meaningful ones so other people (and you sometimes in the future) can better understand what is going on.
Method for extracting even columns checks the length of each row, which needs not to be the same for all rows.
It works by checking if column index is even and if so, inserts into appropriate place in the new array.
I hope you will improve your skills by analyzing this example, good luck!
Full code:
public class ArrayExample {
public static void main(String[] args) {
int[][] arr = initializeArray();
int[][] evenColumnsOnly = getEvenColumns(arr);
printArray(evenColumnsOnly);
}
static int[][] initializeArray() {
int[][] arr = { {01,02,03,04,05,06},
{11,12,13,14,15,16},
{21,22,23,24,25,26},
{31,32,33,34,35,36},
{41,42,43,44,45,46}};
return arr;
}
static void printArray(int[][] arrayToPrint) {
for(int i = 0; i < arrayToPrint.length; i++) {
for(int j = 0; j < arrayToPrint[i].length; j++) {
System.out.print(String.format("%d\t", arrayToPrint[i][j]));
}
System.out.println();
}
}
static int[][] getEvenColumns(int [][] arr)
{
int [][] evenColumnsOnlyArray = new int[arr.length][];
for (int row = 0; row < arr.length; row++) {
int rowSize = arr[row].length / 2;
evenColumnsOnlyArray[row] = new int[rowSize];
for (int col = 0; col < arr[row].length; col++) {
if(col % 2 == 0 && col / 2 < rowSize) {
evenColumnsOnlyArray[row][col / 2] = arr[row][col];
}
}
}
return evenColumnsOnlyArray;
}
}

1-Dimensional array -> 2D array

So i'm a beginner;
The task is to convert a given string into the array, the string always has the first characcter as the amount of rows and the second character as the amount of columns.
My problem is to solve how to move the rest of the string 's' into the 2D array from the 1D array.
Thanks in advance!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split(" ");
int arows = Integer.parseInt(s[0]);
int acols = Integer.parseInt(s[1]);
int[][] cells = new int[arows][acols];
for (int col = 0; col < acols; col++){
for (int row = 0; row <= arows;row++){
cells[row][col] = Integer.parseInt(s[2]);
}
}
}
}
You need to implement a counter for your for-loops to iterate through the input string. What you are doing right now is to fill your 2D-Array with the third element of your string.
One solution would be to just declare a variable i = 2, and increment it for each pass of the inner for-loop.
int i = 2
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
Edit: removed <= in row loop, changed the initial value of the index to 2
This is the solution, you have to put another iterator, and initialize it to 2, so to skip the first two elements of s[]
int i = 2;
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}

Adding an array of strings into a 2D array [duplicate]

This question already has answers here:
How to add strings from one array into another array in Java
(3 answers)
Closed 8 years ago.
So I need to add an array of strings, into a two dimensional array called squares. The array squares is a 10 by 10 array in which the first row of initStrings will match up with squares.
IE - static String[] strings = {"hello"}
The h would be in the first location of the squares array, the e would be in the second and so on. Im wondering how to do this.
static String[] initStrings =
{
"...../...\\",
"..\\.......",
"......./..",
"..........",
"........\\.",
"..........",
"..........",
".....\\../.",
"..\\....../",
".........."
};
I know that I need to have a nested for loop. Something along the lines of
for (col = 0; col < 10; col++)
{
for (rows = 0; rows < 10; rows ++)
{
// what goes here?
}
}
is this what you want?
char[][] squares=new char[10][10];
String[] initStrings = { "...../....", "../.......", "......./..", "..........", "......../.", "..........", "..........", "...../../.", "../....../", ".........." };
int i=0;
for(char[] squareRow:squares)
squareRow=initStrings[i++].toCharArray();
This might help:
static String[] initStrings = { "...../...\", "..\.......", "......./..", "..........", "........\.", "..........", "..........", ".....\../.", "..\....../", ".........." };
char[][] squares = new char[10][10];
int row, col;
for (row = 0; row < 10; rows ++)
{
for (col = 0; col < 10; col++)
{
squares[row][col] = initStrings[row].charAt(col);
}
}
// print squares
for (row = 0; row < 10; rows ++)
{
for (col = 0; col < 10; col++)
{
System.out.print(squares[row][col] + " ");
}
System.out.print("\n");
}
Here's another possible solution. It's a bit overkill, but I like maps, and lists :) One advantage with this is that if you add a new string to your initStrings with more than 10 chars, it should still finish. But, maybe that would be bad...
String[] initStrings = {"...../...\\", "..\\.......", "......./..", "..........", "........\\.", "..........", "..........", ".....\\../.", "..\\....../", ".........." };
Map<Integer, List<String>> columnEntries = new TreeMap<Integer, List<String>>();
for(String str : initStrings) {
for(int i = 0; i < str.length(); i++) {
if(!columnEntries.containsKey(i)) {
columnEntries.put(i, new ArrayList<String>());
}
columnEntries.get(i).add(str.substring(i,i+1));
}
}
//Print results...
for(Entry<Integer, List<String>> e : columnEntries.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}

Categories