Difficult# Count Fish Using ArrayList of Boolean, Integer Pairs

APCSA-WIKZEE

A lake is divided into sections and each section is sampled to count the number of fish and determine whether it is polluted. This information is recorded into an array list that contains pairs of values of whether it is polluted and the count of fish in that section (i.e. [true, 20, false, 35, false, 22....]).

Which of the following methods will return the number of fish in the lake for a specific pollution condition (polluted or not polluted)?

**I.**

```
// Pre-condition: each pair of values in lakeGrid will be a boolean, int.
// isPolluted determines which fish to count
public static int countFish2(ArrayList lakeGrid, boolean isPolluted)
{
int totFish = 0;
for (int i=0; i<lakeGrid.size(); i+=2)
{
if (lakeGrid.get(i)==isPolluted
totFish += lakeGrid.get(i+1);
}
return totFish;
}
```

**II.**

```
// Pre-condition: each pair of values in lakeGrid will be a boolean, int.
// isPolluted determines which fish to count
public static int countFish(ArrayList lakeGrid, boolean isPolluted)
{
boolean polluted
int totFish = 0;
for (int i=0; i<lakeGrid.size(); i+=2)
{
if(lakeGrid.get(i) instanceof Boolean)
{
polluted = (Boolean) lakeGrid.get(i);
if (polluted == isPolluted)
if (lakeGrid.get(i+1) instanceOf Integer)
totFish += (Integer) lakeGrid.get(i+1);
else
{
break;
}
}
else
{
break;
}
}
return totFish;
}
```

**III.**

```
// Pre-condition: each pair of values in lakeGrid will be a boolean, int.
// isPolluted determines which fish to count
public static int countFish2(ArrayList lakeGrid, boolean isPolluted)
{
boolean polluted=false;
int totFish = 0;
for (int i=0; i<lakeGrid.size(); i++)
{
if(lakeGrid.get(i) instanceof Boolean)
{
polluted = (Boolean) lakeGrid.get(i);
}
else
{
if (polluted==isPolluted)
if (lakeGrid.get(i) instanceof Integer)
totFish += (Integer) lakeGrid.get(i);
}
}
return totFish;
}
```