title: Simulating a Grocery Store Line Queue using Java
body: <p>So I have a problem I've been wracking my brain over for about a week now. The situation is:</p>
  
  <blockquote>
    <p>Consider a checkout line at the grocery store. During any given
    second, the probability that a new customer joins the line is 0.02 (no
    more than one customer joins the line during any given second). The
    checkout clerk takes a random amount of time between 20 seconds to 75
    seconds to serve each customer. Write a program to simulate this
    scenario for about ten million seconds and print out the average
    number of seconds that a customer spends waiting in line before the
    clerk begins to serve the customer. Note that since you do not know
    the maximum number of customers that may be in line at any given time,
    you should use an ArrayList and not an array.</p>
  </blockquote>
  
  <p>The expected average wait time is supposed to be between 500 and 600 seconds. However, I have not gotten an answer anywhere close to this range. Given that the probability of a new customer in the line is only 2%, I would expect the line to never have more than 1 person in it, so the average wait time would be about 45-50 secs. I have asked a friend (who is a math major) what his view on this problem, and he agreed that 45 seconds is a reasonable average given the 2% probability. My code so far is: </p>
  
  <pre><code>package grocerystore;
  
  import java.util.ArrayList;
  import java.util.Random;
  
  public class GroceryStore {
  
  private static ArrayList&lt;Integer&gt; line = new ArrayList();    
  private static Random r = new Random();
  
  public static void addCustomer() {        
      int timeToServe = r.nextInt(56) + 20;
      line.add(timeToServe);        
  }    
  
  public static void removeCustomer() {
      line.remove(0);
  }
  
  public static int sum(ArrayList&lt;Integer&gt; a) {
      int sum = 0;
      for (int i = 0; i &lt; a.size(); i++) {
          sum += a.get(i);
      }
      return sum;
  }
  
  public static void main(String[] args) {
        int waitTime = 0;
        int duration = 10000;
        for (int i = 0; i &lt; duration; i++) {              
            double newCust = r.nextDouble();
  
            if (newCust &lt; .02) {
                addCustomer();
            }
  
            try {
                for (int j = 0; j &lt; line.get(0); j++) {                                          
                    waitTime = waitTime + sum(line);                      
                }
            } catch (IndexOutOfBoundsException e) {}                
  
            if (line.isEmpty()) {}
            else {
                removeCustomer();
            }
        }
        System.out.println(waitTime/duration);
  }
  
  }
  </code></pre>
  
  <p>Any advice about this would be appreciated. </p>