Creating a multi-dimensional String array from a method array parameter - java

I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!

You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.

I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.

I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...

I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)

Related

Inputting multiple arrays of integers into an arrayList and then printing each array

I'm looking to create a dynamic amount of arrays of random integers and then put them into an array list. Later I want to use each of these arrays separately to test for quick sort functionality. I'm having problems with adding the object List[] into the ArrayList.
//Create dynamic amount of random arrays
public static ArrayList<int[]> Randomizer(int arrays, int size, int seed){
ArrayList<int[]> Tests = new ArrayList<int[]>(arrays);
int[] List = new int[size];
for (int j = 0; j < arrays; j++){
Random r = new Random(seed+j);
for(int i = 0; i < size; i++){
List[i] = r.nextInt(5*size);//Multiplier for how big the numbers get
System.out.print(List[i] + ",");
}
System.out.println();
Tests.add(j, List);
}
return Tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> Test = Randomizer(tests,size,10); //1st = Number of Tests
//2nd = Number of Digits
//3rd = seed for Randomizer
for(int i = 0; i < Test.size(); i++){
System.out.println(Test.get(i));
}
}
}
The problem with your code was that you were storing the same array 5 times into the ArrayList, so when printing during generation it printed correct numbers, but later you couldn't get them out. Each iteration of the for loop was overwriting the values generated earlier.
Here is the corrected code:
private static ArrayList<int[]> randomizer(int arrays, int size, int seed){
ArrayList<int[]> tests = new ArrayList<>(arrays);
for (int j = 0; j < arrays; j++) {
int[] list = new int[size];
Random r = new Random(seed + j);
for(int i = 0; i < size; i++) {
list[i] = r.nextInt(5 * size); // Multiplier for how big the numbers get
}
tests.add(j, list);
}
return tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> arrays = randomizer(tests, size, 10);
for (int i = 0; i < arrays.size(); i++){
int[] ints = arrays.get(i);
for (int j = 0; j < ints.length; j++) {
System.out.print(ints[j] + ",");
}
System.out.println();
}
}
Basically you needed to move the int[] list = new int[size]; line inside the for loop, so that you are actually creating new arrays instead of using the same one each time.
You can now replace the printing loop in the main() method with whatever you like, like your quick sort tests. Let me know if anything still doesn't work.

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 ...........

2D Array in Java with number manipulation

My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}

Create a 2D array and initialize every element to be the value of i * j where i and j are the 2 indices (for instance, element [5][3] is 5 * 3 = 15)

I am truly stuck here on how to do this. I got as far as creating the 10x10 array and making variables i and j - not far at all. I thought about the use of loops to initialize every element, but I just don't know how to go about doing it. Any help is appreciated, thanks.
public class arrays {
public static void main(String[] args) {
int[][] array = new int[10][10];
int i = 0, j = 0;
}
}
I was thinking of using a do while loop or for loop.
Psuedo-code:
for i = 0 to 9
for j = 0 to 9
array[i][j] = i*j
Converting this to Java should be a snap.
Create two nested for loops, one for i, and one for j, looping over all valid indices. In the body of the inner for loop, assign the computed product to the 2D array element.
You will need two for loops inside each other:
int[][] array = new int[10][10];
for (int x = 0; x < array.length; ++x)
{
for (int y = 0; y < array[y].length; ++y)
{
int product = x * y;
// put the value at the right place
}
}
You can read this as:
For each x value, iterate over the ten y values and do...
int [][] array = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
//initialize every element
array[i][j] = i + j;
}
}

ArrayIndexOutOfBoundsException for my PrintList function and I have no idea why

I am writing a really simple program which automatically extends the array when the user reaches the limit of the current array.
The problem is that I am getting a java.lang.ArrayIndexOutOfBoundsException when I run my PrintList method and I really don't know why. It's working perfectly if I use a random number, which is bigger than the array (e.g. 500), but if I use
for (int i = 0; i < stringArray.length; i++)
or
for (int i = 0; i <= stringArray.length; i++)
I get a nasty exception. How do I deal with this and why am I getting it in the first place?
Thanks a lot for your help!
Here's the source code of my program:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int index = 0;
String[] randomString = new String[1];
while (index <= randomString.length) {
out.println("Enter your string");
String input = keyboard.next();
randomString[index] = input;
PrintArray(randomString);
index++;
if (index >= randomString.length) {
ExtendArray(randomString);
continue;
}
}
}
public static void ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
stringArray[i] = secondArray[i];
stringArray = secondArray;
}
}
public static void PrintArray(String[] stringArray) {
for (int i = 0; i < stringArray.length; i++) {
out.println(" " + stringArray[i]);
}
}
Java does not work in the methods you are trying to employ. Everything in Java is passed by value, unless it is a data point in an object. What you are trying to employ is a pass by reference, which is not possible in Java.
What you are trying to do is an already existing data structure called a Vector: http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
I would suggest doing this: (not sure if it will work properly, as my current PC doesn't have dev tools):
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
secondArray[i] = stringArray[i];
}
return secondArray;
}
then calling it like so in main:
randomString = ExtendArray(randomString);
Relating to vectors, this is how it works in a Vector class:
public void incrementCount(int count){
int increment = (count * 2);
Object newElementData [] = new Object[increment];
for(int i = 0; i < count; i++)
{
newElementData[i] = elementData[i];
}
elementData = new Object[increment];
elementData = newElementData;
}
In this case, elementData is the original array, newElementData is a temp array that acts to up the bounds.
You cant get error on your PrintArray method, you get the error on the line before!
randomString[index] = input;
Because if you do this
index <= randomString.length
The last iteration is out of bounds, String of length 10 has values on 0-9. You have to change the while cycle to
index < randomString.length
Also your ExtendArray method is NOT functional!
You are supposed to swap out the randomString array for a new array with double length. You create a new array and copy the contents of the old one to the new one, but don't do anything with the new array.
I suppose you want the ExtendArray method to return the new array, and set the randomString variable to be the new array.
You need to return your second array from ExtendArray function:
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i <= stringArray.length; i++) {
stringArray[i] = secondArray[i];
}
return secondArray;
}
and in your main:
randomString = ExtendArray(randomString);
also your while condition should be:
while (index < randomString.length)

Categories