I have written a recursive function that I believe will return the 'maximum' row of the 4x4 matrix it is fed. By 'maximum' I mean that the maximum row of the matrix.
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
is row 4 (on account of the first column's values); the maximum row of the matrix
1 2 3 4
2 3 4 1
4 4 1 2
4 1 2 3
is row 3 (on account of the first and second columns' values); the maximum row of the matrix
1 2 3 4
2 3 4 1
4 4 1 2
4 4 2 3
is row 4 (on account of the first, second, and third columns' values); the maximum row of the matrix
1 2 3 4
2 3 4 1
4 4 1 2
4 4 1 3
is row 4 (on account of the values in every column); and the maximum row of the matrix
1 2 3 4
2 3 4 1
4 4 1 3
4 4 1 3
is row 3 (on account of the values in every column - pick the topmost row).
This function is a lot more involved than I expected when I sat down to write it. Please tell me there's an easier way to express this algorithm in C!
(The function is employed in a program written by a Pascalite; please forgive the fact that the arrays ignore their 0th member!)
Here's the function (together with its helper indexOf()
, which is never fed an array in which val fails to appear!) Apologies for variable indentation - bit of a nightmare just getting it to this state!
int indexOf(int a[], int val)
{ /* returns index at which val occurs in a[] */
int i=1;
while(a[i] != val)
i++;
return i;
}
int maxRow (int a[5][5], int index)
{
int store [5] = {-1, a[1][index], a[2][index], a[3][index], a[4][index] };
int store2[5] = {-1, a[1][index], a[2][index], a[3][index], a[4][index] };
int i, j, k, max, i1=0, i2=0, i3=0, i4=0;
int arr[5]={-1,-1,store2[2],store2[3],store2[4]};
if (index==5)
{
if(a[1][4]>=0)
return 1;
else if(a[2][4]>=0)
return 2;
else if(a[3][4]>=0)
return 3;
else if(a[4][4]>=0)
return 4;
}
/* order store[] from max -> min: */
for(i=1; i<=3; i++)
{
max=store[i];
j=i;
for(k=i+1; k<=4; k++)
if(store[k]>max)
{
max=store[k];
j=k;
}
store[j]=store[i];
store[i]=max;
}
i1 = indexOf(store2, store[1]);
/* now we must indicate which (if any ) rows to recurse on... */
if (store[1]==store[2])
{
if(i1==1)
i2 = indexOf(arr,store[1]);
else if (i1==2)
{
arr[2] = -1;
i2 = indexOf(arr, store[1]);
}
else if (i1==3)
i2 = 4;
/* note: if i2==4 then can't have store[1] equal to any other members of store[] */
if(store[1]==store[3])
{
/* i2 = 2 or 3 */
if(store2[4] <= store2[3])
i3 = 3;
else i3=4;
if (store[1]==store[4])
{
i4=4;
}
}
}
if (i2==0)
return i1;
else if(i3==0)
{
i = indexOf(store2,store[4]);
for(j=0;j<5;j++)
a[i][j]=-1;
i = indexOf(store2,store[3]);
for(j=0;j<5;j++)
a[i][j]=-1;
return maxRow(a, index+1);
}
else if (i4==0)
{
i = indexOf(store2,store[4]);
for(j=0;j<5;j++)
a[i][j]=-1;
return maxRow(a, index+1);
}
else /* all i are non-zero */
return maxRow(a, index+1);
}