Dynamic Row Addition
Problem Statement
Write a Java program that allows users to interactively add rows to a jagged array, specifying the length and elements of each row. The program should store the jagged array dynamically, support adding multiple rows with different lengths, and print the resulting array after each addition. Test the implementation with multiple row additions, including edge cases like empty rows or no additions. You can visualize this as building a flexible grid where users can append new rows of varying sizes, like adding shelves of different lengths to a bookcase and filling them with books.
Input:
- Number of rows to add (e.g., 3).
- For each row: length of the row and its elements (e.g., length = 3, elements = [1, 2, 3]). Output:
- The jagged array after each row addition, displayed as a 2D array (e.g.,
[[1, 2, 3], [4, 5], [6, 7, 8, 9]]after three additions). Constraints: - The number of rows to add is between 0 and 100.
- Each row’s length is between 0 and 100.
- Elements are integers between -10^4 and 10^4.
- The input is valid (row lengths and elements are within constraints). Example:
- Input: Add 3 rows:
- Row 1: length = 3, elements = [1, 2, 3]
- Row 2: length = 2, elements = [4, 5]
- Row 3: length = 4, elements = [6, 7, 8, 9]
- Output after each addition:
After adding row 1: [[1, 2, 3]] After adding row 2: [[1, 2, 3], [4, 5]] After adding row 3: [[1, 2, 3], [4, 5], [6, 7, 8, 9]] - Input: Add 1 row:
- Row 1: length = 0, elements = []
- Output:
[[]]
Pseudocode
FUNCTION addRow(jaggedArray, rowLength, elements)
IF rowLength < 0 OR elements length not equal to rowLength THEN
RETURN
ENDIF
CREATE newRow array of size rowLength
FOR i from 0 to rowLength - 1
SET newRow[i] to elements[i]
ENDFOR
ADD newRow to jaggedArray
ENDFUNCTION
FUNCTION main()
SET jaggedArray to empty dynamic array
SET testCases to list of (rowLength, elements) pairs
FOR each (rowLength, elements) in testCases
PRINT current jaggedArray
CALL addRow(jaggedArray, rowLength, elements)
PRINT updated jaggedArray
ENDFOR
ENDFUNCTION
Algorithm Steps
- Initialize an empty dynamic structure (
ArrayList<int[]>) to store the jagged array. - For each row addition: a. Validate the input: ensure row length is non-negative and matches the number of elements provided. b. Create a new array of the specified length and populate it with the provided elements. c. Add the new array as a row to the jagged array.
- Print the jagged array before and after each addition to show the changes.
- In the
mainmethod, simulate user input with predefined test cases, including rows of different lengths, empty rows, and edge cases, to verify correctness.
Java Implementation
import java.util.ArrayList;
public class DynamicRowAddition {
// Adds a row to the jagged array with specified length and elements
public void addRow(ArrayList<int[]> jaggedArray, int rowLength, int[] elements) {
// Validate input
if (rowLength < 0 || elements == null || elements.length != rowLength) {
return;
}
// Create new row and copy elements
int[] newRow = new int[rowLength];
for (int i = 0; i < rowLength; i++) {
newRow[i] = elements[i];
}
// Add row to jagged array
jaggedArray.add(newRow);
}
// Main method to test addRow with various inputs
public static void main(String[] args) {
DynamicRowAddition adder = new DynamicRowAddition();
// Test case 1: Add multiple rows with different lengths
System.out.println("Test case 1: Adding multiple rows");
ArrayList<int[]> jaggedArray1 = new ArrayList<>();
int[][] testRows1 = {
{1, 2, 3}, // Row of length 3
{4, 5}, // Row of length 2
{6, 7, 8, 9} // Row of length 4
};
for (int i = 0; i < testRows1.length; i++) {
System.out.println("Before adding row " + (i + 1) + ":");
printJaggedArray(jaggedArray1);
adder.addRow(jaggedArray1, testRows1[i].length, testRows1[i]);
System.out.println("After adding row " + (i + 1) + ":");
printJaggedArray(jaggedArray1);
}
// Test case 2: Add a single empty row
System.out.println("\nTest case 2: Adding an empty row");
ArrayList<int[]> jaggedArray2 = new ArrayList<>();
System.out.println("Before adding row:");
printJaggedArray(jaggedArray2);
adder.addRow(jaggedArray2, 0, new int[]{});
System.out.println("After adding row:");
printJaggedArray(jaggedArray2);
// Test case 3: Add rows with negative numbers
System.out.println("\nTest case 3: Adding rows with negative numbers");
ArrayList<int[]> jaggedArray3 = new ArrayList<>();
int[][] testRows3 = {
{-1, -2}, // Row of length 2
{-3, -4, -5} // Row of length 3
};
for (int i = 0; i < testRows3.length; i++) {
System.out.println("Before adding row " + (i + 1) + ":");
printJaggedArray(jaggedArray3);
adder.addRow(jaggedArray3, testRows3[i].length, testRows3[i]);
System.out.println("After adding row " + (i + 1) + ":");
printJaggedArray(jaggedArray3);
}
// Test case 4: No rows added
System.out.println("\nTest case 4: No rows added");
ArrayList<int[]> jaggedArray4 = new ArrayList<>();
System.out.println("Jagged array:");
printJaggedArray(jaggedArray4);
}
// Helper method to print jagged array
private static void printJaggedArray(ArrayList<int[]> jaggedArray) {
if (jaggedArray == null || jaggedArray.isEmpty()) {
System.out.println("[]");
return;
}
System.out.println("[");
for (int i = 0; i < jaggedArray.size(); i++) {
System.out.print(" [");
if (jaggedArray.get(i).length == 0) {
System.out.print("]");
} else {
for (int j = 0; j < jaggedArray.get(i).length; j++) {
System.out.print(jaggedArray.get(i)[j]);
if (j < jaggedArray.get(i).length - 1) {
System.out.print(", ");
}
}
System.out.print("]");
}
System.out.println();
}
System.out.println("]");
}
}
Output
Running the main method produces:
Test case 1: Adding multiple rows
Before adding row 1:
[]
After adding row 1:
[
[1, 2, 3]
]
Before adding row 2:
[
[1, 2, 3]
]
After adding row 2:
[
[1, 2, 3]
[4, 5]
]
Before adding row 3:
[
[1, 2, 3]
[4, 5]
]
After adding row 3:
[
[1, 2, 3]
[4, 5]
[6, 7, 8, 9]
]
Test case 2: Adding an empty row
Before adding row:
[]
After adding row:
[
[]
]
Test case 3: Adding rows with negative numbers
Before adding row 1:
[]
After adding row 1:
[
[-1, -2]
]
Before adding row 2:
[
[-1, -2]
]
After adding row 2:
[
[-1, -2]
[-3, -4, -5]
]
Test case 4: No rows added
Jagged array:
[]
Explanation:
- Test case 1: Adds three rows of lengths 3, 2, and 4, building the jagged array incrementally.
- Test case 2: Adds a single empty row, resulting in
[[]]. - Test case 3: Adds two rows with negative numbers, lengths 2 and 3.
- Test case 4: Shows an empty jagged array when no rows are added.
How It Works
- Step 1: Initialize an
ArrayList<int[]>to store the jagged array dynamically. - Step 2: For each row addition in
addRow:- Validate: Ensure
rowLengthis non-negative and matcheselements.length. - Create a new
int[]of sizerowLengthand copyelementsinto it. - Add the new row to the
jaggedArray.
- Validate: Ensure
- Example Trace (Test case 1):
- Start:
jaggedArray = []. - Add row 1:
[1, 2, 3]→[[1, 2, 3]]. - Add row 2:
[4, 5]→[[1, 2, 3], [4, 5]]. - Add row 3:
[6, 7, 8, 9]→[[1, 2, 3], [4, 5], [6, 7, 8, 9]].
- Start:
- Main Method: Simulates user input with test cases, including multiple rows, an empty row, negative numbers, and no additions, printing the array before and after each addition.
- Dynamic Property: Uses
ArrayListfor dynamic row addition, allowing flexible row lengths.
Complexity Analysis Table
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Add Row | O(n) | O(n) |
| Full Algorithm | O(N) | O(N) |
Note:
- n is the length of the row being added.
- N is the total number of elements across all rows added.
- Time complexity: O(n) per row addition (copying elements to new array), O(N) for all additions.
- Space complexity: O(n) per row (new array), O(N) for the entire jagged array.
- Worst case: O(N) time and space for adding all elements across multiple rows.
✅ Tip: Use
ArrayList<int[]>for dynamic row management. Test with empty rows, varying lengths, and negative numbers to ensure flexibility and correctness.
⚠ Warning: Validate that the number of elements matches the specified row length to avoid
ArrayIndexOutOfBoundsException. Ensure the jagged array is initialized to avoidNullPointerException.