Accenture Interview Question
Front-end Software EngineersCountry: Australia
Interview Type: In-Person
Huh? Are you sure that's all? It's easy (assume 0 indexed):
{{
for(i=0; i<n/2; i++)
sum+= A[i][i] + A[i][n-i] + A[n-i][i] + A[n][n];
return ( sum + A[(n+1)/2][(n+1)/2] );
}}
For meaning of this code, sit down and work it through (it's only 2 lines really)
for(i=0; i<n/2; i++) {
sum+= A[i][i] + A[i][n-i] + A[n-i][i] + A[n][n];
}
return ( sum + A[(n+1)/2][(n+1)/2] );
Corrected formatting.
JavaScript
(function(){
var a = [
[3, 5, 9, 2, 6],
[7, 9, 2, 1, 2],
[4, 7, 2, 0, 9],
[6, 8, 3, 5, 6],
[1, 1, 2, 3, 4]
];
alert(getSum(a));
})();
function getSum(a){
// the diagonal elements of the array are:
//
// [x x]
// [ x x ]
// [ + ]
// [ x x ]
// [x x]
//
// with the intersecting element marked with +
// so, you need to add the elements at these locations:
//
// \ diagonal: [0,0] [1,1] [2,2] [3,3] [4,4]
// / diagonal: [0,4] [1,3] [2,2] [3,1] [4,0]
//
// but only add the [2,2] element once
//
// this can be accomplished with a single loop through the array, i.e.
//
// [0,0] + [0,4] + [1,1] + [1,3] + [2,2] + [3,3] + [3,1] + [4,4] + [4,0]
var i, j, n = a.length, sum = 0;
for(i=0;i<n;i++) {
j = n - i - 1;
sum += a[i][i] + ( i == j ? 0 : a[i][j] );
}
return sum;
}
sum = 0
- selva September 13, 2013{
For ( i = 0 ; i < rowsize ;i++ )
{
if ( i == (rowsize -1 - i ))
{
sum = sum + a[i][i]
}
else{
sum = sum + a[i][i] + a[rowsize -1 - i][rowsize -1 - i]
}
}
}