Jagged Arrays in Java: Converting char[][] and ArrayList<ArrayList<char>> - java

How can I convert the following so that it is essentially a jagged nested ArrayList of ArrayLists, with each row/col a list of chars?
//Following excerpt from https://www.geeksforgeeks.org/jagged-array-in-java/
int r = 5;
//Need this to have capacity to hold list of chars (eg, each row/col index can be empty, //have 1 char, or multiple chars
char toFill = new Variable(" ");
// Declaring 2-D array with 5 rows... need it to be ArrayList<ArrayList<char>>
char matrix[][] = new Variable[r][];
// Creating a 2D array such that first row
// has 1 element, second row has two
// elements and so on.
for (int i=0; i<matrix.length; i++) {
matrix[i] = new char[i + 1];
}
// Initializing array
int count = 0;
for (int i=0; i<matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = toFill;
}
}

Actually lists are dynamic structures, you don't need to pre-define their sizes as with static structures like arrays. He is a sample program directly translating the jagged array into a jagged list of lists. I tried to keep as much of the structure as possible so as to make it easier for you to understand. The code still looks kind of "array-ish" (which I actually don't like because it is somewhat unnatural), but I hope you get the idea.
package de.scrum_master.stackoverflow.q60367936;
import java.util.ArrayList;
import java.util.List;
/**
* Demonstrate 2-D jagged array/list such that first row has 1 element,
* second row has two elements and so on.
*/
class Main {
private static void jaggedArray() {
int r = 5;
// Declaring 2-D array with 5 rows
int arr[][] = new int[r][];
// Creating a 2D array such that first row has 1 element, second row has two elements and so on.
for (int i = 0; i < arr.length; i++)
arr[i] = new int[i + 1];
// Initializing array
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D Jagged Array");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
private static void jaggedArrayList() {
int r = 5;
// Declaring 2-D list of lists
List<List<Integer>> arr = new ArrayList<>();
// Adding empty sub list to main list
for (int i = 0; i < r; i++)
arr.add(new ArrayList<Integer>());
// Initializing 2-D list
int count = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j <= i; j++)
arr.get(i).add(count++);
// Displaying the values of 2D Jagged list
System.out.println("Contents of 2D Jagged ArrayList");
for (List<Integer> list : arr) {
for (Integer i : list)
System.out.print(i + " ");
System.out.println();
}
}
public static void main(String[] args) {
jaggedArray();
System.out.println("\n------------------------------\n");
jaggedArrayList();
}
}
Console log:
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
------------------------------
Contents of 2D Jagged ArrayList
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
As you can see, both the array and the list variant yield identical results. Whether you use a List<List<Integer>> or a List<List<Char>> does not matter for the algorithm.

Related

Insert value to 2d array

I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me

Transpose java error

I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).

How to sort 2D array(int) without converting it into 1D array in java?

How can I sort 2d array without converting it into 1d array.
This is what I have done -
private int[][] data2D = {{1,2,3},{6,8},{3,2,5,2}};
private void sortCustom(){
int totalElements = 0;
// calculating total elements
for(int[] i : data2D){
totalElements = totalElements+i.length;
}
int[] data1D = new int[totalElements];
int m = 0 ;
// converting 2D data into 1D
for(int i=0 ; i<data2D.length ; i++ ){
for(int j=0 ; j<data2D[i].length ; j++){
data1D[m++] = data2D[i][j];
}
}
// sorting data
Arrays.sort(data1D);
//converting 1D data into 2D
int n=0;
for(int i=0 ; i<data2D.length ; i++){
for(int j=0 ; j<data2D[i].length ; j++){
data2D[i][j] = data1D[n++];
}
}
// print sorted data
for(int i=0 ; i<data2D.length ; i++){
for(int j=0 ; j<data2D[i].length ; j++){
System.out.print(data2D[i][j]+" ");
}
System.out.println();
}
}
output :
1 2 2
2 3
3 5 6 8
As you can see I am able to sort 2d array after converting it into 1d. My question is how can I sort 2d array without converting it into 1d array?
I want to short all the values , not row by row
You can use bubble sorting, for a simple array you must use 2 nested for-loops, so for a 2d array you must use 3 nested for-loops:
for(int i = 0; i < data2D.length; i++){
for(int j = 0; j < data2D[0].length; j++){
for(int k = 0; k < data2D[j].length; k++){
if(data2D[i][k]>data2D[i][k+1]){
int temp = data2D[i][k];
data2D[i][k] = data2D[i][k+1];
data2D[i][k+1] = temp;
}
}
}
}
Use sorting(bubblesort, quicksort) algorithms. Choose for your need, if your data is small it does not matter at all. Otherwise choose O(nlogn) algorithms
Just try something like this:
Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.
double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };
java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
public int compare(double[] a, double[] b) {
return Double.compare(a[0], b[0]);
}
});

Combining elements in jagged 2D arrays into one new jagged 2D array (Deep Copy issue)

Given two jagged arrays: a & b where a + b will always have the same # of rows:
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
how exactly can I manipulate a new jagged array c to return:
{ {1,2,7}, {4,5,6,8,9,0} }?
Here's what I have so far:
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
//rest of my code for assigning the values into the appropriate position works.
The trouble arises, as you all can see, that I am performing a deep copy, which, on the second iteration of the for-loop, is setting ALL rows to a length of the length of the current row on the step of the iteration.
Flaw in your approach
You are creating a new 2D array object each iteration of your loop. Each time through, you are reassigning c, thus throwing out all of your previous work. Additionally, placing a number in both set of brackets at the same time results in each row having the same length.
Using your example, the first time through the loop, c is assigned to a 2D array with two rows, each of length three. The second time through the loop, you throw out your previous 2D array and create a new one having two rows, each of length six.
But what you need to be doing is creating a new row each time through the loop, not the entire 2D array.
Solution
First, we create a 2D array called c and specify that it has a.length rows. We don't put a value in the second bracket, because that would indicate that all of the rows are of the same length. So at this point, c does not know about row length. It just knows how many rows it can have. Keep in mind: c doesn't actually have any rows yet, just a capacity for a.length rows.
Next, we must create the rows and assign a length/capacity to them. We set up our loop to run as many times as there are rows. The current row index is denoted by i, and therefore, c[i] refers to a specific row in the 2D c array. We use new int[] to create each individual row/array, but inside the brackets, we must specify the length of the current row. For any row c[i], its length is given by the sum of the lengths of a[i] and b[i]; that is, a[i].length + b[i].length.
What we are left with is an array c that contains rows/arrays, each with a set length/capacity that matches the sum of the corresponding rows lengths in a and b.
Keep in mind that c still does not contain any integer values, only containers that are of the correct size to hold the values in a and b. As you mentioned, you already have code to populate your array with values.
int[][] c = new int[a.length][];
for (int i = 0; i < a.length; i++) {
c[i] = new int[a[i].length + b[i].length];
}
When initialize Java 2D array, lets consider it as a table; you only have to give the number of rows and in each row of your table can have different number of columns.
Eg. Say we have a 2D array call c defined as follows,
int[][] c = new int[10][];
It says you defined c contains 10 of int[] elements. But in order to use it you have to define the number of columns each row has.
Eg. Say we have 3 columns in the second row
int c[1] = new int[3];
So in this example you have to add the column values of 2D arrays a and b to calculate the resultant array which is c.
c[i] = new int[a[i].length + b[i].length];
This will give you what you expected.
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
int[][] c = new int[a.length][];
for(int i = 0; i<a.length; i++){
c[i] = new int[a[i].length + b[i].length];
for (int j=0;j< a[i].length; j++) {
c[i][j] = a[i][j];
}
int length = a[i].length;
for (int j=0;j< b[i].length; j++) {
c[i][length+j] = b[i][j];
}
}
Try c[i] = new int[a[i].length + b[i].length]
int[][] c = new int[a.length][];
for(int i = 0; i < c.length; i++){
c[i] = new int[a[i].length + b[i].length];
int x = 0;
for (int num : a[i]) {
c[i][x] = num;
x++;
}
for (int num : b[i]) {
c[i][x] = num;
x++;
}
}
or even simpler...
int[][] c = new int[a.length][];
for(int i = 0; i < c.length; i++){
c[i] = new int[a[i].length + b[i].length];
System.arraycopy(a[i], 0, c[i], 0, a[i].length);
System.arraycopy(b[i], 0, c[i], a[i].length, b[i].length);
}
Try this one:
int[][] c = new int[a.length][];
for(int i = 0; i<a.length; i++){
c[i] = new int [a[i].length + b[i].length];
int j;
for(j=0; i < a[i].length; j++){
c[i][j] = a[i][j];
}
for(int k=0; i < b[i].length; k++){
c[i][j+k] = b[i][j];
}
}
public static void main(String [] args) {
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
for(int i = 0; i<a.length; i++){
for (int j = 0; j < a[i].length+b[i].length; j++) {
if(j< a[i].length){
c[i][j]=a[i][j];
}
if(j< a[i].length+b[i].length && j>= a[i].length){
c[i][j]=b[i][j-a[i].length];
}
}
}
for(int i = 0; i<a.length; i++){
for (int j = 0; j < a[i].length+b[i].length; j++) {
System.out.print(c[i][j]);
}
System.out.println();
}
}
This works in my system ...........

Java 2-D selection sort

I am preparing for an exam, and we are likely to be tasked with sorting a two dimensional array of ints. Sorted meaning the first row, first column is the lowest and the last row, last column is the highest.
I approached the task by creating a 1-D array, and then populating it with all the values in the 2d array. Then, I passed it through a sorting method. Finally, I wrote each value of the sorted array back into the 2d array and returned it.
This sort of worked, as you can see from the output below. I am confused as to where my process is breaking down, I would appreciate any input.
Input:
int[][] nums = {{1,5,9},{8,9,3},{0,7,6}};
output:
0 0 0
0 0 0
0 0 1
public int[][] sort2D(int[][]nums){
int[] temp = new int[((nums.length+1)*(nums.length+1))];//make one long array
for(int i =0; i<nums.length; i++){ //populate
int counter = 0; //indices for long array
for(int j = 0; j<nums[i].length; j++){
System.out.println(temp[counter]);
temp[counter] = (int)nums[i][j];
counter++;
}
}
temp = sort(temp); //sort it (verified code)
for(int i = 0; i<nums.length; i++){ //reverse the above process
int counter = 0;
for(int j = 0; j<nums.length; j++){
nums[i][j] = temp[counter];
counter++;
}
}
return nums;
}
The first thing I think you're doing wrong is this:
int[] temp = new int[((nums.length+1)*(nums.length+1))];//make one long array
nums.length +1 = 4 in your case. you are copying your 3*3 array into a 4*4 array.
This has the funny effect of adding 5 0's to your result. (temp[9] till temp[15] will be 0 filled)
After you sort, these 0's will show up
the place where your code breaks down is:
for(int i =0; i<nums.length; i++){ //populate
>> int counter = 0; //indices for long array
for(int j = 0; j<nums[i].length; j++){
System.out.println(temp[counter]);
temp[counter] = (int)nums[i][j];
counter++;
}
}
You initialize the counter to 0 every time you go through one of your outer arrays.
this means that on the 3rd pass (last array) you overwrite temp[0], temp1 and temp[2] with nums[2][0], nums2, nums[2][2]
I assume in your actual code, you do
int counter = 0; //indices for long array
for(int i =0; i<nums.length; i++){ //populate
for(int j = 0; j<nums[i].length; j++){
System.out.println(temp[counter]);
temp[counter++] = (int)nums[i][j];
}
}
You could also use System.arrayCopy, especially if you know the length and suchlike.

Categories