Bloomberg LP Interview Question
Financial Software DevelopersI also thought there was a mistake like unnamed_array. But, then I thought it might be a little trickier pattern. Anyway, here is the solution for the original question with possible mistake but you can easily modify it for the corrected question:
{{
/* Input array is: */
/* [2, 3, 5, 6, 12, 4, 2] */
/* The output array is: */
/* [2, 6, 18, 24, 30, 35, 38, 40] */
#include "stdio.h"
void main()
{
int in_ar[7] = {2, 3, 5, 6, 12, 4, 2};
short len = sizeof(in_ar)/sizeof(int);
int* out_ar = malloc(sizeof(int)*(len + 1)); /* [2, 6, 18, 24, 30, 35, 38, 40]; */
out_ar[0] = in_ar[len - 1];
int j = len - 2;
int k = len - j - 1;
while (j >= 0) {
if (j == k) {
out_ar[k] = out_ar[k - 1] + in_ar[j];
}
else {
out_ar[k] = out_ar[k - 1] + in_ar[j];
j--;
}
printf("Cur int is : %d\n", out_ar[k]);
k++;
}
}
}}
<pre lang="" line="1" title="CodeMonkey6708" class="run-this">/* Input array is: */
/* [2, 3, 5, 6, 12, 4, 2] */
/* The output array is: */
/* [2, 6, 18, 24, 30, 35, 38, 40] */
#include "stdio.h"
void main()
{
int in_ar[] = {2, 3, 5, 6, 12, 4, 2};
short len = sizeof(in_ar)/sizeof(int);
int* out_ar = malloc(sizeof(int)*(len + 1)); /* [2, 6, 18, 24, 30, 35, 38, 40]; */
out_ar[0] = in_ar[len - 1];
int j = len - 2;
int k = len - j - 1;
while (j >= 0) {
out_ar[k] = out_ar[k - 1] + in_ar[j];
if (j != k)
j--;
printf("Cur int is : %d\n", out_ar[k]);
k++;
}
}
</pre><pre title="CodeMonkey6708" input="yes">
</pre>
public static int[] output(int[] arr) {
if (arr == null || arr.length == 0) return null;
int[] output = new int[arr.length];
output[0] = arr[arr.length - 1];
for (int i = 1; i < arr.length; i++) {
output[i] = output[i - 1] + arr[arr.length - i - 1];
}
return output;
}
public static void main(String[] args) {
int[] input = {2, 3, 5, 6, 6, 12, 4, 2};
int[] output = output(input);
System.out.println(Arrays.toString(output));
}
import java.util.Arrays;
public class CareerUp_ReverseInt {
public static void main(String[] args) {
int[] input = {2,3,5,6,6,12,4,2};
int[] output = new int[input.length];
int j = 0;
for(int k=input.length-1; k>=0 ; k--){
int temp = 0;
for(int i=input.length-1 ; i>=k ; i--){
temp = temp + input[i];
}
output[j] = temp;
j++;
}
System.out.println(Arrays.toString(output));
}
}
I think you have something missing in the input array. It should have been [2,3,5,6,6,12,4,2]. Then the sum of the elements in reverse are the out put array. Where the out put would be [2,2+4,2+4+12,2+4+12+6,2+4+12+6+6,2+4+12+6+6+5,2+4+12+6+6+5+3,2+4+12+6+6+5+3+2]
- unnamed_array March 27, 2011