POO-ITBA / 2024_01

Consultas 1C 2024
0 stars 0 forks source link

Parcial 2021 2C - Ejercicio 2 #25

Closed lmoliveto closed 4 months ago

lmoliveto commented 4 months ago

Buenas tardes, está bien esta forma de resolverlo?


public class Person {
    private final String name;
  private final int age;

  public Person(String name, int age) {
      this.name = name;
    this.age = age;
  }

  public String getName(){
      return name;
  }

  public int getAge(){
      return age;
  }

  public String toString(){
      return "Person Name=%s, Age=%d".formatted(getName(), getAge());
  }
}

public class Directory{
    private int count;
    private Person[] people;

    public Directory(int limit){
        people = new Person[limit];
    }

    public Directory addPerson(Person person){
        if(count == people.length){
            throw new ReachedLimitException(count);
        }
        people[count++] = person;
        return this;
    }

    public Person[] persons(){
        return applyCmp(new Comparator<Person>(){
            @Override
            public int compare(Person p1, Person p2){
                int toReturn = p1.getName().compareTo(p2.getName());
                if(toReturn == 0){
                    toReturn = Integer.compare(p2.getAge(), p1.getAge());
                }
                return toReturn;
            }
        });
    }

    protected Person[] applyCmp(Comparator<Person> cmp){
        Person[] toReturn = Arrays.copyOf(people, count);
        Arrays.sort(toReturn, cmp);
        return toReturn;
    }
}

public class DescendingNameDirectory extends Directory{
    public DescendingNameDirectory(int limit){
        super(limit);
    }

    @Override
    public Person[] persons(){
        return applyCmp(new Comparator<Person>(){
            @Override
            public int compare(Person p1, Person p2){
                int toReturn = p2.getName().compareTo(p1.getName());
                if(toReturn == 0){
                    toReturn = Integer.compare(p1.getAge(), p2.getAge());
                }
                return toReturn;
            }
        });
    }
}

public class AscendingAgeDirectory extends Directory{
    public AscendingAgeDirectory(int limit){
        super(limit);
    }

    @Override
    public Person[] persons(){
        return applyCmp(new Comparator<Person>(){
            @Override
            public int compare(Person p1, Person p2){
                int toReturn = Integer.compare(p1.getAge(), p2.getAge());
                if(toReturn == 0){
                    toReturn = p1.getName().compareTo(p2.getName());
                }
                return toReturn;
            }
        });
    }
}

public class ReachedLimitException extends RuntimeException{
    public ReachedLimitException(int limit){
        super("Reached limit of %d people".formatted(limit));
    }
}
fmeola commented 4 months ago

Hola @lmoliveto La implementación es correcta.