Skip to content

Instantly share code, notes, and snippets.

@kelvintaywl
Last active August 29, 2015 14:07
Show Gist options
  • Save kelvintaywl/0a583f8c0f2faa8396a6 to your computer and use it in GitHub Desktop.
Save kelvintaywl/0a583f8c0f2faa8396a6 to your computer and use it in GitHub Desktop.
kennyroharjo_deque
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Comparator;
import java.util.Arrays;
public class RaharjoQueue {
static int DEFAULT_PACK_SIZE = 3;
private List<String> customers; // list of customers in original order
private List<String> orders; // order of customers handled
private int packSize;
public class CustomerComparator implements Comparator<String> {
public int compare(String a, String b){
if(isIrate(a) && isIrate(b)){
return -1; // -1 because we should swap b in front of a
}
else if(isIrate(a) && !isIrate(b)){
return -1;
}
else if(!isIrate(a) && isIrate(b)){
return 1;
}
else {
return 0;
}
}
public boolean isIrate(String customer){
return customer.charAt(0) == 'I';
}
}
public RoharjoQueue(List<String> customers){
this.customers = new ArrayList<String>(customers);
this.orders = new ArrayList<String>(); // initialize empty
this.packSize = RoharjoQueue.DEFAULT_PACK_SIZE;
}
public RoharjoQueue(List<String> customers, int packSize){
this.customers = new ArrayList<String>(customers);
this.orders = new ArrayList<String>(); // initialize empty
this.packSize = packSize;
}
public List<String> handleCustomers(){
List<String> queue = new ArrayList<String>();
int customerIndex = 0;
do {
if(queue.size() < 20){
List<String> nextWave;
try{
nextWave = this.customers.subList(customerIndex, customerIndex + this.packSize);
queue.addAll(nextWave);
}
catch(Exception e){
if(customerIndex < this.customers.size()){
nextWave = this.customers.subList(customerIndex, this.customers.size());
queue.addAll(nextWave);
};
};
};
Collections.sort(queue, new CustomerComparator());
String nextCustomer = queue.remove(0); // first customer in queue
this.orders.add(nextCustomer);
//updates
customerIndex += this.packSize;
} while (queue.size() > 0);
return this.orders;
}
}
@kelvintaywl
Copy link
Author

@ kenny: import RaharjoQueue class / data structure onto a separate file (for instance, in a test file). Example,

import RaharjoQueue;

public class TryingOutRaharjoQueue{

     public static void main(String []args){
        List<String> customers = Arrays.asList("N1", "N2", "N3", "I1", "N4", "I2", "N5");
        RoharjoQueue que = new RoharjoQueue(customers);
        List<String> order = que.handleCustomers();

        for(String customer : order){
            System.out.println(customer);
        }; 
     }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment