Separating an array into three - java

I currently have a 2d array, could anyone explain how i would extract the following:
the 0th to the 4th row the whole way down the array
then the 5th-10th row the whole way down the array
then the 11th-16th row the whole way down the array
I then want to hold these in 3 seperate arrays.
and then once I have carried out calculations on each individual array how do i sum them all back to one array?
This is the calculations I will carry out on the full array, that I would like to carry out on each individual array.
double[][] newjagssw = jaggedarr;
for(int i=0; i<jaggedarr.length; i++){
for(int j = 0; j<jaggedarr[i].length; j++){
newjagssw[i][j] = jaggedarr[i][j] - average[i];
double hold = newjagssw[i][j];
newjagssw[i][j] = Math.pow(hold, 2);
}
}
sst = new double[record];
for(int i = 0; i < sst.length; i++){
double hold = 0;
for(int j= 0; j < newjagssw[i].length; j++){
hold = hold + newjagssw[i][j];
}
sst[i] = hold;
System.out.println(probename[i] + ": " + ssw[i]);
}return ssw;
is there anyway of adapting it?
Thanks.

Related

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

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?)

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.

Element Modification in Multi-Dimensional Arrays in Java

I have created a 2-D array in Java and I wish to change the value of each element.
Here is what I am trying to accomplish
-number each student from 1-10
-give each student 5 random marks from 40-100
int[][] students = new int[10][5];
Random numGen = new Random();
for (int i=0; i < students.length; i++){
students[i] = i; //Problem here..
for (int j=0; j<5; j++){
students[i][j] = numGen.nextInt(40)+61
}
}
I am having issues assigning each student a number from 1-10.
Where I wrote '//Problem here', is where the compiler keeps giving me trouble.
What is the appropriate method for modifying a single element in multi-dimension arrays?
Just use the index into the students (and return id as index+1 when you need to).
int[][] students = new int[10][5];
Random numGen = new Random();
for (int i=0; i < students.length; i++){
for (int j=0; j<5; j++){
students[i][j] = numGen.nextInt(40)+61
}
}
Array indices in java starts from 0. Which means 1st row is represented as 0. To edit an element in a 2D array you need to specify the both indices.
For example to edit an element at 5th row and 4th column you should use myArray[4][3]. Because you start counting from 0. myArray[0][0] is first element of the first row.
int[][] students = new int[10][5];
Random numGen = new Random();
for (int i=0; i < students.length; i++){
students[i][0] = i; //Change student[i] = i to student[i] = i+i
// because i starts from 0 but student number starts from 1.
for (int j=0; j<5; j++){
students[i][j] = numGen.nextInt(40)+61
}
}

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

Categories