to problem set

Problem 6 - Code comprehension

What is the value of result after the code executes:

int[] a = new int[] {1, 1, 2, 3, 5};
int[] b = new int[] {a.length, a[0]+a[1], a[1]+a[2], 10};
int[] c = a;
int[] d = b;
c[0] = d[2];
a[1] = b[3];
a = b;
d = c;
b = d;
b[3] = a[b[0]];
int result = a[0] + b[1] + c[2] + d[3];

To start this problem lets first write out the arrays and the values they contain.

a is easy because the values are declared for us.

a [1, 1, 2, 3, 5]

b has the following values
[length of a = 5, 1 + 1, 1 + 2, 10]

b [5, 2, 3, 10]

c is just a variable that is pointing to the same thing as a.
d is just a variable pointing to b

So in the end we have this

a, c [1, 1, 2, 3, 5]
b, d [5, 2, 3, 10]

Now if we use a reference to c at this point, we are just going to rewrite it as a, and d will be re-written as b.

c[0] = d[2]; will be the same as a[0] = b[2];
so now index 0 will be the value of b at index 2.

a [3, 1, 2, 3, 5]

a[1] = b[3]; will just swap the value of a at 1 for the value of b at 3.

a [3, 10, 2, 3, 5]

Now we have to deal with the swapping.

a = b; 
d = c;
b = d;

a = b means that a will now point to the same thing as b. At this point, everything but c is pointing to the array that was b.
This is the result:

b, c, d [5, 2, 3, 10]

d = c points the d array back to the array that was originally a.

b, a [5, 2, 3, 10]
d, c [3, 10, 2, 3, 5]

finally b = d assigns b back to the other array.

a [5, 2, 3, 10]
b, d, c [3, 10, 2, 3, 5]

b[3] = a[b[0]];

b[0] is 3
a[3] is 10
so we switch b[3] to 10 which leaves us with.

a [5, 2, 3, 10]
b, d, c [3, 10, 2, 10, 5]

finally
int result = a[0] + b[1] + c[2] + d[3];
result = 5 + 10 + 2 + 10 = 27