I cannot get the final column in a 2D array to print - java

My task is to take the original 2D array, and calculate the weight of each index and create a new array with the new values. I just can't output the final column of the new array
Thank you!

Your loops should look like this:
for (int i = 0; i < calcWeight.length; i++) {
// note the calcWeight[i], you´ll get the first dimension length
// if you leave out the [i] part
// This way your inner loop would stop at 4 (rather 5 because <=)
// instead of its actuall length, 6
for (int j = 0; j < calcWeight[i].length; j++) {
...
}
}

Related

Checking for Adjacent elements in 2d Arrays and replacing them

So, I am building a method to check a 2d array for a target value and replace each adjacent element with that target value. I have literally tried to brainstorm the solution to this for about an hour and I just want to know if anyone can help me with this, this is the code I have so far
public int[][] replaceValue(int n, int[][]y){
int [][]temp0 = new int[y.length][y[0].length];
int[]top, down ,left, right = new int[y[0].length];
for(int row = 0; row < y.length; row++){
for(int col = 0; col < y[row].length; col++){
temp0[row][col] = y[row][col];// new array so I wouldn't mess with the array passed in
}
}
for(int row = 0; row < temp0.length; row++){
for(int col = 0; col < temp0[row].length; col++){
top[row] = temp0[row-1][col];
down[row] = temp0[row+1][col];
right[row] = temp0[row][col+1];
left[row] = temp0[row] [col-1];
}
}
I got error messages such as I didn't initialize my top and left and right and down variables but I simply don't understand how the logic works for checking the adjacent elements and making sure the whole array is not replaced with the target value. Thanks
The question is a little confusing so I will try to interpret it.
What you are given is a 2-dimensional array with some integer values. Your function should scan the 2-d array, and if you find some target value,
return a 2-d array with the adjacent indices as the target value as well.
For example, if we have a 3x3 array and the target is 2...
1 1 1 1 2 1
1 2 1 ====> 2 2 2
1 1 1 1 2 1
Your problem is that you can't think of a way to change the value without changing the entire array to 2.
Solution One: You scan for the target value in the given array, but you update the values in the temporary array.
Solution Two: You scan the temporary array, and store whether or not it should be changed using a 2-d boolean array.
Solution One is much better in terms of efficiency (both memory and time), so I'll just give you my solution #2, and leave you to do Solution One on your own.
Also, please use more descriptive variable names when it matters :P (why is the input called temp??)
public static int[][] replaceValue(int target, int[][] currArray){
int[][] temp = new int[currArray.length][];
//get a boolean array of same size
//NOTE: it is initialized as false
boolean[][] needsChange = new boolean[currArray.length][currArray[0].length];
//copy the current array into temp
for(int i = 0; i < currArray.length; i++){
temp[i] = currArray[i].clone();
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
//if it is the target value, mark it to be changed
if(temp[i][j] == target){
needsChange[i][j] = true;
}
}
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
if(needsChange[i][j]){ //NOTE: same as "needsChange[i][j] = true;"
//Now, we will check to make sure we don't go out of bounds
//Top
if(i > 0){
temp[i-1][j] = target;
}
//Bottom
if(i + 1 < temp.length){
temp[i+1][j] = target;
}
//Left
if(j > 0){
temp[i][j-1] = target;
}
//Right
if(j + 1 < temp[0].length){
temp[i][j+1] = target;
}
}
}
}
//return the new array we made
return temp;
}
You have not initialized your local variables before first use. So you need to change your 3rd line to some thing like the below code:
int[] top = new int[temp[0].length], down = new int[temp[0].length],
left = new int[temp[0].length], right = new int[temp[0].length];
After that your code is compiled and you can check your logic.

Inputting values to a full 2d array

I'm currently trying to figure out how to add values into a full 2d array. Any help would be appreciated.
This is what i currently have.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray)
{
//Creates a new array with an extra row
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++)
{
for (int ii = 0; ii <= newArray[0].length; ii++)
{
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length)
{
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
}
else
{
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
What I currently have done is input a value to the new row however the method is going to be called multiple times to add more than one value. Which mean it's going to create multiple rows rather than adding to the next available column.
EDIT:
mistyped the data type the array and value are suppoed to be objects.
First, your code throws an IndexOutOfBoundsException. Here is why:
Consider the if (i <= oldArray.length) clause. Say, oldArray.length is 3. When i = 3, newArray[i][ii] = oldArray[i][ii] line seeks the oldArray[3][ii] elements but there are no such elements. All the possible elements of oldArray is oldArray[0][ii], oldArray[1][ii] and oldArray[2][ii], since counting starts with 0 in programming.
Second, I didn't get the point of adding another row for each next value. If you're not going to add a set of values to each row, then, why do you consider expanding number of rows?
This is a typical situation when you need to make a tradeoff between element access complexity and complexity of adding new column
If you need fast column adding without new structure allocation you should use LinkedList as a storage of rows and call list.add(row) every time you need to add a new column so your code will look like:
public static void addValue(int value, LinkedList<int[]> list) {
int[] row_you_need_to_add = new int[list.get(0).length];
for (int i = 0; i < list.get(0).length; i++) {
row_you_need_to_add[i] = value;
}
list.add(row_you_need_to_add);
}
As 2D Array is an Array which consist of an array within an Array. So at every index of 2D array there is another array is present and has a specific size.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray) {
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++) {
for (int ii = 0; ii <= newArray[0].length; ii++) {
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length) {
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
} else {
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}

Filling 2d array

Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));

How To Assign A Value To The First Index In a Multi Dimensional Array In Java

I have a 2d array and I want to know how do you set the first value so if my array was
int array[a][b] = int[10][10];
How would you access index 'a' in a for loop?
This is my simple code that I am working on thanks in advance
int[][] timesTable = new int[12][12];
for(int i = 0; i < timesTable.length; i++){
timesTable[i][i] = i + 1;//can't set the first index with this value
System.out.println(timesTable[i]);
}
I hope you are not putting the "a" and "b" in the array declaration.
int array[][] = int[10][10];
A 2D array is array of arrays. The index "a" or what you are trying to set is another array.
timesTable[i][i] = i + 1;//can't set the first index with this value
The above can be written like this:
timesTable[i] = {1,2,3};// puts another array at index i
You access your array using [], which you'll need to do n times for an n-dimensional array if you're trying to access a particular element.
If you're simply trying to set the first element, then you can do:
array[0][0] = 100; // some number
If you want to iterate over each element in the entire 2d array, you'll need 2 loops, one for each dimension, like so:
for ( int i = 0; i < array.length; ++i ) {
for ( int j = 0; j < array[i].length; ++j ) {
array[i][j] = i + j; // or whatever you want to set the elements to
System.out.println( array[i][j] );
}
}

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

Categories

Resources