To do that, I create two functions, one that increases the queue of customers (with the shop supporting up to 3 customers) amd one that dispatces customers, decreasing the queue. I assume 4 hours for customers to be able to take a seat (the barber's will close after 4 hours and cut the remaining wating customers).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns barber-2) | |
(def seats 3) | |
(def max-time (* 4 3600) ) | |
(def queue (ref 0)) | |
(def total (ref 0)) | |
(defn customer-enter [t] | |
(let [f (if (< @queue 3) inc identity)] | |
(dosync (alter queue f)) )) | |
(defn barber-work [k r o n] | |
(if (>= n o) | |
(let [rnd (. (java.util.Random. ) nextInt 200)] | |
(if (< rnd 150) | |
(dosync | |
(println "Queue: " @queue) | |
(alter queue dec) | |
(alter total inc) ))))) | |
(add-watch queue 0 barber-work) | |
(defn cut [] | |
(loop [t max-time] | |
(if (> t 0) | |
(let [interval (+ 1200 (. (java.util.Random. ) nextInt (* 10 60)) )] | |
(java.lang.Thread/sleep interval) | |
(customer-enter interval) | |
(println t) | |
(recur (- t interval) ) )))) | |
(cut) | |
(println "Total haircuts: " @total) |
The important functional element is this
(let [f (if (< @queue 3) inc identity)]Notice the conditional assignment to the variable in the let block. This removes the boilerplate code needed in the expression section within the let block.
(dosync (alter queue f)) ))
No comments:
Post a Comment