The most important thing to understand in this problem is which class you are operating in. Because the methods are
the same for every instance of Foo
make sure you are editing the correct values inside the methods.
public class Foo {
private int[] vals;
public Foo(int[] vals) {
this.vals = vals;
}
public int[] getVals() {
return vals;
}
public int getIndex(int i) {
return vals[i];
}
public void addOtherVals(int[] other_vals) {
for (int i=0; i<vals.length; i++) {
vals[i] += other_vals[i];
}
}
public void swapBiggerVals(int[] other_vals) {
for (int i=0; i<vals.length; i++) {
if (vals[i] > other_vals[i]) {
int tmp = other_vals[i];
other_vals[i] = vals[i];
vals[i] = tmp;
}
}
}
}
Foo f1 = new Foo(new int[] {1, 4, 5});
Foo f2 = new Foo(new int[] {2, 3, 6});
f1.swapBiggerVals(f2.getVals());
f2.addOtherVals(f1.getVals());
f2.swapBiggerVals(f1.getVals());
int r1 = f1.getIndex(0);
int r2 = f1.getIndex(1);
int r3 = f1.getIndex(2);
int r4 = f2.getIndex(1);
int r5 = f2.getIndex(2);
We are trying to find the values of r1
- r5
:
Lets start by just keeping track of the two arrays and see what happens. At the start:
f1 [1, 4, 5]
f2 [2, 3, 6]
Our first call is to f1.swapBiggerVals(f2.getVals());
What does this method do?
The only time this ends up happening is when the index is one. So in this case we swap the values at position
one.
after the swapping
f1 [1, 3, 5]
f2 [2, 4, 6]
The next call is f2.addOtherVals(f1.getVals());
This method does the following
because this is happening on the f2
class we have the following values
f1 [1, 3, 5]
f2 [3, 7, 11]
Now f2.swapBiggerVals(f1.getVals());
Because everything in the f2
array is bigger, everything gets swapped.
f1 [3, 7, 11]
f2 [1, 3, 5]
If you have gotten this far and haven’t confused f1
and f2
it should be easy to pair up the
r1
- r5
int r1 = f1.getIndex(0); // r1 = f1[0] and so on. Keep track of which array
int r2 = f1.getIndex(1); // that you need to access
int r3 = f1.getIndex(2);
int r4 = f2.getIndex(1);
int r5 = f2.getIndex(2);
Final
r1: 3
r2: 7
r3: 11
r4: 3
r5: 5