I have been working my way through the problems in the book Cracking the Coding Interview. The instructions were to maintain an animal shelter that operates on a first in, first out basis (i.e. it is a queue). People must adopt the "oldest" (based on arrival time) of all animals at the shelter, or if they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot choose which specific animal they would like.
AnimalShelter.java
package problem_2_9;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class AnimalShelter {
public enum AnimalType{
DOG, CAT
}
private int animalId;
LinkedList<Integer> cats;
LinkedList<Integer> dogs;
public AnimalShelter(){
cats = new LinkedList<Integer>();
dogs = new LinkedList<Integer>();
}
public void enqueue(AnimalType type){
switch(type){
case DOG:
dogs.add(animalId);
animalId++;
break;
case CAT:
cats.add(animalId);
animalId++;
break;
}
}
public Integer dequeueCat(){
if(cats.isEmpty()) throw new NoSuchElementException("There are no cats in the animal shelter.");
return cats.pop();
}
public Integer dequeueDog(){
if(dogs.isEmpty()) throw new NoSuchElementException("There are no dogs in the animal shelter");
return dogs.pop();
}
public Integer dequeueAny(){
if(dogs.isEmpty() && cats.isEmpty()) throw new NoSuchElementException("There are no animals in the animal shelter.");
if(dogs.isEmpty()){
return cats.pop();
}
else if(cats.isEmpty()){
return dogs.pop();
} else{
if(cats.peek() < dogs.peek()){
return cats.pop();
}
else{
return dogs.pop();
}
}
}
}
I've tested the AnimalShelter
class using this code:
Main.java
package problem_2_9;
import problem_2_9.AnimalShelter.AnimalType;
public class Main {
public static void main(String[] args){
// dogs = 0 2 4 6
// cats = 1 3 5 7
AnimalShelter shelter = new AnimalShelter();
for(int i = 0; i < 4; i++){
shelter.enqueue(AnimalType.DOG);
shelter.enqueue(AnimalType.CAT);
}
for(int i = 0; i < 4; i++){
System.out.println(shelter.dequeueCat());
System.out.println(shelter.dequeueDog());
}
}
}