-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimalShelter.java
More file actions
executable file
·73 lines (59 loc) · 2.13 KB
/
Copy pathAnimalShelter.java
File metadata and controls
executable file
·73 lines (59 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package algorithm.cracking.stacks;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.Optional;
import java.util.Queue;
/**
* An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis.
* People must adopt either the "oldest" (based on arrival time) of all animals at the shelter,
* or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of
* that type). They cannot select which specific animal they would like. Create the data structures to
* maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog,
* and dequeueCat. You may use the built-in Linkedlist data structure.
*/
public class AnimalShelter {
Queue<Dog> queueDogs = new LinkedList<>();
Queue<Cat> queueCats = new LinkedList<>();
void enqueue(Animal animal) {
if (animal instanceof Dog dog) queueDogs.offer(dog);
else if (animal instanceof Cat cat) queueCats.offer(cat);
else throw new RuntimeException("Unsupported animal");
}
Optional<?> dequeueAny() {
if (queueDogs.isEmpty()) return dequeueCat();
if (queueCats.isEmpty()) return dequeueDog();
var oldDog = queueDogs.peek();
var oldCat = queueCats.peek();
if (oldDog.getArrivalDate().isBefore(oldCat.getArrivalDate())) {
return dequeueDog();
} else {
return dequeueCat();
}
}
Optional<Dog> dequeueDog() {
return Optional.ofNullable(queueDogs.poll());
}
Optional<Cat> dequeueCat() {
return Optional.ofNullable(queueCats.poll());
}
@Getter
@NoArgsConstructor
@SuperBuilder
@ToString
abstract static class Animal {
private String name;
private LocalDateTime arrivalDate;
}
@SuperBuilder
@Getter
static class Dog extends Animal {
}
@SuperBuilder
@Getter
static class Cat extends Animal {
}
}