Given a list of people with their birth and end years (all between 1900 and 2000), find the year with the most number of people alive.
Here
my answer
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class AlogrimVarsta {
public static void main(String args[]) {
int startYear = 1890;
int stopYear = 2000;
List listPerson = new LinkedList<>();
listPerson.add(new Person(1910, 1940));
listPerson.add(new Person(1920, 1935));
listPerson.add(new Person(1900, 1950));
listPerson.add(new Person(1890, 1920));
listPerson.add(new Person(1890, 2000));
listPerson.add(new Person(1945, 2000));
Map mapPersoaneCareAuTrait = new LinkedHashMap<>();
for (int x = startYear; x <= stopYear; x++) {
mapPersoaneCareAuTrait.put(x, 0);
}
for (int x = startYear; x <= stopYear; x++) {
for (Person per : listPerson) {
int value = mapPersoaneCareAuTrait.get(x);
if (per.getBorn() == x) {
mapPersoaneCareAuTrait.put(x, value + 1);
continue;
}
if (per.getDie() == x) {
mapPersoaneCareAuTrait.put(x, value + 1);
continue;
}
if ((per.getDie() - per.getBorn() > per.getDie() - x) && (per.getDie() - x > 0)) {
mapPersoaneCareAuTrait.put(x, value + 1);
continue;
}
}
}
for (Map.Entry mapEntry : mapPersoaneCareAuTrait.entrySet()) {
System.out.println("an " + mapEntry.getKey() + " numar " + mapEntry.getValue());
}
}
static class Person {
final private int born;
final private int die;
public Person(int pBorn, int pDie) {
die = pDie;
born = pBorn;
}
public int getBorn() {
return born;
}
public int getDie() {
return die;
}
}
}