Passing a 2d array and using recursion error - arrays

I am doing an assignment and have trouble getting the code compiled. The code must have recursion. The idea is to pass a 2d array sequentially - row by row, column by column and to get a private helper method to match cases and return the result.
I have tried looking at different solutions and everything seems in order, however I get an error:
required: int
found: int[][]
I am passing an array, int row and int column to a method that should be accepting exactly those three.
Take a look:
public static int [][] calculateProximity ( boolean [][] mineField )
{
int [][] proximityField = new int [mineField.length][mineField[0].length];
for (int row = 0; row < mineField.length; row++) {
for (int column=0; column <mineField[row].length; column++) {
proximityField [row][column] = calculateProximity (mineField, row, column);
}
}
return proximityField;
}
private static int [][] calculateProximity (boolean [][] mineField,
int row, int column)
{
int [][] proximityField;
if (row >= mineField.length || column >= mineField[row].length){
return proximityField=0;
}
else if (mineField [row][column]= true){
proximityField[row][column]=1;
return proximityField;
}
else
{
proximityField[row][column]=0;
}
return proximityField;
}
By the way, calculateProximity main method is to return an int 2d array, but it is given a boolean 2d array.

return proximityField=0;, is incorrect. Here, you are returning the result of proximityfield=0. This is going to be a single integer, the value 0. When you assign a variable, the return value is the value you assigned to the variable. You should probably return null instead.

Never use loops while performing recursion. I hope this code gives you some idea:
#include<stdio.h>
#include<stdlib.h>
int i=0,j=0,k=0,flag=0;
int function_Matrix(int arr[][4],int i,int j)
{
if(j==4||i==3)
return 1;
if(flag==0)
{
printf("\t%d",arr[i][j]);
}
function_Matrix(arr,i,j+=1);
printf("\n");
function_Matrix(arr,i+=1,j=0);
flag=1;
}
int main()
{
int x;
int arr[][4]={{1,2,3,4},
{5,6,7,8},
{9,7,6,5}};
function_Matrix(arr,0,0);
}

Related

C - Passing a local variable in a function without initializing

so I'm really new at this, and I was wondering how I would go about passing a local variable in a function (in terms of the initialization). For example, I have one function (move) that declares and initializes two variables (t_row and t_column) to be used in a for loop, and within that loop, I have another functions (swap), that is called if certain conditions are met. How do I go about using those variables in the swap function. I know I need to declare them, but their initialization in the swap function depends on what iteration of the for loop swap was called. Thanks in advance for any help!
bool move(int tile)
{
for (int t_row = 0; t_row < d; t_row++)
{
for (int t_column = 0; t_column < d; t_column++)
{
if (tile == board[t_row][t_column])
{
if (0 < t_row && board[t_row - 1][t_column] == 0)
{
swap(t_row - 1, t_column);
return true;
}
}
}
}
return false;
}
void swap(int row_new, int column_new)
{
int t_row;
int t_column;
int hold = board[t_row][t_column];
board[t_row][t_column] = 0;
board[row_new][column_new] = hold;
}
The easiest way I can see to do this would be to pass in the values of the old row and column.
void swap(int row_new, int col_new, int row_old, int col_old) {
int hold = board[row_old][col_old];
board[row_old][column_old] = 0;
board[row_new][column_new] = hold;
}

Sum Specified Column Jagged Array

My homework assignment is asking to output the sum of a specified column of a Jagged 2D Array. I've seen other solutions that show how to get the sum of ALL columns, but not a specific one. The issue I'm running into is that I get a java.lang.ArrayIndexOutOfBoundsException if a column is entered and no element exists in a row of the 2D array.
// returns sum of specified column 'col' of 2D jagged array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
for (int j = 0; j < array[col].length; j++) {
sum += array[j][col];
}
return sum;
} // end columnSum()
Example: Ragged Array Input (class is named RaggedArray)
int[][] ragArray = { {1,2,3},
{4,5},
{6,7,8,9} };
System.out.println(RaggedArray.columnSum(ragArray, 2));
This obviously gives me an ArrayIndexOutOfBoundsException, but I don't know how to fix it if a specified column is asked for as an argument. Any ideas? I appreciate any help or suggestions!
In your loop, do a
try{
sum += array[j][col];
}catch(ArrayIndexOutOfBoundsException e){
}
block, where it simply skips over if there is nothing, and keeps going to the next one.
you will have to import that exception as well. If you run into trouble, just look up how try/catch blocks work
Here is another solution I found.
// returns sum of the column 'col' of array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
try {
for (int j = 0; j < array.length; j++) {
if (col < array[j].length)
sum += array[j][col];
}
}
catch (ArrayIndexOutOfBoundsException e){
}
return sum;
} // end columnSum()
public class JaggedArrayColSum {
int[] jackedArrayColSum(int arr[][]){
int sum;
int maxLen=0;
boolean status;
//START #MAX LENGTH
//Finding the max length of inner array
for(var a=0;a<arr.length;a++) {
status=true;
for(var b=0;b<arr.length;b++) {
if(a==b)continue;
if(arr[a].length<arr[b].length) {
status=false;
break;
}
if(status)maxLen=arr[a].length;
}
}
//END #MAX LENGTH
//START #SUM JAGGED ARRAY
int [ ] arr1=new int[maxLen];
for(var a=0;a<maxLen;a++) {
sum=0;
for(var b=0;b<arr.length;b++) {
if(arr[b].length>a)sum+=arr[b][a];
}
arr1[a]=sum; //Adding values to the the return array index
}
//END #SUM JAGGED ARRAY
return arr1;
}
public static void main ( String [ ] args ) {
int [][]arr= {{1},{1,3},{1,2,3,4},{1,2,3,4,5,6,7}};
for(int x:new JaggedArrayColSum().jackedArrayColSum ( arr ))System.out.print ( x +" " ) ;
}
}

Returning Arrays from Methods

So I have to display the marks that are below average, and all the marks that are above average.
I don't know where to go with this next but here's what I have so far:
public static void main (String[]args) {
int[]marks={50,60,30,90,70,40,80,44};
int average=average(marks);
int[]resultBelowAverage=getBelowAverage(marks,average);
printIntArray(resultBelowAverage);
int[]resultAverageandAbove=getAverageandAbove(marks,average);
printIntArray(resultAverageandAbove);
}
This next method is used to calculate the average. I got the right answer for this one which is 58.
public static int average(int[] marks) {
int i=0;
int total=0;
for(i=0;i<marks.length;i++){
total=total+marks[i];
}
int average=total/i;
return average;
}
This next method gets how many values in the array are below average.
public static int countBelowAverage (int[] numbers,int av){
int size=0;
for(int i=0;i<numbers.length;i++) {
if (numbers[i]<av) {
size=size+1;
}
}
return size;
}
This next method gets how many values in the array are above average.
public static int countAboveAverage (int[] numbers,int av) {
int size=0;
for(int i=0;i>=numbers.length;i++) {
if (numbers[i]>=av) {
size=size+1;
}
}
return size;
}
This next method gets which values in the array are below average. I think this is where I went wrong.
public static int[] getBelowAverage(int[]numbers,int av) {
int size=countBelowAverage(numbers,av);
int[]belowAverage=new int[size];
return belowAverage;
}
This next method gets which values in the array are above average.
public static int[] getAverageandAbove(int[] numbers,int av) {
int size=countAboveAverage(numbers,av);
int[]AboveAverage=new int[size];
return AboveAverage;
}
This last method prints the arrays that are classified into below average and above average.
public static void printIntArray(int[]x) {
for(int i=0;i<x.length;i++){
System.out.println (x[i]);
}
}
In your method getAverageandAbove you make an array, but you do not put anything in it.
you should loop through your numbers array again, and fill your AboveAverage array with the values that are greater than the average.
Try something like this to get the below average array
public static int[] getBelowAverage(int[]numbers,int av){
int size=countBelowAverage(numbers,av);
int[]belowAverage=new int[size];
int j = 0;
for (int i = 0; i < numbers.length; i++){
if (numbers[i] < av){
belowAverage[j] = numbers[i];
j++;
}
}
return belowAverage;
}
Do similar for the above average method
In your methods you just creating arrays of proper size, an empty arrays and returning them. You should put some marks that are below / above average to these arrays before returning
Like here:
int[]belowAverage=new int[size];
//you have an empty array just after creation with nothing inside
//enter here marks from the marks array that are below average
return belowAverage;
Exactly the same situation here:
int[]AboveAverage=new int[size];
//you have an empty array just after creation with nothing inside
//enter here marks from the marks array that are above average
return AboveAverage;
You may use an algorithm from peeskillet's solution to do it.

Write the definition of a function, isReverse

Write the definition of a function, isReverse , whose first two parameters are arrays of integers of equal size, and whose third parameter is an integer indicating the size of each array. The function returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.)
int isReverse(int array1[], int array2[], int size)
{
int i;
for (i=0;i<size;i++)
{
if(array1[i] == array2[size-1])
return 0;
else
return 1;
}
}
i keep getting an error. whats wrong with it.
When you return from within any block in the function the function execution ends there, so in your case you are returning from function even when the first elements of the arrays are matching which is not correct, you should check whole array and then return from the function in the end, check the code below:
int isReverse(int array1[], int array2[], int size)
{
int i,status=1;
for (i=0;i<size;i++) //Size is the length of the array? if yes than you need -1 from it.
{
if(array1[i] == array2[size])
{
status=0;
--size;
}
else
return 1;
}
return status;
}
Moreover, size-1 does not change the value of the variable size itself hence size will remain same throughout the loop, use --size this will decrement the value of actual variable hence decrementing it by one every time.
The variable "size" never changes, so you're always checking elements of array1 against the last element of array2.
Since this sounds like a homework problem, I'll let you see if you can go from there.
This is how I did it.
int isReverse(int array1[], int array2[], int SIZE)
{
for( int counter = 0; counter <= SIZE/2; counter++ )
if(array1[counter] != array2[SIZE-counter] || array2[counter] != array1[SIZE-counter])
return 1;
return 0;
}
You are just comparing the value at index i with a constant SIZE-1. Instead you want to compare the value at i with the comparison array's size-i. So each time the counter increments it compares with the opposite array's size-i. And you only have to do this for half of the array.
The return value is wrong because you are checking only 1 value from each array, not all of them. What you want to do is something like this.
for (i=0;i<size;i++)
{
if(!(array1[i] == array2[size-i-1]))
return 0;
}
return 1;
Basically you go through the array one by one, if any of the values are not the same as the appropriate value on the other array, it is not a reverse, so we return 0. If we get out of the for loop without going through the if, it means they are reverses so we return 1.
int isReverse(int array1[], int array2[], int size)
{
int flag = 0;
for (int i=0;i<size;i++)
{
if(array1[i] != array2[size-1]){
flag = 1;
break;
}
return flag;
}
}
In the code you have kept the return statement inside the loop... keep the return statement outside the loop and try
int isReverse(int a[], int b[], int n)
{
int i = 0;
while (i<n)
{
if (a[i] != b[n-i-1]) {return 0; break;}
else i++;
}
return 1;
}
anw this was the correct answer.
bool isReverse(int array1[], int array2[],int size)
{
int i=0;
for (int k=0;k<size;k++){
if (array1[k]==array2[size-k-1]){
i++;
}
}
if (i==size){
return true;
}else{
return false;
}
}

Transposing a matrix

I want to transpose a matrix, its a very easy task but its not working with me :
UPDATE
I am transposing the first matrix and
storing it in a second one
The two
arrays point to the same structure
I
need two arrays (target and source)
so I can display them later for
comparison.
struct testing{
int colmat1;
int rowmat1;
float mat[64][64];
};
int testtranspose(testing *test,testing *test2){
int i,j;
test2->colmat1 = test->rowmat1;
test2->rowmat1 = test->colmat1
for(i=0;i<test->rowmat1;i++){
for(j=0;j<test->colmat1;j++){
test2->mat[i][j] = test->mat[i][j];
}
printf("\n");
}
}
I thought this is the correct method of doing it, but apparently for a matrix such as :
1 2
3 4
5 6
7 8
I get :
1 2 0 0
3 4 0 0
What is the problem ?
Please help,
Thanks !
To transpose the matrix, you need to change rows and columns. So you need to use:
targetMatrix[i][j] = sourceMatrix[j][i];
Note how the order of i,j is changed, since one matrix's rows are another's columns.
By the way, instead of (*a).b, you can write a->b. This is the normal way of accessing a field of a struct pointer.
Try this...
struct testing{
int colmat;
int rowmat;
float mat[64][64];
};
int testtranspose(testing *test,testing *test2){
int i,j;
test2->colmat = test->rowmat;
test2->rowmat = test->colmat;
for(i=0;i<test->rowmat;i++){
for(j=0;j<test->colmat;j++){
test2->mat[j][i] = test->mat[i][j];
}
}
return 0;
}
int printmat(testing* mat)
{
for(int i=0;i<mat->rowmat;i++)
{
printf("\n");
for(int j=0;j<mat->colmat;j++)
printf((" %f"),mat->mat[i][j]);
}
return 0;
}
// 2
// main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
testing mat1, mat2;
memset(&mat1,0,sizeof(testing));
memset(&mat2,0,sizeof(testing));
mat1.colmat =2;
mat1.rowmat =3;
for(int i=0;i<mat1.rowmat;i++)
{
for(int j=0;j<mat1.colmat;j++)
mat1.mat[i][j] = (float)rand();
}
printmat(&mat1);
testtranspose(&mat1,&mat2);
printmat(&mat2);
getchar();
}
I am new to C / C++ (3rd day or so :) ) and I had the same problem. My approach was slightly different in that I thought it would be nice to have a function that would return a transposed matrix. Unfortunately, as I found out, you cannot return a an array nor pass an array to a function in C++ (let alone a double array), but you can pass / return a pointer which works similar to an array. So this is what I did:
int * matrix_transpose(int * A, int A_rows, int A_cols){
int * B;
int B_rows, B_cols;
B_rows = A_cols; B_cols= A_rows;
B = new int [B_rows*B_cols];
for(int i=0;i<B_rows;i++){
for(int j=0;j<B_cols;j++){
B[i*B_cols+j]=A[j*A_cols+i];
}
}
return B;
};
The trick was in dynamic arrays. I used A_rows and B_rows as separate names (you can use only rows and cols) in order to make the problem less intricate and less confusing when reading code.
B = new int [rows*cols] // This is cool in C++.

Resources