Advertisement
Guest User

Untitled

a guest
Nov 28th, 2015
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.77 KB | None | 0 0
  1. import java.awt.List;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.lang.reflect.Array;
  10. import java.math.RoundingMode;
  11. import java.security.KeyStore.Entry;
  12. import java.text.DecimalFormat;
  13. import java.util.ArrayList;
  14. import java.util.Collection;
  15. import java.util.Collections;
  16. import java.util.Comparator;
  17. import java.util.LinkedList;
  18. import java.util.Map;
  19. import java.util.Map;
  20. import java.util.SortedMap;
  21. import java.util.TreeMap;
  22. import java.util.concurrent.BrokenBarrierException;
  23. import java.util.concurrent.ConcurrentHashMap;
  24. import java.util.concurrent.CountDownLatch;
  25. import java.util.concurrent.CyclicBarrier;
  26. import java.util.concurrent.ExecutorService;
  27. import java.util.concurrent.Executors;
  28.  
  29. import javax.swing.text.html.HTMLDocument.Iterator;
  30.  
  31. /**
  32.  * Clasa ce reprezinta o solutie partiala pentru problema de rezolvat. Aceste
  33.  * solutii partiale constituie task-uri care sunt introduse in workpool.
  34.  */
  35. class PartialSolution {
  36.     // ...
  37. }
  38.  
  39. /**
  40.  * Clasa ce reprezinta un thread worker.
  41.  */
  42. class WorkerMap extends Thread {
  43.     WorkPool wp;
  44.     String docName;
  45.     int start;
  46.     ConcurrentHashMap<Integer, Integer> hmap;
  47.     ArrayList<String> maxWords;
  48.    
  49.     public WorkerMap(WorkPool workpool, String doc, int ofst) {
  50.         this.wp = workpool;
  51.         docName = new String(doc);
  52.         start = ofst;
  53.         hmap = new ConcurrentHashMap<Integer, Integer>();
  54.         maxWords = new ArrayList<String>();
  55.     }
  56.  
  57.     /**
  58.      * Procesarea unei solutii partiale. Aceasta poate implica generarea unor
  59.      * noi solutii partiale care se adauga in workpool folosind putWork().
  60.      * Daca s-a ajuns la o solutie finala, aceasta va fi afisata.
  61.      * @throws IOException
  62.      * @throws BrokenBarrierException
  63.      * @throws InterruptedException
  64.      */
  65.     void processPartialSolution(PartialSolution ps) throws IOException, InterruptedException, BrokenBarrierException {
  66.         BufferedReader br = new BufferedReader(new FileReader(docName));
  67.         int end = start + ReplicatedWorkers.chunkSize;
  68.         File f = new File(docName);
  69.         int fileLen = (int) f.length();
  70.         end = Math.min(fileLen, end);
  71.         char c[] = new char[1];
  72.         br.mark(1000 + end);
  73.         br.skip(start);
  74.         br.read(c, 0, 1);
  75.         br.reset();
  76.         if (start != 0 && (ReplicatedWorkers.CheckDelim(c[0]) == false))
  77.         {
  78.             br.mark(1000 + end);
  79.             br.skip(start - 1);
  80.             br.read(c, 0, 1);
  81.             br.reset();
  82.             if (ReplicatedWorkers.CheckDelim(c[0]) == true)
  83.             {
  84.                
  85.             }
  86.             else while (start < end && (ReplicatedWorkers.CheckDelim(c[0]) == false))
  87.             {
  88.                 start++;
  89.                 br.mark(1000 + end);
  90.                 br.skip(start);
  91.                 br.read(c, 0, 1);
  92.                 br.reset();
  93.             }
  94.         }
  95.         br.mark(1000 + end);
  96.         br.skip(end - 1);
  97.         br.read(c, 0, 1);
  98.         br.reset();
  99.         while (ReplicatedWorkers.CheckDelim(c[0]) == true)
  100.         {
  101.             end++;
  102.             br.mark(1000 + end);
  103.             br.skip(end - 1);
  104.             int readInvalid = br.read(c, 0, 1);
  105.             br.reset();
  106.             if(readInvalid == -1)
  107.             {
  108.                 end--;
  109.                 break;
  110.             }
  111.         }
  112.         c = new char[end - start];
  113.     //  System.out.println(c);
  114.         br.mark(1000 + end);
  115.         br.skip(start);
  116.         br.read(c, 0, end - start);
  117.         br.reset();
  118.         String s = new String();
  119.         int dim = 0;
  120.         String[] words = new String[end - start];
  121.         for (int i = 0; i < c.length; i++)
  122.         {
  123.             if (ReplicatedWorkers.CheckDelim(c[i]))
  124.             {
  125.                 if (s.length() != 0)
  126.                 {
  127.                     words[dim] = s;
  128.                     dim++;
  129.                 }
  130.                 s = new String();
  131.             }
  132.             else
  133.             {
  134.                 s += c[i];
  135.             }
  136.         }
  137.         words[dim] = s;
  138.         dim++;
  139.         int maxLen = -1;
  140.         for (int i = 0; i < dim; i++)
  141.         {
  142.             System.out.println(words[i]);
  143.             int len = words[i].length();
  144.             if (maxLen < len)
  145.                 maxLen = len;
  146.             if (hmap.containsKey(len))
  147.             {
  148.                 hmap.put(len, hmap.get(len) + 1);
  149.             }
  150.             else
  151.             {
  152.                 hmap.put(len, 1);
  153.             }
  154.         }
  155.        
  156.         for (int i = 0; i < dim; i++)
  157.         {
  158.             if (words[i].length() == maxLen)
  159.                 maxWords.add(words[i]);
  160.         }
  161.        
  162.         ConcurrentHashMap<String, ArrayList<String>> maxWordsMap = ReplicatedWorkers.maxWords;
  163.        
  164.         synchronized (ReplicatedWorkers.maxWords)
  165.         {
  166.             if (maxWordsMap.containsKey(docName))
  167.             {
  168.                 ArrayList<String> aux = maxWordsMap.get(docName);
  169.                 aux.addAll(maxWords);
  170.                 maxWordsMap.put(docName, aux);
  171.             }
  172.             else
  173.             {
  174.                 maxWordsMap.put(docName, maxWords);
  175.             }
  176.         }
  177.        
  178.         synchronized (ReplicatedWorkers.results)
  179.         {
  180.             if (!ReplicatedWorkers.results.containsKey(docName))
  181.             {
  182.                 ArrayList<ConcurrentHashMap<Integer, Integer>> res = new ArrayList<ConcurrentHashMap<Integer, Integer>>();
  183.                 res.add(hmap);
  184.                 ReplicatedWorkers.results.put(docName, res);
  185.             }  
  186.             else
  187.             {
  188.                 ArrayList<ConcurrentHashMap<Integer, Integer>> res = ReplicatedWorkers.results.get(docName);
  189.                 res.add(hmap);
  190.                 ReplicatedWorkers.results.put(docName, res);
  191.             }
  192.         }
  193.     }
  194.    
  195.     public void run() {
  196.         PartialSolution ps = wp.getWork();
  197.         if (ps == null)
  198.         {
  199.             ReplicatedWorkers.doneSignal.countDown();
  200.             return;
  201.         }
  202.         try {
  203.             processPartialSolution(ps);
  204.         } catch (IOException e) {
  205.             e.printStackTrace();
  206.         } catch (InterruptedException e) {
  207.             e.printStackTrace();
  208.         } catch (BrokenBarrierException e) {
  209.             e.printStackTrace();
  210.         }
  211.         ReplicatedWorkers.doneSignal.countDown();
  212.     }
  213.  
  214.    
  215. }
  216.  
  217.  
  218. class WorkerReduce extends Thread {
  219.     WorkPool wp;
  220.     String docName;
  221.     double rank;
  222.    
  223.     private int fib(int n)
  224.     {
  225.         int p = 0;
  226.         int c = 1;
  227.         int r = 0; // The result is initialized to 0 (undefined).
  228.         for (int i = 0; i < n; i++)
  229.         {
  230.             r = p + c; // Produce next number in the sequence.
  231.             p = c;     // Save previous number.
  232.             c = r;     // Save current number.
  233.         }
  234.  
  235.         return r;
  236.     }
  237.    
  238.     public WorkerReduce(WorkPool workpool, String doc) {
  239.         this.wp = workpool;
  240.         docName = doc;
  241.     }
  242.             /**
  243.      * Procesarea unei solutii partiale. Aceasta poate implica generarea unor
  244.      * noi solutii partiale care se adauga in workpool folosind putWork().
  245.      * Daca s-a ajuns la o solutie finala, aceasta va fi afisata.
  246.      * @throws IOException
  247.              * @throws BrokenBarrierException
  248.              * @throws InterruptedException
  249.      */
  250.     void processPartialSolution(PartialSolution ps) throws IOException, InterruptedException, BrokenBarrierException {
  251.  
  252.         ConcurrentHashMap<String, ArrayList<ConcurrentHashMap<Integer, Integer>>> results =
  253.                 ReplicatedWorkers.results;
  254.         ConcurrentHashMap<Integer, Integer> reduceResult =
  255.                 new ConcurrentHashMap<Integer, Integer>();
  256.         ArrayList<ConcurrentHashMap<Integer, Integer>> hmapList = results.get(docName);
  257.         synchronized (ReplicatedWorkers.results)
  258.         {
  259.             for (int i = 0; i < results.get(docName).size(); i++)
  260.             {
  261.                 for (Map.Entry<Integer, Integer> e : results.get(docName).get(i).entrySet())
  262.                 {
  263.                     if (e.getKey() == 0)
  264.                         continue;
  265.                     synchronized(reduceResult)
  266.                     {
  267.                         if (reduceResult.containsKey(e.getKey()))
  268.                         {
  269.                             reduceResult.put(e.getKey(), e.getValue() + reduceResult.get(e.getKey()));
  270.                         }
  271.                         else
  272.                         {
  273.                             reduceResult.put(e.getKey(), e.getValue());
  274.                         }
  275.                     }
  276.                 }
  277.             }
  278.         }      
  279.         ArrayList<String> maxWords = new ArrayList<String>();
  280.         ArrayList<String> maxWordsFromMap = ReplicatedWorkers.maxWords.get(docName);
  281.         int maxLen = -1;
  282.         synchronized (ReplicatedWorkers.maxWords) {
  283.             for (int i = 0; i < maxWordsFromMap.size(); i++)
  284.             {
  285.                 if (maxWordsFromMap.get(i).length() > maxLen)
  286.                     maxLen = maxWordsFromMap.get(i).length();
  287.             }
  288.            
  289.             for (int i = 0; i < maxWordsFromMap.size(); i++)
  290.             {
  291.                 if (maxWordsFromMap.get(i).length() == maxLen)
  292.                     maxWords.add(maxWordsFromMap.get(i));
  293.             }
  294.         }
  295.         double numWords = 0;
  296.         rank = 0;
  297.         for (Map.Entry<Integer, Integer> e : reduceResult.entrySet())
  298.         {  
  299.             numWords += e.getValue();
  300.             rank += fib(e.getKey()) * e.getValue();
  301.         }
  302.         rank /= numWords;
  303.        
  304.  
  305.         ArrayList<String> str = new ArrayList<String>();
  306.         for (int i = 0; i < maxWords.size(); i++)
  307.         {
  308.             boolean add = true;
  309.             for (int j = 0; j < str.size(); j++)
  310.             {
  311.                 if (str.get(j).equals(maxWords.get(i)))
  312.                 {
  313.                     add = false;
  314.                     break;
  315.                 }
  316.                
  317.             }
  318.             if (add)
  319.             {
  320.                 str.add(maxWords.get(i));
  321.             }
  322.         }
  323.         maxWords = str;
  324.  
  325.         synchronized (ReplicatedWorkers.ranks)
  326.         {  
  327.             ReplicatedWorkers.ranks.put(docName, rank);
  328.         }
  329.         synchronized (ReplicatedWorkers.maxWordsEnd)
  330.         {
  331.             ReplicatedWorkers.maxWordsEnd.put(docName, maxWords);
  332.         }
  333.     }
  334.    
  335.     public void run() {
  336.         PartialSolution ps = wp.getWork();
  337.        
  338.         if (ps == null)
  339.         {
  340.             ReplicatedWorkers.doneSignal.countDown();
  341.             return;
  342.         }
  343.         try {
  344.             processPartialSolution(ps);
  345.         } catch (IOException e) {
  346.             e.printStackTrace();
  347.         } catch (InterruptedException e) {
  348.             e.printStackTrace();
  349.         } catch (BrokenBarrierException e) {
  350.             e.printStackTrace();
  351.         }
  352.         ReplicatedWorkers.doneSignal.countDown();
  353.     }
  354.  
  355.    
  356. }
  357.  
  358. class Pair implements Comparable<Object>
  359. {
  360.     Double v1;
  361.     String v2;
  362.    
  363.     Pair(double d, String s)
  364.     {
  365.         v1 = new Double(d);
  366.         v2 = new String(s);
  367.     }
  368.  
  369.     @Override
  370.     public int compareTo(Object arg0) {
  371.         Pair p = (Pair)arg0;
  372.         if (Math.abs(v1 - p.v1) < 0.01)
  373.         {
  374.             if (v2.equals(p.v2))
  375.                 return 0;
  376.            
  377.             String[] docs = ReplicatedWorkers.docs;
  378.             int i1 = 0, i2 = 0;
  379.             for (int i = 0; i < docs.length; i++)
  380.             {
  381.                 if (docs[i].equals(v2))
  382.                     i1 = i;
  383.                 if (docs[i].equals(p.v2))
  384.                     i2 = i;
  385.             }
  386.            
  387.             if (i1 > i2)
  388.                 return 1;
  389.             else return -1;
  390.            
  391.         }
  392.         else
  393.         {
  394.             if (v1 > p.v1)
  395.                 return -1;
  396.             else return 1;
  397.         }
  398.     }
  399.    
  400.    
  401. }
  402.  
  403. public class ReplicatedWorkers {
  404.  
  405.     static BufferedReader br;
  406.     static int chunkSize;
  407.     static String[] docs;
  408.     static int numDocs;
  409.     static ConcurrentHashMap<String, ArrayList<ConcurrentHashMap<Integer, Integer>>> results;
  410.     static ConcurrentHashMap<String, ArrayList<String>> maxWords;
  411.     static ConcurrentHashMap<String, Double> ranks;
  412.     static ConcurrentHashMap<String, ArrayList<String>> maxWordsEnd;
  413.     static int count = 0;
  414.     static int activeThreads = 0;
  415.     static String delim;
  416.     static CountDownLatch doneSignal;
  417.    
  418.     static boolean CheckDelim(char c)
  419.     {
  420.         for (int i = 0; i < delim.length(); i++)
  421.         {
  422.             if (c == delim.charAt(i))
  423.             {
  424.                 return true;
  425.             }
  426.         }
  427.         return false;
  428.     }
  429.    
  430.     public static void main(String args[]) throws NumberFormatException, IOException, InterruptedException {
  431.         DecimalFormat df = new DecimalFormat("#.00");
  432.         df.setRoundingMode(RoundingMode.DOWN);
  433.         int numThreads = Integer.parseInt(args[0]);
  434.         br = new BufferedReader(new FileReader(args[1]));
  435.         ranks = new ConcurrentHashMap<String, Double>();
  436.         maxWordsEnd = new ConcurrentHashMap<String, ArrayList<String>>();
  437.         maxWords = new ConcurrentHashMap<String, ArrayList<String>>();
  438.         chunkSize = Integer.parseInt(br.readLine());
  439.         numDocs = Integer.parseInt(br.readLine());
  440.         docs = new String[numDocs];
  441.         for (int i = 0; i < numDocs; i++)
  442.             docs[i] = br.readLine();
  443.         delim = new String(";:/?~.,><~`[]{}()!@#$%^&-_+'=*|");
  444.         delim += '"';
  445.         delim += ' ';
  446.         delim += '\n';
  447.         delim += '\r';
  448.         delim += '\t';
  449.        
  450.         results = new ConcurrentHashMap<String, ArrayList<ConcurrentHashMap<Integer, Integer>>>();
  451.         BufferedWriter wr = new BufferedWriter(new FileWriter(args[2]));
  452.         WorkPool wpMap = new WorkPool(numThreads);
  453.         WorkPool wpReduce = new WorkPool(numThreads);
  454.         ArrayList<Thread> mapThds = new ArrayList<Thread>();
  455.         ArrayList<Thread> reduceThds = new ArrayList<Thread>();
  456.         ExecutorService ex = Executors.newFixedThreadPool(numThreads);
  457.         for (int i = 0; i < docs.length; i++)
  458.         {
  459.             File f = new File(docs[i]);
  460.             int len = (int) f.length();
  461.             for (int j = 0; j < len / chunkSize; j++)
  462.             {  
  463.                 count++;
  464.             }
  465.             if (len % chunkSize != 0)
  466.             {
  467.                 count++;
  468.             }
  469.         }
  470.         doneSignal = new CountDownLatch(count);
  471.         for (int i = 0; i < docs.length; i++)
  472.         {
  473.             File f = new File(docs[i]);
  474.             int len = (int) f.length();
  475.             for (int j = 0; j < len / chunkSize; j++)
  476.             {  
  477.                 count++;
  478.                 wpMap.putWork(new PartialSolution());
  479.                 //mapThds.add(new WorkerMap(wpMap, docs[i], j * chunkSize));
  480.                 ex.execute(new WorkerMap(wpMap, docs[i], j * chunkSize));
  481.             }
  482.             if (len % chunkSize != 0)
  483.             {
  484.                 count++;
  485.                 wpMap.putWork(new PartialSolution());
  486.                 //mapThds.add(new WorkerMap(wpMap, docs[i], chunkSize * (len / chunkSize)));
  487.                 ex.execute(new WorkerMap(wpMap, docs[i], chunkSize * (len / chunkSize)));
  488.             }
  489.         }
  490.         doneSignal.await();
  491.         /*for (int i = 0; i < mapThds.size(); i++)
  492.         {
  493.             mapThds.get(i).start();
  494.         }
  495.         for (int i = 0; i < mapThds.size(); i++)
  496.         {
  497.             mapThds.get(i).join();
  498.         }*/
  499. /*      System.out.println(1);
  500.        
  501.         while (count > 0)
  502.         {
  503.             System.out.println(count);
  504.         }*/
  505.         count = 0;
  506.         System.out.println(3);
  507.         ex.shutdown();
  508.         ExecutorService ex2 = Executors.newFixedThreadPool(numThreads);
  509.         doneSignal = new CountDownLatch(docs.length);
  510.         for (int i = 0; i < docs.length; i++)
  511.         {
  512.             count++;
  513.             wpReduce.putWork(new PartialSolution());
  514.             //reduceThds.add(new WorkerReduce(wpReduce, docs[i]));
  515.             ex2.execute(new WorkerReduce(wpReduce, docs[i]));
  516.         }
  517.         /*for (int i = 0; i < reduceThds.size(); i++)
  518.         {
  519.                 reduceThds.get(i).start();
  520.         }
  521.         for (int i = 0; i < reduceThds.size(); i++)
  522.         {
  523.             reduceThds.get(i).join();
  524.         }*/
  525.         doneSignal.await();
  526.         ex2.shutdown();
  527.        
  528.         ArrayList<Pair> sortedFiles = new ArrayList<Pair>();
  529.         for (Map.Entry<String, Double> e : ranks.entrySet())
  530.         {
  531.             sortedFiles.add(new Pair(e.getValue(), e.getKey()));
  532.         }
  533.        
  534.         Collections.sort(sortedFiles);
  535.        
  536.         for (int i = 0; i < sortedFiles.size(); i++)
  537.         {
  538.             String s = new String();
  539.  
  540.             String docName = sortedFiles.get(i).v2;
  541.             s += docName;
  542.             s += ';';  
  543.             s += df.format(sortedFiles.get(i).v1);
  544.             s += ';';
  545.             s = s + '[' + new Integer(maxWordsEnd.get(docName).get(0).length()).toString() + ','
  546.                     + new Integer(maxWordsEnd.get(docName).size()) + ']' + '\n';
  547.             wr.write(s, 0, s.length());
  548.            
  549.         }
  550.         wr.close();
  551.        
  552.     }
  553. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement