Feeder
is #1 from the from the 2024 AP Computer Science A Free Response problems.
https://apcentral.collegeboard.org/media/pdf/ap24-frq-comp-sci-a.pdf
Part (a) simulateOneDay
method
public void simulateOneDay(int numBirds)
{
if(Math.random() < 0.95)
{
int foodPerBird = (int) (Math.random() * 41) + 10;
currentFood -= numBirds * foodPerBird;
if(currentFood < 0)
currentFood = 0;
}
else
{
currentFood = 0;
}
}
For more on working with Math.random()
see Generating numbers with Math.random().
Part (b) simulateManyDays
method
public int simulateManyDays(int numBirds, int numDays)
{
int daysLeft = numDays, foundFood = 0;
while(daysLeft > 0 && currentFood > 0)
{
daysLeft--;
foundFood++;
simulateOneDay(numBirds);
}
return foundFood;
}
2024 AP CS Exam Free Response Solutions
- Scoreboard Free Response Solution
- WordChecker Free Response Solution
- GridPath Free Response Solution
Help & comments
Get help from AP CS Tutor Brandon Horn
See an error? Question? Please comment below.
2024-05-13 comment
(Email withheld)
If I made the random number 0 - 100 do you think I would get points off? I adjusted the if statement accordingly to: if (randomNum < 95)
Response
Although it is not necessary to convert the number returned by Math.random
into an int
, a solution that did so correctly would not be penalized.