Advertisement
Tal_Rofe

Up

Jan 15th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.55 KB | None | 0 0
  1. package algorithm;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import java.util.concurrent.SynchronousQueue;
  7.  
  8. import org.json.JSONArray;
  9. import org.json.JSONException;
  10. import org.json.JSONObject;
  11.  
  12. public class Algorithm{
  13.    
  14.     private static class ArrayListCar extends ArrayList<Car>{
  15.        
  16.     }
  17.    
  18.     private int spotsInRow; // as an input from server. possible value: 4,5,6,7,8
  19.     private ArrayListCar[][][] park; // each spot has a list of all the cars belong to the spot
  20.     private char[][][] statusPark; // real time 3-dimensions array that has status for each spot
  21.     // e - EMPTY, f - FULL, i - INVALID, s - SAVE, o - ordered
  22.    
  23.     Algorithm(){ // CONSTRUCTOR
  24.         spotsInRow = 4; // spotsInRow = 4 as an initial value
  25.         statusPark = new char[3][3][4];
  26.         park = new ArrayListCar[3][3][4];
  27.        
  28.         int i, j, k;
  29.         for (i = 0; i < 3; i++)
  30.             for (j = 0; j < 3; j++)
  31.                 for(k = 0; k < 4; k++) {
  32.                     park[i][j][k] = new ArrayListCar(); // each cell has an empty list as an initial state
  33.                     statusPark[i][j][k] = 'e';
  34.                 }
  35.         }
  36.    
  37.     Algorithm(int numSpotsInRow){ // 2nd CONSTRUCTOR
  38.         statusPark = new char[3][3][numSpotsInRow];
  39.         park = new ArrayListCar[3][3][numSpotsInRow];
  40.         spotsInRow = numSpotsInRow;
  41.        
  42.         int i, j, k;
  43.         for (i = 0; i < 3; i++)
  44.             for (j = 0; j < 3; j++)
  45.                 for (k = 0; k < numSpotsInRow; k++) {
  46.                     park[i][j][k] = new ArrayListCar();
  47.                     statusPark[i][j][k] = 'e';
  48.                 }
  49.     }
  50.    
  51.     public Algorithm(int numSpotsInRow, String db, String si){ // 3rd CONSTRUCTOR
  52.         this.spotsInRow = numSpotsInRow;
  53.         this.park = generateParkFromString(db);
  54.         this.statusPark = generateStatusPark(si);
  55.        
  56.         int i, j, k;
  57.         for (i = 0; i < 3; i++)
  58.             for (j = 0; j < 3; j++)
  59.                 for (k = 0; k < numSpotsInRow; k++)
  60.                     // sort by exit time. It also means it is sorted by entry time.
  61.                     Collections.sort(park[i][j][k]);
  62.     }
  63.    
  64.     private char[][][] generateStatusPark(String si){
  65.         //TODO: make row width dynamic
  66.         char[][][] tmpStatuses = new char[3][3][4];
  67.         try {
  68.             JSONArray statuses = new JSONArray(si);
  69.             for(int index = 0; index < statuses.length(); index++) {
  70.                 JSONObject current = statuses.getJSONObject(index);
  71.                 int i = current.getInt("i");
  72.                 int j = current.getInt("j");
  73.                 int k = current.getInt("k");
  74.                 tmpStatuses[i][j][k] = current.getString("status").charAt(0);
  75.                
  76.             }
  77.         } catch (JSONException e) {
  78.             // TODO Auto-generated catch block
  79.             e.printStackTrace();
  80.         }
  81.         return tmpStatuses;
  82.     }
  83.    
  84.     private ArrayListCar[][][] generateParkFromString(String st){
  85.         ArrayListCar[][][] cars = new ArrayListCar[3][3][4];
  86.         for (int i = 0; i < 3; i++)
  87.             for (int j = 0; j < 3; j++)
  88.                 for(int k = 0; k < 4; k++)
  89.                     cars[i][j][k] = new ArrayListCar();
  90.         try {
  91.             JSONArray arr = new JSONArray(st);
  92.             for(int index = 0; index < arr.length(); index++) {
  93.                 JSONObject current = arr.getJSONObject(index);
  94.                 int i = current.getInt("i");
  95.                 int j = current.getInt("j");
  96.                 int k = current.getInt("k");
  97.                 String carID = current.getString("carID");
  98.                 long entryTime = current.getLong("entryTime");
  99.                 long exitTime = current.getLong("exitTime");
  100.                 if(cars[i][j][k] == null) {
  101.                     cars[i][j][k] = new ArrayListCar();
  102.                 }
  103.                 cars[i][j][k].add(new Car(carID, exitTime, entryTime));
  104.             }
  105.         } catch (JSONException e) {
  106.             // TODO Auto-generated catch block
  107.             e.printStackTrace();
  108.         }
  109.        
  110.         return null;
  111.     }
  112.    
  113.     //------------------------//
  114.    
  115.     // function checks whether specific spot is empty in real time or not
  116.         private boolean isEmptySpotRealTime(int i, int j, int k){
  117.             if (statusPark[i][j][k] == 's' || statusPark[i][j][k] == 'i')
  118.                 return false;
  119.            
  120.             long realTime = System.currentTimeMillis();
  121.             int z;
  122.             for (z = 0; z < park[i][j][k].size(); z++){
  123.                 if (realTime <= park[i][j][k].get(z).getExitTime() &&
  124.                         realTime >= park[i][j][k].get(z).getEntryTime())
  125.                     return false;
  126.             }
  127.             return true;
  128.         }
  129.  
  130.         // function checks whether specific spot is empty but has ordered cars belong to it
  131.         private boolean isEmptyButOrderedRealTime(int i, int j, int k){
  132.             if (!park[i][j][k].isEmpty() && isEmptySpotRealTime(i, j, k))
  133.                 return true;
  134.             return false;
  135.         }
  136.        
  137.         // function gets specific list of cars that have any connection with a specific spot
  138.         // returns true if the specific spot is empty in the given times
  139.         private boolean checkAvailableSpot(long entryTime, long exitTime, ArrayListCar list){
  140.             // NO NEED TO CHECK 's' , 'i' CASES
  141.            
  142.             if (list.isEmpty()){
  143.                 return true;
  144.             }
  145.             else if (exitTime <= list.get(0).getEntryTime())
  146.                 return true;
  147.             else if (entryTime >= list.get(list.size() - 1).getExitTime())
  148.                 return true;
  149.             else{
  150.                 int z;
  151.                 for (z = 0; z < list.size() - 1; z++){
  152.                     if (entryTime >= list.get(z).getExitTime() && exitTime <= list.get(z+1).getEntryTime())
  153.                         return true;
  154.                 }
  155.                 return false;
  156.             }
  157.         }
  158.        
  159.         // function checks whether the park is available to insertion command in the given times
  160.         private boolean checkAvailablePark(long entryTime, long exitTime){
  161.             int i, j, k;
  162.             for (i = 0; i < 3; i++)
  163.                 for (j = 0; j < 3; j++)
  164.                     for (k = 0; k < spotsInRow; k++)
  165.                         if ((statusPark[i][j][k] != 's' && statusPark[i][j][k] != 'i') &&
  166.                                 checkAvailableSpot(entryTime, exitTime, park[i][j][k]))
  167.                             return true;
  168.             return false;
  169.         }
  170.        
  171.         // function returns spot's coordinates where a given car is located at
  172.         private int[] locateCarSpot(String carID){
  173.             int[] a = {-1, -1, -1}; // an array holds the coordinates of the car
  174.             int i, j, k, z;
  175.            
  176.             for (i = 0; i < 3; i++){
  177.                 for (j = 0; j < 3; j++){
  178.                     for (k = 0; k < spotsInRow; k++){
  179.                         for(z = 0; z < park[i][j][k].size(); z++){
  180.                             if (park[i][j][k].get(z).getCarID().equals(carID)){
  181.                                 a[0] = i; a[1] = j; a[2] = k;
  182.                                 return a;
  183.                             }
  184.                         }
  185.                     }
  186.                 }
  187.             }
  188.             return a;
  189.         }
  190.        
  191.         // get the cars out of the park from a specific depth
  192.         // list is a list which keeps the ejected cars
  193.         private void ejectInDepth(ArrayListCar list, int i, int j, int k){
  194.             int t, z;
  195.             for (t = 0; t <= i; t++){
  196.                 if (statusPark[t][j][k] != 'i' && statusPark[t][j][k] != 's'){
  197.                     statusPark[t][j][k] = 'e'; // update the status because cars were ejected
  198.                    
  199.                     for (z = park[t][j][k].size() - 1; z >= 0; z--){
  200.                         list.add(park[t][j][k].get(z));
  201.                         park[t][j][k].remove(z);
  202.                     }
  203.                 }
  204.             }
  205.         }
  206.        
  207.         // get the cars out of the park from a specific floor
  208.         // list is a list which keeps the ejected cars
  209.         private void ejectInFloor(ArrayList<Car> list, int j, int k){
  210.             int t, z;
  211.             for (t = 0; t < j; t++){
  212.                 if (statusPark[0][t][k] != 'i' && statusPark[0][t][k] != 's'){
  213.                     statusPark[0][t][k] = 'e'; // update the status because cars we ejected
  214.                    
  215.                     for (z = park[0][t][k].size() - 1; z >= 0; z--){
  216.                         list.add(park[0][t][k].get(z));
  217.                         park[0][t][k].remove(z);
  218.                     }
  219.                 }
  220.             }
  221.         }
  222.        
  223.         // find the optimal position for an entry command of a car
  224.         private int[] locateOptimalSpot(long entryTime, long exitTime){
  225.             int i, j, k, z, moves, minMoves = 5;
  226.             int[] optimal = new int[3];
  227.             boolean st;
  228.            
  229.             for (k = 0; k < spotsInRow; k++){ // first loop on width
  230.                 for (j = 0; j < 3; j++){ // then loop on height
  231.                    
  232.                     moves = 0; // will be calculated with each iteration
  233.                    
  234.                     for (z = 0; z < j; z++){
  235.                         if (statusPark[0][z][k] != 'i' && statusPark[0][z][k] != 's'){
  236.                             st = checkAvailableSpot(entryTime, exitTime, park[0][z][k]);
  237.                             if (!st) // if the spot won't be empty in the given times we need to move another car
  238.                                 moves++;
  239.                         }
  240.                     }
  241.                    
  242.                     for (i = 0; i < 3; i++){           
  243.                         if (statusPark[i][j][k] != 'i' && statusPark[i][j][k] != 's'){
  244.                             st = checkAvailableSpot(entryTime, exitTime, park[i][j][k]);
  245.                             if (st)
  246.                                 break;
  247.                             moves++;
  248.                         }
  249.                     }
  250.                    
  251.                     if (moves < minMoves){ // when we find lower number of moves we update
  252.                         minMoves = moves;
  253.                         optimal[0] = i; optimal[1] = j; optimal[2] = k;
  254.                     }
  255.                 }
  256.             }
  257.             return optimal;
  258.         }
  259.        
  260.         // function plots back the ejected cars (given in list) into the park
  261.         // assume list is sorted by exit time
  262.         private void reEnterCars(ArrayListCar list, int i, int j, int k){
  263.             boolean cont;
  264.             long lastCTime;
  265.            
  266.             if (!list.isEmpty()){ // as long as we need to re-insert the ejected car
  267.                 int t = 0;
  268.                 for(t = 0; t < j; t++){
  269.                     if (statusPark[0][t][k] != 's' && statusPark[0][t][k] != 'i'){
  270.                         park[0][t][k].add(list.get(0));
  271.                         list.remove(0);
  272.                        
  273.                         cont = true;
  274.                         while (cont && !list.isEmpty()){
  275.                             lastCTime = park[0][t][k].get(park[0][t][k].size() - 1).getExitTime();
  276.                             if (list.get(0).getEntryTime() >= lastCTime){
  277.                                  park[0][t][k].add(list.get(0));
  278.                                  list.remove(0);
  279.                             }
  280.                             else
  281.                                 cont = false;
  282.                         }
  283.                        
  284.                         if (!isEmptySpotRealTime(0, t, k))
  285.                             statusPark[0][t][k] = 'f';
  286.                        
  287.                         if (isEmptyButOrderedRealTime(0, t, k))
  288.                             statusPark[0][t][k] = 'o';
  289.                     }
  290.                 }
  291.                
  292.                 t = 0;
  293.                 for(t = 0; t <= i; t++){
  294.                     if (statusPark[t][j][k] != 's' && statusPark[t][j][k] != 'i'){
  295.                         park[t][j][k].add(list.get(0));
  296.                         list.remove(0);
  297.                        
  298.                         cont = true;
  299.                         while (cont && !list.isEmpty()){
  300.                             lastCTime = park[t][j][k].get(park[t][j][k].size() - 1).getExitTime();
  301.                             if (list.get(0).getEntryTime() >= lastCTime){
  302.                                  park[t][j][k].add(list.get(0));
  303.                                  list.remove(0);
  304.                             }
  305.                             else
  306.                                 cont = false;
  307.                         }
  308.                     }
  309.                 }
  310.             }
  311.         }
  312.        
  313.         public void insertOrderedCar(Car car, long entryTime, long exitTime){
  314.             boolean fullPark = !this.checkAvailablePark(entryTime, exitTime);
  315.             if(fullPark){
  316.                 // Send message to server: insertion command failed
  317.             }
  318.            
  319.             else{
  320.                 int[] a = locateOptimalSpot(entryTime, exitTime);
  321.                 park[a[0]][a[1]][a[2]].add(car);
  322.                
  323.                 if(isEmptyButOrderedRealTime(a[0], a[1], a[2]))
  324.                     statusPark[a[0]][a[1]][a[2]] = 'o';
  325.             }
  326.         }
  327.        
  328.         public void insertCar(Car car){
  329.             long entryTime = car.getEntryTime(), exitTime = car.getExitTime();
  330.            
  331.             boolean fullPark = !this.checkAvailablePark((int)entryTime, exitTime);
  332.             if(fullPark){
  333.                 // Send message to server: insertion command failed
  334.             }
  335.            
  336.             else{
  337.                 int[] a = locateOptimalSpot(entryTime, exitTime);
  338.                 park[a[0]][a[1]][a[2]].add(car);
  339.                 Collections.sort(park[a[0]][a[1]][a[2]]);
  340.                 statusPark[a[0]][a[1]][a[2]] = 'f';
  341.                 ArrayListCar list = new ArrayListCar();
  342.                 ejectInDepth(list, a[0] - 1, a[1], a[2]);
  343.                 ejectInFloor(list, a[1], a[2]);
  344.                 Collections.sort(list);
  345.                 reEnterCars(list, a[0] - 1, a[1], a[2]);
  346.             }
  347.         }
  348.        
  349.         public void ejectCar(Car car){
  350.             int[] a = locateCarSpot(car.getCarID());
  351.             ArrayListCar list = new ArrayListCar();
  352.             ejectInDepth(list, a[0] - 1, a[1], a[2]);
  353.             ejectInFloor(list, a[1], a[2]);
  354.             Collections.sort(list);
  355.             int i;
  356.             for (i = 0; i < park[a[0]][a[1]][a[2]].size(); i++){
  357.                 if (park[a[0]][a[1]][a[2]].get(i).getCarID().equals(car.getCarID())){
  358.                     park[a[0]][a[1]][a[2]].remove(i);
  359.                     break;
  360.                 }
  361.             }
  362.             Collections.sort(park[a[0]][a[1]][a[2]]);
  363.            
  364.             if (isEmptySpotRealTime(a[0], a[1], a[2]))
  365.                 statusPark[a[0]][a[1]][a[2]] = 'e';
  366.            
  367.             if (isEmptyButOrderedRealTime(a[0], a[1], a[2]))
  368.                 statusPark[a[0]][a[1]][a[2]] = 'o';
  369.            
  370.                
  371.             reEnterCars(list, a[0] - 1, a[1], a[2]);
  372.         }
  373.    
  374.     //------------------------//
  375.    
  376.    
  377.     // FORMAT: <Calculation of converted convenient indexes> with <status in the spot>
  378.         public String generateStatusStringOld(){
  379.             String statusString = "";
  380.             for(int i = 0 ; i < 3; i++){
  381.                 for(int j = 0; j < 3; j++){
  382.                     for(int k = 0; k < this.spotsInRow; k++){
  383.                         int value = i * 3 * this.spotsInRow + j * this.spotsInRow + k;
  384.                         statusString += Integer.toString(value);
  385.                         statusString += this.statusPark[i][j][k];
  386.                     }
  387.                 }
  388.             }
  389.             return statusString;
  390.         }
  391.         public String generateStatusString(){
  392.             JSONArray statuses = new JSONArray();
  393.             //String statusString = "";
  394.             for(int i = 0 ; i < 3; i++){
  395.                 for(int j = 0; j < 3; j++){
  396.                     for(int k = 0; k < this.spotsInRow; k++){
  397.                         JSONObject current = new JSONObject();
  398.                         //System.out.println(i + "," + j + "," + k);
  399.                         try {
  400.                             //current.put("pos", i * 3 * this.spotsInRow + j * this.spotsInRow + k);
  401.                             current.put("i", i);
  402.                             current.put("j", j);
  403.                             current.put("k", k);
  404.                             current.put("status", String.valueOf(this.statusPark[i][j][k]));
  405.                         } catch (JSONException e) {
  406.                             // TODO Auto-generated catch block
  407.                             e.printStackTrace();
  408.                         }
  409.                         statuses.put(current);
  410.                        
  411.                     }
  412.                 }
  413.             }
  414.             //return statusString;
  415.             return statuses.toString();
  416.         }
  417.        
  418.         // FORMAT: <depth index,> <height index,> <width index,> <carID> <entry time of car,>
  419.         // <exit time of car,> <#> <\n> ((EACH LINE DESCRIBES ONE SPOT))
  420.         public String generateDBString(){
  421.             JSONArray spots = new JSONArray();
  422.             int i, j, k, z;
  423.             //String DBString = "";
  424.             for (i = 0; i < 3; i++){
  425.                 for(j = 0; j < 3; j++){
  426.                     for(k = 0; k < this.spotsInRow; k++){
  427.                         for (z = 0; z < park[i][j][k].size(); z++){
  428.                            
  429.                             JSONObject current = new JSONObject();
  430.                             try {
  431.                                 current.put("i", i);
  432.                                 current.put("j", j);
  433.                                 current.put("k", k);
  434.                                 current.put("carID", park[i][j][k].get(z).getCarID());
  435.                                 current.put("entryTime", park[i][j][k].get(z).getEntryTime());
  436.                                 current.put("exitTime", park[i][j][k].get(z).getExitTime());
  437.                                 spots.put(current);
  438.                             }catch(Exception e) {
  439.                                 e.printStackTrace();
  440.                             }
  441.  
  442.                         }
  443.                     }
  444.                 }
  445.             }
  446.             //return DBString;
  447.             return spots.toString();
  448.         }
  449.        
  450.    
  451.    
  452.    
  453.     public static void main(String args[]) {
  454.         Algorithm alg = new Algorithm(4);
  455.        
  456.         alg.insertCar(new Car("cesc", 2l, 9l));
  457.         alg.insertCar(new Car("roare", 9l, 11l));
  458.         alg.insertCar(new Car("roland", 11l, 12l));
  459.         alg.insertCar(new Car("obo", 13l, 16l));
  460.         alg.insertCar(new Car("sakho", 7l, 11l));
  461.         alg.insertCar(new Car("miki", 6l, 8l));
  462.        
  463.         int[] a = alg.locateCarSpot("cesc");
  464.         System.out.println("car: " + a[0] + "," + a[1] + ","+a[2]);
  465.        
  466.         a = alg.locateCarSpot("roare");
  467.         System.out.println("car: " + a[0] + "," + a[1] + ","+a[2]);
  468.        
  469.          System.out.println(alg.generateStatusString());
  470.          System.out.println(alg.generateDBString());
  471.          
  472.          System.out.println("nnn" + alg.statusPark[0][0][0]);
  473.          
  474.          System.out.println(alg.park[0][0][0].get(0).getCarID());
  475.          System.out.println(alg.park[0][0][0].get(1).getCarID());
  476.          
  477.     }
  478.    
  479. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement