Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions java-gym-master.iml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="junit.jupiter" level="project" />
</component>
</module>
43 changes: 23 additions & 20 deletions src/ru/yandex/practicum/gym/Coach.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,19 @@

public class Coach {

//фамилия
private String surname;
//имя
private String name;
//отчество
private String middleName;
// фамилия
private final String surname;
// имя
private final String name;
// отчество
private final String middleName;

public Coach(String surname, String name, String middleName) {
this.surname = surname;
this.name = name;
this.middleName = middleName;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coach coach = (Coach) o;
return Objects.equals(surname, coach.surname) && Objects.equals(name, coach.name) && Objects.equals(middleName, coach.middleName);
}

@Override
public int hashCode() {
return Objects.hash(surname, name, middleName);
}

public String getSurname() {
return surname;
}
Expand All @@ -41,4 +28,20 @@ public String getName() {
public String getMiddleName() {
return middleName;
}
}

// Нужно для корректной работы HashMap в getCountByCoaches()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coach coach = (Coach) o;
return Objects.equals(surname, coach.surname)
&& Objects.equals(name, coach.name)
&& Objects.equals(middleName, coach.middleName);
}

@Override
public int hashCode() {
return Objects.hash(surname, name, middleName);
}
}
27 changes: 14 additions & 13 deletions src/ru/yandex/practicum/gym/TimeOfDay.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,25 @@

public class TimeOfDay implements Comparable<TimeOfDay> {

//часы (от 0 до 23)
private int hours;
//минуты (от 0 до 59)
private int minutes;
// часы (от 0 до 23)
private final int hours;
// минуты (от 0 до 59)
private final int minutes;

public TimeOfDay(int hours, int minutes) {

this.hours = hours;
this.minutes = minutes;
}

public int getHours() {
return hours;
}

public int getMinutes() {
return minutes;
}

@Override
public int compareTo(TimeOfDay o) {
if (hours != o.hours) return hours - o.hours;
Expand All @@ -32,12 +41,4 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(hours, minutes);
}

public int getHours() {
return hours;
}

public int getMinutes() {
return minutes;
}
}
}
124 changes: 117 additions & 7 deletions src/ru/yandex/practicum/gym/Timetable.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,127 @@

public class Timetable {

private /* как это хранить??? */ timetable;
// O(1) получить отсортированный список занятий за день
private Map<DayOfWeek, List<TrainingSession>> dayCache;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private Map<DayOfWeek, List<TrainingSession>> dayCache;

Честно говоря, не до конца понял выгоду от добавления и поддержания этой структуры. Лучше было бы сразу же собирать статистику в разрезе тренеров.
На ваше усмотрение.

private HashMap<Coach, Integer> coachesCounter;

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Согласен. Добавлю coachesCounter и упрощю реализацию.


// O(1) получить занятия по дню и времени
private Map<DayOfWeek, Map<TimeOfDay, List<TrainingSession>>> byDayAndTime;

// сразу считаем тренировки тренеров при добавлении
private Map<Coach, Integer> coachesCounter;

public Timetable() {
dayCache = new HashMap<>();
byDayAndTime = new HashMap<>();
coachesCounter = new HashMap<>();

for (DayOfWeek day : DayOfWeek.values()) {
dayCache.put(day, new ArrayList<>());
byDayAndTime.put(day, new HashMap<>());
}
}

public void addNewTrainingSession(TrainingSession trainingSession) {
//сохраняем занятие в расписании
if (trainingSession == null) {
return;
}

DayOfWeek day = trainingSession.getDayOfWeek();
TimeOfDay time = trainingSession.getTimeOfDay();
Coach coach = trainingSession.getCoach();

if (day == null || time == null || coach == null) {
return;
}

// 1) Добавление в список дня
List<TrainingSession> dayList = dayCache.get(day);
dayList.add(trainingSession);

// сортируем по времени начала (разрешено делать при добавлении)
Collections.sort(dayList, new Comparator<TrainingSession>() {
@Override
public int compare(TrainingSession a, TrainingSession b) {
return a.getTimeOfDay().compareTo(b.getTimeOfDay());
}
});

// Добавление в map день->время->список
Map<TimeOfDay, List<TrainingSession>> timeMap = byDayAndTime.get(day);

List<TrainingSession> sessionsAtTime = timeMap.get(time);
if (sessionsAtTime == null) {
sessionsAtTime = new ArrayList<>();
timeMap.put(time, sessionsAtTime);
}
sessionsAtTime.add(trainingSession);

// Сразу обновляем статистику по тренерам
Integer count = coachesCounter.get(coach);
if (count == null) {
coachesCounter.put(coach, 1);
} else {
coachesCounter.put(coach, count + 1);
}
}


public List<TrainingSession> getTrainingSessionsForDay(DayOfWeek dayOfWeek) {
if (dayOfWeek == null) {
return new ArrayList<>();
}
return dayCache.get(dayOfWeek);
}

public /* непонятно, что возвращать */ getTrainingSessionsForDay(DayOfWeek dayOfWeek) {
//как реализовать, тоже непонятно, но сложность должна быть О(1)

public List<TrainingSession> getTrainingSessionsForDayAndTime(DayOfWeek dayOfWeek, TimeOfDay timeOfDay) {
if (dayOfWeek == null || timeOfDay == null) {
return new ArrayList<>();
}

Map<TimeOfDay, List<TrainingSession>> timeMap = byDayAndTime.get(dayOfWeek);
List<TrainingSession> result = timeMap.get(timeOfDay);

if (result == null) {
return new ArrayList<>();
}
return result;
}

public /* непонятно, что возвращать */ getTrainingSessionsForDayAndTime(DayOfWeek dayOfWeek, TimeOfDay timeOfDay) {
//как реализовать, тоже непонятно, но сложность должна быть О(1)
// Теперь без перебора всех тренировок: берём готовую статистику
public List<CounterOfTrainings> getCountByCoaches() {
List<CounterOfTrainings> result = new ArrayList<>();

for (Coach coach : coachesCounter.keySet()) {
result.add(new CounterOfTrainings(coach, coachesCounter.get(coach)));
}

// сортировка по убыванию количества
Collections.sort(result, new Comparator<CounterOfTrainings>() {
@Override
public int compare(CounterOfTrainings a, CounterOfTrainings b) {
return b.getCount() - a.getCount();
}
});

return result;
}

public static class CounterOfTrainings {
private Coach coach;
private int count;

public CounterOfTrainings(Coach coach, int count) {
this.coach = coach;
this.count = count;
}

public Coach getCoach() {
return coach;
}

public int getCount() {
return count;
}
}
}
}
Loading