473,487 Members | 2,448 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Need Help In Understanding The Logic And Code Of The Simulation

1 New Member
Hi guys..

I'm a newbie in java and I try to understand the logic of this simulation

I want to control the arrival value of the customer and server.

There is no error but the result is mess up. The code did not match with the logic of simulation. Can anyone help me?

This is the code that I put inside:

Expand|Select|Wrap|Line Numbers
  1. int[] servers = {1, 2, 3, 5};
  2.  
  3.             for (int nserv : servers) 
  4.              {
  5.                 simulateServers(lambdaA, lambdaS, tEnd, nserv);
  6.              }   
  7.  
  8.  
  9.  
  10.             int[] arrivalEvent = {100, 200, 300, 400};
  11.  
  12.             for (int i = 0; i < arrivalEvent.length; i++) 
  13.                 {
  14.                 int ta = arrivalEvent[i];
  15.                 System.out.println("Testing" + ta);
  16.             //  simulateArrival(lambdaA, lambdaS,  tEnd,   arrivalEvent);
  17.                 }
  18.             }
  19.  
  20. //// Below is the initial code//////
  21.  
  22. import java.util.ArrayList;
  23. import java.text.DecimalFormat;
  24.  
  25. /**
  26.  * This class implements a simple FIFO (first-in-first-out) queue simulation.
  27.  * 
  28.  
  29. public class Simulate3 {
  30.  
  31.     private static boolean openPosition;
  32.     private static double fractionAvg = 0.0;
  33.     private static DecimalFormat percent;
  34.  
  35.  
  36.     public static void main(String[] args) {
  37.         double lambdaA = 58.0;
  38.         double lambdaS = 30.0;
  39.         double tEnd = 8.0;
  40.         /**
  41.          * By starting and finishing shift with 1 server, almost 98.484848% of
  42.          * customers wait more than 6 mins with the avg wait time at 218 hours.
  43.          * With 2 servers the avg wait time is 13 hours with 69.1489% waiting
  44.          * more than 6 mins. With 3 servers the avg waiting time is 26mins with
  45.          * 0% of customers waiting more than 6 mins. Therefore the optimal
  46.          * allocation will be by assigning 2 servers to start off the shift and
  47.          * when the need arises, open a new position of service. If 1 server
  48.          * alone starts, the fraction in close to 16%. By starting with 2 servers
  49.          * the fraction is 4.3%.
  50.          */
  51.         int nserv = 2;
  52.  
  53.         // The starting seed for the random number generator
  54.         long seed = 12342;
  55.  
  56.         //The number of times the simulation will be repeated for the average statistics
  57.         int trials =100;
  58.  
  59.         // Conduct a number of trials in order to get the average fraction of customers
  60.         // waiting more than 6 mins. Use different seed in each trial.
  61.         for (int i = 1; i <= trials; i++) {
  62.             simulateNServers(lambdaA, lambdaS, tEnd, nserv, seed);
  63.             seed++;
  64.         }
  65.         double trialAvg = fractionAvg/trials;
  66.         percent = new DecimalFormat("0.#%");    
  67.         System.out.println("=============================================================================");
  68.         System.out.println();
  69.         System.out.println("Average percent of task waiting more than 6 minutes (100 trials) : "+percent.format(trialAvg));
  70.  
  71.     }
  72.  
  73.     /**
  74.      * Static method to run a simulation with certain parameters. It outputs the
  75.      * following statistical data.
  76.      * 
  77.      * Average waiting time   : 
  78.      * Server free fraction   : [The percentage of the servers being free]
  79.      * Maximum queue length   : 
  80.      * Total customers arrived: [Total arrivals of customers within the work-day]
  81.      * Total customers served : [Total customers served within the work-day]
  82.      * Total customers >6min  : [Total number of customers that waited more than 6 minutes to be served, within the work-day]
  83.      * fraction               : [Percentage of customers that waited more than 6 minutes in the queue]
  84.      * 
  85.      * @param lambdaA
  86.      *            Mean of exponential inter-arrival distribution.
  87.      * @param lambdaS
  88.      *            Mean of erlang completion distribution.
  89.      * @param tEnd
  90.      *            The time until the end of the work-day
  91.      * @param nserv
  92.      *            The number of servers in the branch
  93.      * @param seed 
  94.      */
  95.     public static void simulateNServers(double lambdaA, double lambdaS,
  96.             double tEnd, int nserv, long seed) {
  97.         Queue q = new Queue(); // Initializes up the Queue
  98.         ArrayList<Server> serverFree = new ArrayList<Server>(); // Create list of servers
  99.         MyRandom r = new MyRandom(seed); // Initializes the random number
  100.         // generator
  101.         int k = 3; // Initializes the kappa of the Erlang distribution
  102.  
  103.         double clock = 0; // Start of time
  104.         double tna = 0.0; // Time to next arrival
  105.         //double[] tnc = new double[nserv]; // Times of size nserv of completion
  106.                                             // for every server [i]
  107.         double endTime = tEnd; // Minutes until endtime
  108.         int te = 0; // Number of total events
  109.         int ta = 0; // Number of total arrivals
  110.         double tne = 0.0; // The time to the next event
  111.         int qLength = 0; // Max Q length
  112.  
  113.         double timeFree = 0.0; // Time free at each instance
  114.         double ttServer = 0.0; // Total server free time
  115.         double ttServerFree = 0.0;
  116.         double ttwait = 0.0; // Total waiting time
  117.         double ttServed = 0.0; // Total Number of Customers
  118.         double ttWait6 = 0.0; // Number of customers waiting more than 6 minutes
  119.         int busySrv = 0;    // The total number of servers busy for all events  
  120.         int prevHour = 0;       // Keeping track of which hour has finished
  121.         int hourStartEvent = 0;
  122.         int serverSum = 0;
  123.         double serverHourlyAvg = 0.0;
  124.  
  125.         // Initialize the servers' status
  126.         for (int i = 0; i < nserv; i++) {
  127.             serverFree.add(new Server(true));
  128.         }
  129.  
  130.         // Initialise the first completion time to 0.0
  131.         Server tmpSrv = serverFree.get(0);
  132.         tmpSrv.setTnc(0.0);
  133.         serverFree.set(0, tmpSrv);
  134.  
  135.         // Primary simulation loop
  136.         while (true) {
  137.  
  138.             boolean arrivalEvent = false; // The type of the next event, arrival
  139.                                             // or otherwise
  140.             boolean serviceEvent = false; // The type of the next event, service
  141.                                             // or otherwise
  142.             // Keep track of previous event for server free statistics
  143.             double prevEvent = 0.0;
  144.             // Check if the length of the Q is the largest
  145.             if (q.length() > qLength) {
  146.                 qLength = q.length();
  147.             }
  148.             //Keep track of the fraction of customers waiting more than 6mins
  149.             //This should not exceed 5% on average
  150.             double fraction = ttWait6 / ttServed;
  151.  
  152.             // Print out the fraction per event
  153.             System.out.println("fraction: "
  154.                     + fraction);
  155.             // Prints out the number of servers
  156.             int servers=serverFree.size();
  157.             System.out.println("servers: "
  158.                     + servers);
  159.  
  160.             // Keep track of how many servers are busy
  161.             busySrv += busyServersNo(serverFree);
  162.  
  163.             // Get the next completion time from all servers
  164.             double tnc;
  165.             Server tmp = getNextTNC(serverFree); 
  166.             if(tmp!=null) tnc = tmp.getTnc();
  167.             else tnc=Double.POSITIVE_INFINITY;
  168.             int tnc_index = serverFree.indexOf(tmp);
  169.  
  170.             // Check if the next event is a feasible arrival time
  171.             tne = Math.min(tna, tnc);
  172.             if (tne == tna && tna != tnc) {
  173.                 arrivalEvent = true;
  174.                 serviceEvent = false;
  175.             } else if (tne == tnc && tna != tnc) {
  176.                 serviceEvent = true;
  177.                 arrivalEvent = false;
  178.             } else if (tna == tnc) {
  179.                 arrivalEvent = true;
  180.             }
  181.  
  182.             // Update the clock
  183.             if (tne != Double.POSITIVE_INFINITY) {
  184.                 prevEvent = clock;
  185.                 clock = tne;
  186.             }
  187.  
  188.             /**
  189.              * In this block I'll be keeping some statistics for the average
  190.              * allocation of servers per hour
  191.              */
  192.             int currHour=(int) clock;
  193.             if(currHour==prevHour)
  194.             {
  195.                 serverSum+=servers;
  196.  
  197.             }else if (currHour>=prevHour){
  198.                 serverHourlyAvg= (double) serverSum/(te-hourStartEvent);
  199.                 System.out.println("Avg servers for hour "+currHour+" : "+serverHourlyAvg);
  200.                 serverSum = 0;
  201.                 hourStartEvent=te;
  202.                 prevHour=currHour;
  203.             }
  204.  
  205.             /**
  206.              * Every time the cycle begins there needs to be a check whether the
  207.              * optimality constraint is met. This constraint is that the queue
  208.              * is no larger than 6 customers. If it is not, then the algorithm
  209.              * needs to set up a flag that will increase the number of servers
  210.              * until the constraint is satisfied.
  211.              */
  212.             if (q.length()>6) {
  213.                 openPosition=true;
  214.             }else openPosition=false;
  215.  
  216.             // Get the index of the next available server
  217.             int id = getFreeServer(serverFree);
  218.             // BRANCH_1// Check if the condition to stop the simulation has been met.
  219.             if (q.isEmpty() && clock >= endTime
  220.                     && tnc == Double.POSITIVE_INFINITY) {
  221.                 percent = new DecimalFormat("0.0#%");
  222.                 System.out.println("Average waiting time: " + 60*ttwait
  223.                         / ttServed+" minutes");
  224.                 System.out.println("Server free fraction: " + percent.format(ttServer/ ttServerFree));
  225.                 System.out.println("Maximum queue length: " + qLength);
  226.                 System.out.println("Total tasks arrived: " + ta);
  227.                 System.out.println("Total tasks served : " + (int) ttServed);
  228.                 System.out.println("Total tasks waiting >6min  : " + (int) ttWait6);
  229.                 System.out.println(" fraction              : "     + fraction);
  230.                 fractionAvg+=fraction;
  231.                 System.out.println(" server avg            : " + ((double) busySrv/te));
  232.                 break;
  233.             }
  234.  
  235.             // BRANCH_2// This is an arrival event and the end time is not reached
  236.             if (arrivalEvent && clock < endTime) {
  237.                 if (id != -1)
  238.                     timeFree = clock - prevEvent;
  239.                 ttServerFree += timeFree;
  240.                 ttServer += timeFree * freeServersNo(serverFree);
  241.                 // Report how many servers are free and for how long
  242.                 if (freeServersNo(serverFree) != 0)
  243.                     System.out.println(freeServersNo(serverFree) + " server(s) are free for " + timeFree + " hours. Total= " + ttServer);
  244.  
  245.                 // Sample for next arrival time so long that it doens't exceed endTime
  246.                 tna = clock + r.nextExponential(getLambda(clock));
  247.                 if (tna > tEnd) 
  248.                 {
  249.                     tna = Double.POSITIVE_INFINITY;
  250.                 }
  251.  
  252.                 ta++;
  253.                 // BRANCH_3_YES
  254.                 // Inner conditional loop to check if there is at least one server free
  255.                 if (id != -1) {
  256.                     // Mark the server as busy by replacing the object in the arraylist
  257.                     Server tmpSrv0 = serverFree.get(id);
  258.                     tmpSrv0.setState(false);
  259.  
  260.                     // Sample for time of next completion
  261.                     tmpSrv0.setTnc(clock + r.nextErlang(k, lambdaS));
  262.                     serverFree.set(id, tmpSrv0);
  263.  
  264.                 } else {// BRANCH_3_NO
  265.                     //
  266.                     // Put person in the queue
  267.                     q.put(clock);
  268.                     // If there is need for servers add one here
  269.                     if (openPosition) serverFree.add(new Server(true));
  270.                 }
  271.                 // Print out the arrival event
  272.                 System.out.println(" Total event arrival: " +  te + "  " + "" + " Queue length: " + q.length() + " Time: " + clock);
  273.                 if (q.isEmpty()) {
  274.                     // System.out.println("Guy is served, has waited: 0.0");
  275.                     ttServed++;
  276.                 }
  277.             } else {
  278.                 // BRANCH_4_YES// This is a service completion event
  279.                 if (serviceEvent) {
  280.                     if (id != -1)
  281.                         timeFree = clock - prevEvent;
  282.                     ttServerFree += timeFree;
  283.                     ttServer += timeFree * freeServersNo(serverFree);
  284.                     // Report how many servers are free and for how long
  285.                     if (freeServersNo(serverFree) != 0)
  286.                         System.out.println(freeServersNo(serverFree) + " server(s) are free for " + timeFree + " hours." + " Total : " + ttServer);
  287.                     // BRANCH_5_YES// Inner conditional loop to check if the
  288.                     // queue is empty
  289.                     if (q.isEmpty()) {
  290.  
  291.                         // If there is no more need; release the additional server
  292.                         if (!openPosition && serverFree.size()>nserv && id!=-1) serverFree.remove(id);
  293.  
  294.                         // Get the first busy server and release them
  295.                         int busy = serverFree.indexOf(getNextTNC(serverFree));
  296.                         if (busy != -1){
  297.                             // Mark the server as busy by replacing the object in the arraylist
  298.                             Server tmpSrv1 = serverFree.get(busy);
  299.                             tmpSrv1.setState(true);
  300.                             serverFree.set(busy, tmpSrv1);
  301.                         }
  302.  
  303.                         if (busy != -1){
  304.                             Server tmpSrv2 = serverFree.get(busy);
  305.                             tmpSrv2.setTnc(Double.POSITIVE_INFINITY);
  306.                             serverFree.set(busy, tmpSrv2);
  307.                         }
  308.  
  309.  
  310.                     }// End of yes in Condition 5
  311.                     else {// BRANCH_5_NO//
  312.                             // Get person from queue
  313.                         double t = q.get();
  314.  
  315.                         // Log the served customer
  316.                         ttServed++;
  317.                         // Check which customers waited more than 6 minutes (0.1
  318.                         // of the hour)
  319.                         if ((clock - t) > 0.1) {
  320.                             // If it took more than 6 minutes to serve, log it.
  321.                             ttWait6++;
  322.                         }
  323.                         System.out.println("Tasks is served, has waited: "
  324.                                 + (clock - t));
  325.                         // Update the sum of waiting times
  326.                         ttwait += (clock - t);
  327.  
  328.                         // Sample for time of next completion
  329.                         Server tmpSrv3 = serverFree.get(tnc_index);
  330.                         tmpSrv3.setTnc(clock + r.nextErlang(k, lambdaS));
  331.                         serverFree.set(tnc_index, tmpSrv3);
  332.  
  333.                     }// End of no in Condition 5
  334.                         // Write out the Completion of the event
  335.                     int event = tnc_index + 1;
  336.                     System.out.println("Total event : "+ te + "  " + "completed : " + event + "  " + "Queue length: " + q.length() + " Time: " + clock);
  337.  
  338.                 }// End of Condition 4
  339.                 else {// BRANCH_4_NO//
  340.                         // Set next arrival time to very large number
  341.                     tna = Double.POSITIVE_INFINITY;
  342.                 }// End of Infinite arrival time
  343.             }// End of no in Condition 2
  344.                 // Increment the number of events
  345.             te++;
  346.         }// End of while loop
  347.     }// End of static main method
  348.  
  349.  
  350.  
  351.     /**
  352.      * Method to get the appropriate average of arriving customers per hour of
  353.      * service. The distributions were provided by the manager. They can be 
  354.      * changed to any measured distribution.
  355.      * 
  356.      * @param Clock
  357.      *            The current time
  358.      * @return The average customers arriving for this hour
  359.      */
  360.     private static double getLambda(double clock) {
  361.         switch ((int) clock) {
  362.         case 0:
  363.             return 58.0;
  364.         case 1:
  365.             return 50.0;
  366.         case 2:
  367.             return 70.0;
  368.         case 3:
  369.             return 80.0;
  370.         case 4:
  371.             return 40.0;
  372.         case 5:
  373.             return 60.0;
  374.         case 6:
  375.             return 50.0;
  376.         case 7:
  377.             return 70.0;
  378.         default:
  379.             return 0;
  380.         }
  381.  
  382.     }
  383.  
  384.  
  385.     /**
  386.      * Find the first server that is free.
  387.      * @param serverFree The arraylist in which to look for a free server
  388.      * @return  The index of the position of the first free server
  389.      */
  390.     private static int getFreeServer(ArrayList<Server> serverFree) {
  391.         for (Server server : serverFree) {
  392.             boolean state = server.isState();
  393.             if (state){
  394.                 return serverFree.indexOf(server);
  395.             }
  396.         }return -1;
  397.     }// End of getFreeServer method
  398.  
  399.     /**
  400.      * Find the first server that is busy.
  401.      * @param serverFree The arraylist in which to look for a busy server
  402.      * @return The index of the position of the first busy server
  403.      */
  404.     private static int getBusyServer(ArrayList<Server> serverFree) {
  405.         for (Server server : serverFree) {
  406.             boolean state = server.isState();
  407.             if (state){
  408.                 return serverFree.indexOf(server);
  409.             }
  410.         }return -1;
  411.     }// End of getFreeServer method
  412.  
  413.     /**
  414.      * Count the free servers
  415.      * @param serverFree The arraylist in which to look for a free server
  416.      * @return The number of servers that are free
  417.      */
  418.     private static int freeServersNo(ArrayList<Server> serverFree) {
  419.         int servers = 0;
  420.         for (Server server : serverFree) {
  421.             boolean state = server.isState();
  422.             if (state) servers++;
  423.         }
  424.         return servers;
  425.     }// End of freeServersNo method
  426.  
  427.     /**
  428.      * Count the busy servers
  429.      * @param serverFree The arraylist in which to look for a busy server
  430.      * @return The number of servers that are busy
  431.      */
  432.     private static int busyServersNo(ArrayList<Server> serverFree) {
  433.         int servers = 0;
  434.         for (Server server : serverFree) {
  435.             boolean state = server.isState();
  436.             if (!state) servers++;
  437.         }
  438.         return servers;
  439.     }// End of busyServersNo method
  440.  
  441.  
  442.     /**
  443.      * Find the server with the lowest completion time
  444.      * @param tnc_min The arraylist to search for completion times 
  445.      * @return The index of the lowest time of completion
  446.      */
  447.     private static Server getNextTNC(ArrayList<Server> serverFree) {
  448.         double tnc_min = Double.POSITIVE_INFINITY;
  449.         Server index = null;
  450.         for (Server server : serverFree) {
  451.             if(server.getTnc() < tnc_min) {
  452.                 tnc_min = server.getTnc();
  453.                 index=server;
  454.             }
  455.  
  456.         }
  457.         return index;
  458.     }// End of getNextTNC method
  459. }// End of Class
  460.  
May 22 '17 #1
1 1109
chaarmann
785 Recognized Expert Contributor
This is too much to read.
You said there is something wrong but you did not tell us what exactly. I can only guess but I cannot read your mind.
We must analyze method by method.
Can you please specify by example which logic did not match. I mean what output you expected versus the actual computation, for each method.

Why don't you write JUnit-Tests for each method (or show us the tests if already there)? Then we can see for each method what we need to fix so that the output matches your expectations.
May 24 '17 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2125
by: worzel | last post by:
need some simple code to copy text to clipboard in c# - my app has right click > copy to clicpboard feature, which is best way to do this?
6
3564
by: Randy Harris | last post by:
I wonder if I might get some of you to describe methods or tools that you've found effective to store and manage code snippets and routines. I don't have a particular need to share code with other...
16
8997
by: MS newsgroup | last post by:
I don't have clear reasons why we need business logic layer and data logic layer instead of having only data logic layer. Are there any good reasons for that?
14
5487
by: mistral | last post by:
Need compile python code, source is in html and starts with parameters: #!/bin/sh - "exec" "python" "-O" "$0" "$@" I have installed ActivePython for windows.
0
1385
by: Jyothihathwar | last post by:
Hi Friends, I am displaying data using Datagrid and i have set properties as Allow Pagin = "True" and PageSize as 10.So for ex if there are records then first 10 records will be displayed first...
2
4469
by: deltaa5 | last post by:
Hi. i need a source code compute logical expressions in lex/yacc. for Example: (20>5) or (6<=6)--->true (1<=2) and (3==1) --->false.
1
7486
by: leox | last post by:
Need C++ source code for Coppersmith-Winograd algorithm of mathrics multiplication. Is there any c++ internet library?
3
2971
by: =?gb2312?B?zfW2rA==?= | last post by:
I need a C++ code style checker. Which is the best choice? free or for fee.
1
1110
by: Vini8888 | last post by:
Hello. I'm trying to request some assitance regarding a vba code that will allow me to enter a ticket number in a combo box and by clicking the search button an entry will upload on my form and allow...
0
7142
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7352
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5445
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4875
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3078
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1383
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
618
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
272
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.