Skip to content

Instantly share code, notes, and snippets.

@Daomephsta
Created January 26, 2018 22:35
Show Gist options
  • Save Daomephsta/ff8a8b7ba9f1c3f05045b1c0f998c5af to your computer and use it in GitHub Desktop.
Save Daomephsta/ff8a8b7ba9f1c3f05045b1c0f998c5af to your computer and use it in GitHub Desktop.
import java.util.Arrays;
public class RabbitProblem
{
private static final int DEATH_AGE = 96;
private static final int FERTILE_AGE = 4;
private static final int MALES_PER_LITTER = 5;
private static final int FEMALES_PER_LITTER = 9;
private static long[] maleAgeTracker = new long[DEATH_AGE];
private static long[] femaleAgeTracker = new long[DEATH_AGE];
private static long population;
private static long targetPopulation;
private static int months;
public static void main(String[] args)
{
if (args.length < 3) throw new IllegalArgumentException("Missing arguments");
if (args.length > 3) throw new IllegalArgumentException("Too many arguments");
int initialMales = Integer.parseInt(args[0]);
int initialFemales = Integer.parseInt(args[1]);
targetPopulation = Long.parseLong(args[2]);
population = initialMales + initialFemales;
//Initial rabbits are 2 months old
maleAgeTracker[2] = initialMales;
femaleAgeTracker[2] = initialFemales;
while (population < targetPopulation)
{
doMonthlyTick();
System.out.printf("Month %d, Population %d\n", months, population);
System.out.printf("Males: %s\n", Arrays.stream(maleAgeTracker).sum());
System.out.printf("Females: %s\n", Arrays.stream(femaleAgeTracker).sum());
System.out.println();
}
System.out.printf("%d months for %d to %d, Target: %d", months, initialMales + initialFemales, population, targetPopulation);
}
private static void doMonthlyTick()
{
months++;
long newbornF = 0;
long newbornM = 0;
for(int f = FERTILE_AGE; f < DEATH_AGE; f++)
{
newbornM += MALES_PER_LITTER * femaleAgeTracker[f];
newbornF += FEMALES_PER_LITTER * femaleAgeTracker[f];
}
age();
//Add newborns now so they are not aged with the rest
maleAgeTracker[0] += newbornM;
femaleAgeTracker[0] += newbornF;
countPopulation();
}
private static void age()
{
long[] newMaleAgeTracker = new long[DEATH_AGE];
long[] newFemaleAgeTracker = new long[DEATH_AGE];
for(int i = 0; i < DEATH_AGE; i++)
{
//Kill old rabbits
if(i == DEATH_AGE - 1) continue;
newMaleAgeTracker[i + 1] = maleAgeTracker[i];
newFemaleAgeTracker[i + 1] = femaleAgeTracker[i];
}
maleAgeTracker = newMaleAgeTracker;
femaleAgeTracker = newFemaleAgeTracker;
}
private static void countPopulation()
{
population = Arrays.stream(maleAgeTracker).sum() + Arrays.stream(femaleAgeTracker).sum();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment