Converting arrays into a multi-dimensional array - Java - java

is there a way to convert three single dimensional arrays into a multi-dimensional one.
For example I have three arrays (text, retweets, geo) how can I merge them so it appears as:-
The arrays I want to merge are something along the lines of text = 'hello, 'hello'. retweets = '2,5' and geo = '19912, 929293'.
And should result in:-
combined =
[hello, 2, 19912
hello, 5, 929293]
and so one... All of the arrays are the same sizes. I know I should loop through while a for loop somehow but am not quite sure how to implement it.
Thanks to any response.

int count = ...;
String [] text = new String [count];
int [] retweets = new int [count];
int [] geo = new int [count];
// Fill arrays with data here
Object [] combined = new Object [count * 3];
for (int i = 0, j = 0; i < count; i++)
{
combined [j++] = text [i];
combined [j++] = retweets [i];
combined [j++] = geo [i];
}

public static void main(String[] args) {
String[] array1 = { "hello1", "A2", "X19912" };
String[] array2 = { "hello2", "B2", "Y19912" };
String[] array3 = { "hello3", "C2", "Z19912" };
String[] copyArrays = new String[array1.length + array2.length
+ array3.length];
System.arraycopy(array1, 0, copyArrays, 0, array1.length);
System.arraycopy(array2, 0, copyArrays, array1.length, array2.length);
System.arraycopy(array3, 0, copyArrays, array1.length + array2.length,
array3.length);
String[][] array = new String[3][3];
int index = 0;
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++) {
array[i][j] = copyArrays[index++];
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
Output:
hello1 A2 X19912
hello2 B2 Y19912
hello3 C2 Z19912
This code will first copy the given arrays into a new array. Then it will insert all elements of copyArrays into a 2d array using for loop .

String[] text =...;
int[] retweets =...;
int[] geo =...;
int len = text.length;
List<List<Object>> items = new ArrayList<>();
for (int i = 0; i < len; i++) {
List<Object> item = new ArrayList<>();
item.add(text[i]);
item.add(retweets[i]);
item.add(geo[i]);
items.add(item);
}

a clever way of "toTableFormTheArrays" is:
public static String[][] to2DArray(String[]... yourArrays){
return yourArrays;
}
then the code is:
String[] text = {"hello", "hello"};
String[] retweets = {2, 5};
String[] geo = {19912, 929293};
String[][] yourTableForm2DArray = to2DArray(text, retweets, geo);
note: can change types, multi calls of to2darray for other D, maybe.

String[] text = {"hello", "hello"};
int[] retweets = {2, 5};
int[] geo = {19912, 929293};
//create table of strings for each array
Object[][] combined = new Object[text.length][3];
//load information into table, converting all information into Strings
for(int row = 0; row<text.length; row++){
combined[row][0] = text[row];
combined[row][1] = retweets[row];
combined[row][2] = geo[row];
}
This creates a multidimensional array that should look like this:
[[hello, 2, 19912], [hello, 5, 929293 ]]

Related

Java how to copy values from 2D array to regular array row by row

I have the 2D array and printed them out backward. What I am trying to achieve is to copy each line of printed row to a regular array. Is it possible to do that?
Integer[][] testList;
testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
for (int i = 0; i < testList.length; i++) {
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] + " ");
}
System.out.println();
}
This will copy any size 2D array of ints.
int[][] testData = { { 1, 2, 3 },{}, null, { 4, 5, 6, 7 },null,{ 8, 9 },
{ 10, 11, 12 } };
int[] result = copy2DArrays(testData);
System.out.println(Arrays.toString(result));
prints
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
First, compute size of result array. This also handles null rows.
if a null row is encountered, replace with an empty array for copy phase.
Allocate the return array of computed size
Then for each row
iterate thru the row, copying the value to result array indexed by k
When done, return the resultant array.
public static int[] copy2DArrays(int[][] array) {
int size = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
// replace null row with empty one
array[i] = new int[]{};
continue;
}
size += array[i].length;
}
int k = 0;
int[] result = new int[size];
for (int[] row : array) {
for (int v : row) {
result[k++] = v;
}
}
return result;
}
Another, simpler option is using streams.
stream the "2D" array
only pass nonNull rows
flatten each row into a single stream
then gather them into an array.
int[] array = Arrays.stream(testData)
.filter(Objects::nonNull)
.flatMapToInt(Arrays::stream)
.toArray();
You can create a new array and then copy the values into it:
for (int i = 0; i < testList.length; i++) {
int[] copy = new int[testList[i].length];
int copyIndex = 0;
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] + " ");
copy[copyIndex++] = testList[i][j];
}
}
The Arrays class gives you a lot of nifty features:
public static void main(String[] args) {
Integer[][] testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
int max = 0;
for (Integer[] row : testList) {
max = Math.max(max, row.length);
}
Integer[][] copy = new Integer[testList.length][max];
for (int i = 0; i < testList.length; i++) {
copy[i] = Arrays.copyOf(testList[i], copy[i].length);
}
for (int i = 0; i < testList.length; i++) {
System.out.println("Source " + i + ": " + Arrays.toString(testList[i]));
System.out.println("Copy " + i + ": " + Arrays.toString(copy[i]));
}
}

How to covert comma separated string to a 2D array in Java?

For example I have some comma separated strings
"aron, IA52, 20"
"john, IA61, 23"
"kleo, IA32, 42"
How can I convert them to a 2 dimensional array in the easiest way possible?
As already pointed out in comments, you should use split() while iterating over your comma separated string list and populate your array accordingly. Here is sample code to give you some idea:
List<String> input = Arrays.asList("aron, IA52, 20", "john, IA61, 23", "kleo, IA32, 42");
String[][] array = new String[3][3];
int row = 0;
// Loop Over Comma Separated List and split each string to populate 2D array
for (String commaSeparatedStr : input) {
String[] parts = commaSeparatedStr.split(",");
System.arraycopy(parts, 0, array[row], 0, parts.length);
row++;
}
// Print array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(array[i][j]);
System.out.println();
}
This prints:
aron IA52 20
john IA61 23
kleo IA32 42
The provided function will parse the string to the 2D matrix.
Below is the format of the string that you need to provide to this function.
1.2,2.3,3.5\n3.1,4.70,5.0
function
public double[][] parseStingToArray(String str) {
System.out.println(str);
String arr1[] = str.split("\n");
double[][] ans = new double[arr1.length][];
for (int i = 0; i < arr1.length; i++) {
String[] col = arr1[i].split(",");
ans[i] = new double[col.length];
for (int j = 0; j < col.length; j++) {
ans[i][j] = Double.parseDouble(col[j]);
}
}
doubleArray = ans;
return ans;
}

java incrementing with for works only once

City[] array = new City[6];
String [] arr = {"Paris","London","Rome","Los Angeles","New York","San Francisco"};
int [] arr2 = {200000, 100000, 80000, 60000, 50000, 45000};
String [] arr3 = {"Breitzel", "Statute of Liberty", "Tramways"};
for (int i = 0; i < 6; i++){
if (i<3){
City V = new City (arr[i], "EU", tab2[i]);
array[i] = V;
}
else {
for (int j = 0; j < 3; j++){
Capitale C = new Capitale (arr[i], "USA", arr2[i], arr3[j]);
array[i] = C;
}
}
}
The first incrementing loop works well, the one that creates cities (System.out.printline shows that City[] get 6 elements, which are the 6 cities.
BUT : the 3 American cities should each be assigned an element of arr3. This doesn't work. j doesn't get incremented and all 3 American cities get "Tramways".
I don't see why...
On the contrary, j is being incremented.
But each iteration of the internal loop is overwriting the results of the prior iteration.
The last iteration has j = 2, and arr3[2] is "Tramways".
I think you'll get the result you're looking for with this.
for (int i = 0; i < 6; i++){
if (i<3){
City V = new City (arr[i], "EU", tab2[i]);
array[i] = V;
}
else {
Capitale C = new Capitale (arr[i], "USA", arr2[i], arr3[j - 3]);
array[i] = C;
}
}
That said, the code isn't all that clear. The magic value of 3 isn't clear.
You could address this with a named constant:
final int INDEX_OF_FIRST_CAPITALE = 3;
Or by having arr3 be parallel to the other two arrays
String [] arr3 = { null, null, null, "Breitzel", "Statute of Liberty", "Tramways"};
Or by using a map from capital name to attraction.
Map<String,String> = new HashMap<String,String>();

Java - Partially convert 2D string to 2D Integer ArrayList

I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList.
This is the function that can help you.
public void ArrayList<ArrayList<Integer>> convert2DStringTo2DIntegerArray(String[][] original) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < original.length; i++)
{
ArrayList<Integer> tempArray = new ArrayList<Integer>();
for (int j = 0; j < original[i].length; j++)
{
tempArray.add(Integer.valueOf(original[i][j]));
}
list.add(tempArray);
}
return list;
}
Updated. To convert multidimensional array of integers represented as strings:
import java.util.List;
import java.util.ArrayList;
public class Convert
{
public static void main(String[] args)
{
List<List<Integer>> list = convert2DStringToList(new String[][]{ {"0", "1", "2"}, {"3", "4", "5"}, {"100", "200", "300", "500"}, {"22"} });
System.out.println(list.toString());
}
public static List<List<Integer>> convert2DStringToList(String[][] original)
{
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < original.length; i++)
{
List<Integer> subList = new ArrayList<>();
list.add(subList);
for (int j = 0; j < original[i].length; j++)
{
subList.add(Integer.valueOf(original[i][j]));
}
}
return list;
}
}
For given code the output is [[0, 1, 2], [3, 4, 5], [100, 200, 300, 500], [22]].

2-dimensional array with given number [duplicate]

Here is the code I have so far:
public static int mode(int[][] arr) {
ArrayList<Integer> list = new ArrayList<Integer>();
int temp = 0;
for(int i = 0; i < arr.length; i ++) {
for(int s = 0; s < arr.length; s ++) {
temp = arr[i][s];
I seem to be stuck at this point on how to get [i][s] into a single dimensional array. When I do a print(temp) all the elements of my 2D array print out one a time in order but cannot figure out how to get them into the 1D array. I am a novice :(
How to convert a 2D array into a 1D array?
The current 2D array I am working with is a 3x3. I am trying to find the mathematical mode of all the integers in the 2D array if that background is of any importance.
In Java 8 you can use object streams to map a matrix to vector.
Convert any-type & any-length object matrix to vector (array)
String[][] matrix = {
{"a", "b", "c"},
{"d", "e"},
{"f"},
{"g", "h", "i", "j"}
};
String[] array = Stream.of(matrix)
.flatMap(Stream::of)
.toArray(String[]::new);
If you are looking for int-specific way, I would go for:
int[][] matrix = {
{1, 5, 2, 3, 4},
{2, 4, 5, 2},
{1, 2, 3, 4, 5, 6},
{}
};
int[] array = Stream.of(matrix) //we start with a stream of objects Stream<int[]>
.flatMapToInt(IntStream::of) //we I'll map each int[] to IntStream
.toArray(); //we're now IntStream, just collect the ints to array.
You've almost got it right. Just a tiny change:
public static int mode(int[][] arr) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
// tiny change 1: proper dimensions
for (int j = 0; j < arr[i].length; j++) {
// tiny change 2: actually store the values
list.add(arr[i][j]);
}
}
// now you need to find a mode in the list.
// tiny change 3, if you definitely need an array
int[] vector = new int[list.size()];
for (int i = 0; i < vector.length; i++) {
vector[i] = list.get(i);
}
}
I'm not sure if you're trying to convert your 2D array into a 1D array (as your question states), or put the values from your 2D array into the ArrayList you have. I'll assume the first, but I'll quickly say all you'd need to do for the latter is call list.add(temp), although temp is actually unneeded in your current code.
If you're trying to have a 1D array, then the following code should suffice:
public static int mode(int[][] arr)
{
int[] oneDArray = new int[arr.length * arr.length];
for(int i = 0; i < arr.length; i ++)
{
for(int s = 0; s < arr.length; s ++)
{
oneDArray[(i * arr.length) + s] = arr[i][s];
}
}
}
change to:
for(int i = 0; i < arr.length; i ++) {
for(int s = 0; s < arr[i].length; s ++) {
temp = arr[i][s];
"How to convert a 2D array into a 1D array?"
String[][] my2Darr = .....(something)......
List<String> list = new ArrayList<>();
for(int i = 0; i < my2Darr.length; i++) {
list.addAll(Arrays.asList(my2Darr[i])); // java.util.Arrays
}
String[] my1Darr = new String[list.size()];
my1Darr = list.toArray(my1Darr);
I know its already been answered but here is my take. This function will take a 2d array input and return a 1d array output.
public int[] output(int[][] input){
int[] out = new int[input.length * input[0].length]
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
out[i + (j * input.length)] = input[i][j]
}
}
return out;
}
System.arraycopy should be faster than anything we can write. Also use the built-in java iterator on rows. Here is an example for double arrays. You should be able to use any type or class. If your rows are all the same length, then totalNumberElements = array2D.length * array2D[0].length;
static double[] doubleCopyToOneD(double[][] array2D, int totalNumberElements) {
double[] array1D = new double[totalNumberElements];
int pos = 0;
for (double[] row: array2D) {
System.arraycopy(row, 0, array1D, pos, row.length);
pos += row.length;
}
return array1D;
}
import java.util.*;
public class Main {
public static int A[][] = new int[3][3];
public static int B[] = new int[9];
public static void main(String[] args) {
int temo = 0,t;
Scanner s = new Scanner(System.in);
System.out.println("Enter No for Matrix A");
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A.length; col++) {
A[row][col] = s.nextInt();
}
System.out.print("\n");
}
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A.length; col++) {
t= A[row][col];
B[temo]= t;
temo++;
}
System.out.print("\n");
}
System.out.print("After Converted to one d \n");
for(int i =0;i<B.length;i++) {
System.out.print(" "+B[i]+" ");
}
}
}

Categories

Resources