Skip to content

Instantly share code, notes, and snippets.

@zjor
Created November 25, 2022 00:11
Show Gist options
  • Save zjor/484a4ecbd2b06dda5960c4a958fb5ad9 to your computer and use it in GitHub Desktop.
Save zjor/484a4ecbd2b06dda5960c4a958fb5ad9 to your computer and use it in GitHub Desktop.
Assigns members to weeks till the specified year
package org.sandbox;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class RosterBuilder {
private final List<String> members;
private final int lastYear;
public RosterBuilder(List<String> members, int lastYear) {
this.members = members;
this.lastYear = lastYear;
}
/**
* Get all Mondays starting from today till the {@link #lastYear}
*/
private List<LocalDate> listMondaysFromToday() {
LocalDate date = LocalDateTime.now().toLocalDate().with(ChronoField.DAY_OF_WEEK, 1);
var result = new LinkedList<LocalDate>();
while (true) {
result.add(date);
date = date.plusWeeks(1);
if (date.getYear() >= lastYear) {
break;
}
}
return result;
}
public List<RosterItem> buildRoster() {
var membersIterator = new EndlessIterator<>(members);
return listMondaysFromToday().stream().map(start -> {
var end = start.plusDays(6);
return new RosterItem(start, end, membersIterator.next());
}).collect(Collectors.toList());
}
public static void main(String[] args) {
var members = Arrays.asList(
"Alice",
"Bob",
"Carol",
"Derek",
"Eve");
var builder = new RosterBuilder(members, 2023);
builder.buildRoster().forEach(r ->
System.out.println(r.getStart() + " - " + r.getEnd() + ": " + r.getName()));
}
}
@Data
@Builder
@AllArgsConstructor
class RosterItem {
private LocalDate start;
private LocalDate end;
private String name;
}
class EndlessIterator<T> {
private final Collection<T> items;
private Iterator<T> it;
public EndlessIterator(Collection<T> items) {
this.items = items;
it = items.iterator();
}
public T next() {
if (!it.hasNext()) {
it = items.iterator();
}
return it.next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment