Example #1
0
  private static void getTopDocuments(int num, HashMap<String, Float> scoremap, String filename)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(filename);
    Iterator<String> itr = scoremap.keySet().iterator();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<Float> scores = new ArrayList<Float>();

    while (itr.hasNext()) {
      String key = itr.next();
      if (scores.size() < num) {
        scores.add(scoremap.get(key));
        urls.add(key);
      } else {
        int index = scores.indexOf(Collections.min(scores));
        if (scores.get(index) < scoremap.get(key)) {
          scores.set(index, scoremap.get(key));
          urls.set(index, key);
        }
      }
    }

    while (scores.size() > 0) {
      int index = scores.indexOf(Collections.max(scores));
      out.println(urls.get(index) + "\t" + scores.get(index));
      urls.remove(index);
      scores.remove(index);
    }
    out.close();
  }
Example #2
0
     public void sortFrontbyR(){
    
        sortByR = new ArrayList();
    
        for (int i = 0 ; i < Fronts.size() ; i++){
            
       
            ArrayList tempfront = (ArrayList) Fronts.get(i);
			
			for (int j = 0 ; j < tempfront.size() ; j++){
				
				for (int a = 0 ; a <  tempfront.size() ; a++){
			
					if (a > j){
						
						NSGAII.Solutions.QRTPSolution.OneSolution first = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(j);
						double x  = first.getRecall();
						NSGAII.Solutions.QRTPSolution.OneSolution second = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(a);
						double y  = second.getRecall();
						
						if (y > x){
						
							tempfront.set(j, second);
							tempfront.set(a, first);
						
						}else{}
					}        
				}      
			}   
			
			sortByR.add(tempfront);
		}
    

    }
Example #3
0
  // Executes the given action
  public void executeAction(Action a) {

    // For each state variable, retrieve the DD for it, evaluate it
    // w.r.t. the current state and build a new state.
    ArrayList new_state = new ArrayList();
    int c;
    for (c = 0; c < (_nVars << 1); c++) {
      new_state.add("-");
    }
    for (c = 0; c < (_nVars << 1); c++) {
      Object cur_assign = _state.get(c);
      if (cur_assign instanceof Boolean) {
        // System.out.println(a._tmID2DD);
        int nonprime_id = c + 1;
        int prime_id = nonprime_id - _nVars;
        Object DD = a._tmID2DD.get(new Integer(prime_id));
        _state.set(prime_id - 1, TRUE);
        double p_true = _mdp._context.evaluate(DD, _state);
        // System.out.println("ID: " + nonprime_id + ", " + prime_id + ": " +
        //		   _mdp._context.printNode(DD) + " -> " +
        //		   _mdp._df.format(p_true));
        new_state.set(c, (_r.nextFloat() < p_true) ? TRUE : FALSE);
      }
    }

    _state = new_state;
  }
Example #4
0
  public String toString(Molecule molecule) {
    // write header
    String returnString =
        String.format(
            "%%mem=%dGB\n%%nprocshared=%d\n#p geom=connect %s/genecp empiricaldispersion=gd3bj opt\n",
            mem, nprocshared, method);
    returnString += "\ntitle\n\n0 1\n";

    // write geometry
    returnString = returnString + molecule.getGJFstring() + "\n";

    // initialize some variables
    Atom fromAtom = null;
    Atom toAtom = null;
    Integer fromAtomNumber = 0;
    Integer toAtomNumber = 0;
    Double bondOrder = 0.0;
    DefaultWeightedEdge thisEdge = null;

    // read connectivity data into parallel arrays
    ArrayList<Integer> fromAtoms = new ArrayList<Integer>();
    ArrayList<Integer> toAtoms = new ArrayList<Integer>();
    ArrayList<Double> bondOrders = new ArrayList<Double>();
    ArrayList<Boolean> visited = new ArrayList<Boolean>();
    for (DefaultWeightedEdge e : molecule.connectivity.edgeSet()) {
      fromAtom = molecule.connectivity.getEdgeSource(e);
      fromAtomNumber = molecule.contents.indexOf(fromAtom) + 1;
      toAtom = molecule.connectivity.getEdgeTarget(e);
      toAtomNumber = molecule.contents.indexOf(toAtom) + 1;
      bondOrder = molecule.connectivity.getEdgeWeight(e);

      fromAtoms.add(fromAtomNumber);
      toAtoms.add(toAtomNumber);
      bondOrders.add(bondOrder);
      visited.add(false);
    }

    // write connectivity data
    for (int i = 0; i < molecule.contents.size(); i++) {
      returnString = returnString + (i + 1) + " ";
      for (int j = 0; j < fromAtoms.size(); j++) {
        if (fromAtoms.get(j) == i + 1 && visited.get(j) == false) {
          returnString =
              returnString + toAtoms.get(j) + " " + String.format("%.1f ", bondOrders.get(j));
          visited.set(j, true);
        }
        if (toAtoms.get(j) == i + 1 && visited.get(j) == false) {
          returnString =
              returnString + fromAtoms.get(j) + " " + String.format("%.1f ", bondOrders.get(j));
          visited.set(j, true);
        }
      }
      returnString = returnString + "\n";
    }

    // write footer
    returnString += String.format("\n@%s\n\n", basis);
    return returnString;
  }
Example #5
0
 static void shuffle(ArrayList keys) {
   int size = keys.size();
   for (int i = size; i > 1; i--) {
     int r = rng.nextInt(i);
     Object t = keys.get(i - 1);
     keys.set(i - 1, keys.get(r));
     keys.set(r, t);
   }
 }
Example #6
0
 public static ArrayList<Card> bubblesort(ArrayList<Card> cards) {
   for (int i = 1; i < cards.size(); i++) {
     for (int j = 0; j < cards.size() - 1; j++) {
       // comparing cards by rank
       if (cards.get(j).getRank() > cards.get(j + 1).getRank()) {
         Card tempcard = cards.get(j);
         cards.set(j, cards.get(j + 1));
         cards.set(j + 1, tempcard);
       }
     }
   }
   return cards;
 }
 public static void madLibber(Scanner inputText) {
   ArrayList<String> paragraph = new ArrayList<>();
   while (inputText.hasNextLine()) {
     paragraph.add(inputText.nextLine());
   }
   int index1 = 0;
   int index2 = 0;
   String word;
   String userWord;
   for (int i = 0; i < paragraph.size(); i++) {
     while (paragraph.get(i).indexOf("[") != -1) {
       index1 = paragraph.get(i).indexOf("[");
       index2 = paragraph.get(i).indexOf("]");
       word = paragraph.get(i).substring(index1 + 1, index2);
       System.out.print("Pick a(n) " + word + ":");
       userWord = input.next();
       paragraph.set(
           i,
           paragraph.get(i).substring(0, index1)
               + userWord
               + paragraph.get(i).substring(index2 + 1));
     }
     index1 = 0;
     index2 = 0;
   }
   System.out.println("\n---\n");
   for (int i = 0; i < paragraph.size(); i++) {
     System.out.println(paragraph.get(i));
   }
 }
Example #8
0
 public static void main(String[] args) throws IOException {
   // Use BufferedReader rather than RandomAccessFile; it's much faster
   BufferedReader f = new BufferedReader(new FileReader("badrand.in"));
   // input file name goes above
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("badrand.out")));
   // Use StringTokenizer vs. readLine/split -- lots faster
   StringTokenizer st = new StringTokenizer(f.readLine());
   // Get line, break into tokens
   int i1 = Integer.parseInt(st.nextToken()); // first integer
   ArrayList squares = new ArrayList<Integer>(10000);
   int mark = 0;
   i1 = middleSquare(i1);
   while (i1 > 0) {
     if (squares.contains(i1)) {
       squares.add(i1);
       squares.set(squares.indexOf(i1), 10000);
       mark = i1;
       i1 = 0;
     } else {
       squares.add(i1);
       i1 = middleSquare(i1);
     }
   }
   squares.add(10000);
   squares.add(0);
   out.println(squares.indexOf(mark) + 1);
   out.close(); // close the output file
   System.exit(0); // don't omit this!
 }
Example #9
0
  public static void qsHelp(int lo, int hi, ArrayList<Book> d) {

    if (lo >= hi) return;

    int tmpLo = lo;
    int tmpHi = hi;
    Book pivot = d.get(lo);

    while (tmpLo < tmpHi) {
      // first, slide markers in as far as possible without swaps
      while (d.get(tmpLo).compareTo(pivot) < 0) {
        // System.out.println("2");
        tmpLo++;
      }
      while (d.get(tmpHi).compareTo(pivot) > 0) {
        // System.out.println("3");
        tmpHi--;
      }

      swap(tmpLo, tmpHi, d);
    }

    // pivot has been floating around... plant it where it belongs
    d.set(tmpLo, pivot);

    // recurse on lower and upper ranges
    qsHelp(lo, tmpLo - 1, d);
    qsHelp(tmpLo + 1, hi, d);
  } // end qsHelp
Example #10
0
 public void drawOrbits(ArrayList alObjectsArchive) {
   //  println("SIZE:" + alObjectsArchive.size());
   //  ArrayList alObjectsArchive = timeline.getObjectStateArchive();
   ArrayList alPrevPos = new ArrayList();
   ArrayList alColors = new ArrayList();
   alColors.add(color(255, 0, 0));
   alColors.add(color(255, 255, 0));
   alColors.add(color(255, 0, 255));
   //  for (int i = timeline.getTimeIdx(); i >= 0 && i > (timeline.getTimeIdx() - 1 - 100); i--)
   for (int i = 0; i < alObjectsArchive.size(); i++) {
     ArrayList objects = (ArrayList) alObjectsArchive.get(i);
     for (int j = 0; j < objects.size(); j++) {
       CelestialObject obj = (CelestialObject) objects.get(j);
       //      CelestialObject obj = (CelestialObject)objects.get(1);
       PVector pos = obj.getPosition();
       //      stroke(0, 0, 255);
       stroke((Integer) alColors.get(j));
       if (alPrevPos.size() == objects.size()) {
         PVector prevPos = (PVector) alPrevPos.get(j);
         line(prevPos.x, prevPos.y, pos.x, pos.y);
         alPrevPos.set(j, pos);
       } else alPrevPos.add(pos);
     }
   }
 }
Example #11
0
  private void fixTabs(int tabSize) {

    int rowIndex = 0;

    for (StringBuilder row1 : rows) {
      String row = row1.toString();
      StringBuilder newRow = new StringBuilder();

      char[] chars = row.toCharArray();
      for (char c : chars) {
        if (c == '\t') {
          int spacesLeft = tabSize - newRow.length() % tabSize;
          if (DEBUG) {
            System.out.println("Found tab. Spaces left: " + spacesLeft);
          }
          String spaces = StringUtils.repeatString(" ", spacesLeft);
          newRow.append(spaces);
        } else {
          String character = Character.toString(c);
          newRow.append(character);
        }
      }
      rows.set(rowIndex, newRow);
      rowIndex++;
    }
  }
Example #12
0
    @Override
    public void reduce(Text key, Iterable<Text> values, Context context)
        throws IOException, InterruptedException {
      Hashtable<String, Integer> wordCounts = new Hashtable<String, Integer>();
      ArrayList docName = new ArrayList<String>();
      LinkedList wordName = new LinkedList<String>();
      while (values.iterator().hasNext()) {
        String[] items = values.iterator().next().toString().split("@");
        if (!wordName.contains(items[0])) {
          wordName.add(items[0]);
        }
        String[] keys = items[1].split(":|,");
        for (int i = 0; i < keys.length; i += 2) {
          if (!docName.contains(keys[i])) {
            docName.add(keys[i]);
            wordCounts.put(keys[i], 0);
          }
          int tmp = wordCounts.get(keys[i]);
          tmp += Integer.parseInt(keys[i + 1]);
          wordCounts.put(keys[i], tmp);
        }
      }

      for (int i = 0; i < docName.size() - 1; ++i) {
        for (int j = i + 1; j < docName.size(); ++j) {
          if (wordCounts.get(docName.get(i)) < wordCounts.get(docName.get(j))) {
            String stmp = docName.get(i).toString();
            docName.set(i, docName.get(j).toString());
            docName.set(j, stmp);
          }
        }
      }

      String retKey = wordName.get(0).toString();
      for (int i = 1; i < wordName.size(); ++i) {
        retKey += "," + wordName.get(i);
      }

      String retValue =
          ""; // ="\n" + docName.get(0).toString() + ":" +
              // wordCounts.get(docName.get(0).toString());
      for (int i = 0; i < docName.size(); ++i) {
        retValue +=
            "\n" + docName.get(i).toString() + ": " + wordCounts.get(docName.get(i).toString());
      }
      context.write(new Text(retKey), new Text(retValue));
    }
Example #13
0
  // Derives QFunctions for the given value function and simulates the
  // greedy policy for the given number of trials and steps per trial.
  // Returns final value of every trial.
  public ArrayList simulate(int trials, int steps, long rand_seed) {
    ArrayList values = new ArrayList();
    _r = new Random(rand_seed);

    for (int trial = 1; trial <= trials; trial++) {

      System.out.println("\n -----------\n   Trial " + trial + "\n -----------");

      // Initialize state
      _state = new ArrayList();
      _nVars = _mdp._alVars.size();
      for (int c = 0; c < (_nVars << 1); c++) {
        _state.add("-");
      }
      Iterator i = _mdp._alVars.iterator();
      _vars = new TreeSet();
      while (i.hasNext()) {
        String s = (String) i.next();
        if (!s.endsWith("\'")) {
          Integer gid = (Integer) _mdp._tmVar2ID.get(s);
          _vars.add(gid);

          // Note: assign level (level is gid-1 b/c gids in order)
          _state.set(gid.intValue() - 1, _r.nextBoolean() ? TRUE : FALSE);
        }
      }
      // System.out.println(_mdp._context.printNode(_mdp._valueDD) + "\n" + _state);
      double reward = _mdp._context.evaluate(_mdp._rewardDD, _state);
      System.out.print(" " + PrintState(_state) + "  " + MDP._df.format(reward));

      // Run steps
      for (int step = 1; step <= steps; step++) {

        // Get action
        Action a;
        if (_bUseBasis) {
          a = getBasisAction();
        } else {
          a = getAction();
        }

        // Execute action
        executeAction(a);

        // Update reward
        reward =
            (_mdp._bdDiscount.doubleValue() * reward)
                + _mdp._context.evaluate(_mdp._rewardDD, _state);

        System.out.println(", a=" + a._sName);
        System.out.print(
            " " + PrintState(_state) + "  " + MDP._df.format(reward) + ": " + "Step " + step);
      }
      values.add(new Double(reward));
      System.out.println();
    }

    return values;
  }
Example #14
0
 public Object set(int index, Object e) {
   Object old = get(index);
   if (index < 0 || index >= size()) add(index, e);
   else {
     if (type != null) e = Converter.convert(e, type);
     super.set(index, e);
   }
   return old;
 }
Example #15
0
  public void mergeVertex() {
    int[] edge = pickEdge();
    int v = edge[0];
    int u = edge[1];

    // attach u's list to v
    for (int i = 0; i < adjlist.get(u).size(); i++) {
      adjlist.get(v).add(adjlist.get(u).get(i));
    }

    // scan u's neighbor's list and replace u to v
    ArrayList<Integer> uNeighbor = adjlist.get(u);
    for (int i = 0; i < uNeighbor.size(); i++) {
      // get neighbor's vertex #
      int n = uNeighbor.get(i);

      // get neighbor's list
      ArrayList<Integer> nlist = adjlist.get(n);

      // replace u to v
      for (int j = 0; j < nlist.size(); j++) {
        if (nlist.get(j).equals(u)) {
          nlist.set(j, v);
        }
      }
    }

    // test
    //		System.out.print("v's list before remove self loop: ");
    //		Iterator<Integer> it = adjlist.get(v).iterator();
    //		while (it.hasNext()){
    //			System.out.print(it.next() + " ");
    //		}
    //		System.out.println("");

    // remove self loop in v's list
    ArrayList<Integer> vNeighbor = adjlist.get(v);
    while (vNeighbor.remove((Object) v)) ;

    // test
    //		System.out.print("v's list after removing self loop: ");
    //		it = adjlist.get(v).iterator();
    //		while (it.hasNext()){
    //			System.out.print(it.next() + " ");
    //		}
    //		System.out.println("");

    // remove u's list
    adjlist.remove(u);
    vertices.remove(vertices.indexOf(u));
  }
  /**
   * Traverse TimeML file and mapping TimeML tags to correspondent positions in tmlList
   *
   * @param al1 : the TimeML label list
   * @param al2 : the node counting list
   * @return <none>
   */
  private void mapTags(Node node, ArrayList<String> tmlList, ArrayList<Integer> ncList)
      throws Exception {

    if (!(ncList.size() == tagCollect.size() && tagCollect.size() == textNodeCount.size())) {
      System.err.println(
          "[TimeMLParser]: The lengths of ncList, textNodeCount and tagCollect are not equal.");
      System.err.println("ncList.size() = " + ncList.size());
      System.err.println("tagCollect.size() = " + tagCollect.size());
      System.err.println("textNodeCount.size() = " + textNodeCount.size());
      System.exit(0);
    }

    try {
      for (int i = 0; i < ncList.size(); i++) {

        // If the tag is <NONE>, skip to next tag
        if (tagCollect.get(i).equalsIgnoreCase("<NONE>")) {
          continue;
        } else {
          // Check textNodeCount
          if (textNodeCount.get(i) == 1) {
            tmlList.set(ncList.get(i) - 1, tagCollect.get(i));
          }
          // If the <EVENT> or <TIMEX3> tag shall be labeled on
          // more than one tokens (e.g. the third quarter)
          else {
            for (int d = 0; d < textNodeCount.get(i); d++) {
              tmlList.set(ncList.get(i) - 1 - d, tagCollect.get(i));
            }
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private ArrayList<Integer> findRanges() {
   int rowsPerRange = (int) Math.ceil((grid.size()) / (double) threads);
   ArrayList<Integer> ranges = new ArrayList<Integer>();
   int startRow = 0, endRow = rowsPerRange;
   for (int i = 0; i < threads; i++) {
     ranges.add(startRow);
     ranges.add(endRow);
     startRow = endRow;
     ;
     endRow += rowsPerRange;
   }
   ranges.set(ranges.size() - 1, Math.min(grid.size(), ranges.get(ranges.size() - 1)));
   System.out.println(ranges);
   return ranges;
 }
Example #18
0
  // Fill in weights for specific counting aggregator approaches
  //
  // Basis function 1: Count of computers running
  // Basis function 2: Count of computers running and connected to
  //                   one other running computer
  //
  // Assuming action succeeds... compute next-state value based on action,
  // choose best action.
  public Action getBasisAction() {

    int best_reboot = -1;
    double best_reboot_val = -1d;
    for (int c = 1; c <= _nVars; c++) {
      ArrayList test_state = (ArrayList) _state.clone();
      test_state.set(c - 1 + _nVars, TRUE);
      double test_val = evalBasisState(test_state, W_BASIS_1, W_BASIS_2);
      if (test_val > best_reboot_val) {
        best_reboot_val = test_val;
        best_reboot = c;
      }
    }

    return (Action) _mdp._hmName2Action.get("reboot" + best_reboot);
  }
Example #19
0
 public static void main(String[] args) {
   genFib();
   sc = new Scanner(System.in);
   int T = sc.nextInt();
   while (T-- > 0) {
     readInput();
     msg = new ArrayList<Character>();
     for (int i = 0; i < n; i++) {
       int index = Collections.binarySearch(fib, fibI[i]);
       // System.out.println(i+"->"+index);
       while (msg.size() <= index) msg.add(' ');
       msg.set(index, cipher.charAt(i));
     }
     output();
   }
 }
Example #20
0
 public void replaceHumanColorCodes() {
   int height = getHeight();
   for (int y = 0; y < height; y++) {
     String row = rows.get(y).toString();
     for (String humanCode : humanColorCodes.keySet()) {
       String hexCode = humanColorCodes.get(humanCode);
       if (hexCode != null) {
         humanCode = "c" + humanCode;
         hexCode = "c" + hexCode;
         row = row.replaceAll(humanCode, hexCode);
         rows.set(
             y, new StringBuilder(row)); // TODO: this is not the most efficient way to do this
         row = rows.get(y).toString();
       }
     }
   }
 }
Example #21
0
    public void calculateCrowdingDistanceE(){
    
		for (int i = 0 ; i < sortByE.size() ; i++){
		 
			ArrayList tempfront = (ArrayList)  sortByE.get(i);

		   
			if (tempfront.size() > 2){

				((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(0)).setCrowdingDistanceE(inf);
				 double coverMax =   ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(0)).getEnergy();
				((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(tempfront.size()-1)).setCrowdingDistanceE(inf);
				double coverMin =   ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(tempfront.size()-1)).getEnergy();
				
				for (int j = 1 ; j < tempfront.size()-1 ; j++){
				
					double crowdist =0;
					
					if (coverMax - coverMin == 0){
					
						crowdist = 0;
					}else{
						crowdist = ((((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j-1)).getEnergy())-(((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j+1)).getEnergy()))/
										(coverMax - coverMin);
					}
						 ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).setCrowdingDistanceE(crowdist);
			 
				}
				
			}else{
			
				 for(int j = 0 ; j < tempfront.size() ; j++){
					 
					 ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).setCrowdingDistanceE(inf);
				 }

				   
			} 
			
			sortByE.set(i, tempfront);
		
		}    
    }
Example #22
0
    public void calculateCrowdingDistanceT(){
    
		for (int i = 0 ; i < sortByT.size() ; i++){
		  
			ArrayList tempfront = (ArrayList)sortByT.get(i);
			//System.out.println("This is Front "+i+" with size "+tempfront.size());

		 
			if (tempfront.size() > 2){

				((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(0)).setCrowdingDistanceT(inf);
					 double coverMax =   ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(0)).getTime();
					((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(tempfront.size()-1)).setCrowdingDistanceT(inf);
					double coverMin =   ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(tempfront.size()-1)).getTime();
			
				for (int j = 1 ; j < ((ArrayList)sortByT.get(i)).size()-1 ; j++){
				
					double crowdist =0;
					
					if (coverMax - coverMin == 0){
					
						crowdist = 0;
					}else{
						crowdist = ((((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j-1)).getTime())-(((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j+1)).getTime()))/
										(coverMax - coverMin);
					}
						 ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).setCrowdingDistanceT(crowdist);
						  //System.out.println("Solution "+j+" has crowd. dist lif "+((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).getCrowdingDistanceLifetime());

				}
			}else{

				for (int j = 0 ; j < ((ArrayList)sortByT.get(i)).size() ; j++){
					(NSGAII.Solutions.QRTPSolution.OneSolution) ((ArrayList)sortByT.get(i)).get(j)).setCrowdingDistanceT(inf);
			
				}       
			} 
				
				sortByT.set(i, tempfront);
			
		} 
	}
  public boolean setLoadVal(String[] load) {
    int count = 0;
    try {
      for (int i = 0; i < load_list.size(); i++) {
        if (load_list.get(i)[0].contains(load[0])) {
          load_list.set(i, load);
          return true;
        } else {
          count++;
        }
      }
    } catch (Exception e) {
    }

    load_list.add(count, load);
    System.out.println(
        "RAWR " + count + " " + load_list.get(count)[0] + " " + load_list.get(count)[1]);
    // load_list.set(count,load);
    return true;
  }
Example #24
0
 /*
  * this method return a new file that contain the new format of the protein sequence.
  */
 private void CreatedTranslatedText(Reader rd) {
   ArrayList<String> allData = new ArrayList<String>();
   Scanner scanner = new Scanner(rd);
   while (scanner.hasNext()) {
     allData.add(scanner.next());
   }
   ArrayList<String> ID = new ArrayList<String>();
   String key = "*";
   for (int i = 0; i < allData.size(); i++) {
     if (i % 8 == 0) {
       key = allData.get(i);
       if (ID.contains(key) != true) {
         ID.add(key);
         ID.add("*");
         ID.add(allData.get(i + 1));
       } else {
       }
     } else {
     }
   }
   /*
    * i want to use array here, because i can actually know the number of elements that store
    * in the array,but the type of the elements is String.if i want to do so,i must create a
    * new class that contain ID.but here i just use arraylist.
    */
   for (int i = 0; i < ID.size() / 3; i++) {
     for (int j = 0; j < allData.size() / 8; j++) {
       if (ID.get(3 * i).equals(allData.get(8 * j))) {
         ID.set(3 * i + 1, ID.get(3 * i + 1) + ";" + allData.get(8 * j + 2));
       }
     }
   }
   try {
     PrintWriter wr = new PrintWriter(new FileWriter("FASTA-R.elm"));
     for (int i = 0; i < ID.size() / 3; i++) {
       wr.println(ID.get(3 * i) + "@" + ID.get((3 * i + 1)));
       wr.println(ID.get(3 * i + 2));
     }
   } catch (IOException ex) {
   }
 }
Example #25
0
    //the general list with the fronts is sorted based on the crowded distances 
    //in each front separately
    public void sortByCrowdingDistance(){
    
    
   
    
        for (int i = 0 ; i < Fronts.size() ; i++){
            
       
            ArrayList tempfront = (ArrayList) Fronts.get(i);
        
        for (int j = 0 ; j < tempfront.size() ; j++){
            
            for (int a = 0 ; a <  tempfront.size() ; a++){
        
                if (a > j){
                    
            NSGAII.Solutions.QRTPSolution.OneSolution first = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(j);
            double x  = first.getCrowdingDistanceTotal();
            NSGAII.Solutions.QRTPSolution.OneSolution second = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(a);
            double y  = second.getCrowdingDistanceTotal();
            
            if (y >= x){
           
            tempfront.set(j, second);
            tempfront.set(a, first);
            
            }else{ 
           
            tempfront.set(j, first);
            tempfront.set(a, second);
            }
    }        
    }      
    }   
        //System.out.println("After sorting there are "+((ArrayList)Fronts.get(i)).size()+" in "+(i));
        Fronts.set(i,tempfront);
    }  
   
   int count = 0; 
   
  // System.out.println("Fronts "+Fronts.size());
   
   for (int i = 0 ; i < Fronts.size() ; i++){
    
        ArrayList temp = (ArrayList) Fronts.get(i);
    
      //  System.out.println("temp "+temp.size());
        
    int divRank = 0;
        
    for (int j = 0 ; j < temp.size() ; j++){
    
        if (count < alg.popSize){
           
           
        ((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).setDivRank(divRank);    
        newPop[count] = (NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j);    
        count = count+1;
        divRank = divRank+1;
        
          }
    }
    }
   
   
   ArrayList tempfrontToPrint = new ArrayList();
   ArrayList oldfrontToPrint = frontToPrint;
   ArrayList newfrontToPrint = new ArrayList();
   
    //System.out.println();
    //System.out.println("In Generation "+alg.gen+" the PF is: ");
    for(int j = 0 ; j < newPop.length ; j++){
    
       if(((NSGAII.Solutions.QRTPSolution.OneSolution)newPop[j]).getRank() == 0){
        
       //System.out.println("Solution "+j+" with COV: "+((NSGAII.Solutions.QRTPSolution.OneSolution)popForGA[j]).getCoverage()+" and Life:"+((NSGAII.Solutions.QRTPSolution.OneSolution)popForGA[j]).getLifetime());    
      
       tempfrontToPrint.add(((NSGAII.Solutions.QRTPSolution.OneSolution)newPop[j]));
    }
    }

    for(int i = 0 ; i < tempfrontToPrint.size() ; i++){
    
    NSGAII.Solutions.QRTPSolution.OneSolution temp = (NSGAII.Solutions.QRTPSolution.OneSolution)tempfrontToPrint.get(i);   
       
    oldfrontToPrint.add(temp);
       
   }
    
     //System.out.println("The size is "+oldfrontToPrint.size());
    
    //WE COMPARE ALL THE SOLUTIONS TO KEEP ONLY THE BEST
    
    for(int i = 0 ; i < oldfrontToPrint.size() ; i++){
        
         boolean dominated = false;
         boolean exist = false;
         NSGAII.Solutions.QRTPSolution.OneSolution temp1 = temp1 = (NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(i);
        
        for(int j = 0 ; j < oldfrontToPrint.size() ; j++){
    
              NSGAII.Solutions.QRTPSolution.OneSolution temp2 = (NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(j);
              
              if (i != j && temp1 != null && temp2 != null){
           
      if(temp1.getEnergy() <= 0 || temp1.getTime() <= 0 ||  temp1.getRecall() <= 0){   
         
          temp1 = null;
          oldfrontToPrint.set(i,null);
       
       }}
              
          
       if (i != j && temp1 != null && temp2 != null){
           
       if((temp1.getEnergy() > temp2.getEnergy() && temp1.getTime() > temp2.getTime() && temp1.getRecall() < temp2.getRecall())||
     (temp1.getEnergy() == temp2.getEnergy() && temp1.getTime() == temp2.getTime() && temp1.getRecall() == temp2.getRecall())||
     (temp1.getEnergy() > temp2.getEnergy() && temp1.getTime() == temp2.getTime() && temp1.getRecall() ==  temp2.getRecall())||
     (temp1.getEnergy() == temp2.getEnergy() && temp1.getTime() > temp2.getTime() && temp1.getRecall() == temp2.getRecall())||
     (temp1.getEnergy() == temp2.getEnergy() && temp1.getTime() == temp2.getTime() && temp1.getRecall() < temp2.getRecall())||
     (temp1.getEnergy() > temp2.getEnergy() && temp1.getTime() > temp2.getTime() && temp1.getRecall() == temp2.getRecall())||
     (temp1.getEnergy() > temp2.getEnergy() && temp1.getTime() == temp2.getTime() && temp1.getRecall() < temp2.getRecall())||
     (temp1.getEnergy() == temp2.getEnergy() && temp1.getTime() > temp2.getTime() && temp1.getRecall() < temp2.getRecall()))
     {       
       
          temp1 = null;
          oldfrontToPrint.set(i,null);
       
       }     
       }}
    }
     
     
       for(int i = 0 ; i < oldfrontToPrint.size() ; i++){
           
      if ((NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(i) != null){
       
          
          NSGAII.Solutions.Solution newSol = new NSGAII.Solutions.QRTPSolution.OneSolution(alg.chromosomeSize);
          newSol.setChromosome(((NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(i)).getChromosome());
          newSol.setRecall(((NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(i)).getRecall());
          newSol.setEnergy(((NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(i)).getEnergy());
          newSol.setTime(((NSGAII.Solutions.QRTPSolution.OneSolution)oldfrontToPrint.get(i)).getTime());
          newfrontToPrint.add(newSol);
       
      }}
   
    
   if(alg.gen == alg.termination-1){
    System.out.println();
    System.out.println("In Generation "+alg.gen+" the PF is: ");
    for(int j = 0 ; j < newfrontToPrint.size() ; j++){
    
     NSGAII.Solutions.QRTPSolution.OneSolution temp = (NSGAII.Solutions.QRTPSolution.OneSolution)newfrontToPrint.get(j);
        
 System.out.println("Solution "+j+" with E: "+nf.format(temp.getEnergy())+" T:"+nf.format(temp.getTime())+" R:"+nf.format(temp.getRecall()));
      
   }
   //System.out.println();
   }
      
   frontToPrint = newfrontToPrint;

 }
Example #26
0
    public void calculateTotalCrowdingDistance(){
    
    for (int i = 0 ; i < Fronts.size() ; i++){
    
        //the list that has all the fronts
        ArrayList tempfront = (ArrayList) Fronts.get(i);
        double E = 0.0; 
        double PL = 0.0; 
        double DA = 0.0; 
        
        //the list that has all the fronts sorted by energy cons.
            for (int j = 0 ; j < sortByE.size() ; j ++){
            
                ArrayList tempfront1 = (ArrayList) sortByE.get(j);
                
                for (int a=0 ; a < tempfront.size() ; a++){ 
                for (int b=0 ; b < tempfront1.size() ; b++){
                
                //when the same solution is found in two lists then the one sorted by coverage
                    //gives to the general one the value of the crowding distance based on coverage
                if(((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).getIndPos() == ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getIndPos() &&
                ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).getGen() == ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getGen()){
                
                //calculates the value of croud. dist. based on coverage
                E = ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getCrowdingDistanceE();
                ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).setCrowdingDistanceE(E);
                }
                
                } 
            }
            }
        
        //this list has the fronts sorted by path loss
        for (int j = 0 ; j < sortByT.size() ; j ++){
            
                ArrayList tempfront1 = (ArrayList) sortByT.get(j);
                
                for (int a=0 ; a < tempfront.size() ; a++){ 
                    for (int b=0 ; b < tempfront1.size() ; b++){
                
                     //when the same solution is found in two lists then the one sorted by lifetime
                    //gives to the general one the value of the crowding distance based on lifetime
                if(((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).getIndPos() == ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getIndPos() &&
                ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).getGen() == ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getGen()){
                    
                                  
                     PL = ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getCrowdingDistanceT();
                     ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).setCrowdingDistanceT(PL);
                
                }
                
                }
        }
        }
        
        
         //this list has the fronts sorted by path loss
        for (int j = 0 ; j < sortByR.size() ; j ++){
            
                ArrayList tempfront1 = (ArrayList) sortByR.get(j);
                
                for (int a=0 ; a < tempfront.size() ; a++){ 
                    for (int b=0 ; b < tempfront1.size() ; b++){
                
                     //when the same solution is found in two lists then the one sorted by lifetime
                    //gives to the general one the value of the crowding distance based on lifetime
                if(((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).getIndPos() == ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getIndPos() &&
                ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).getGen() == ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getGen()){
                    
                                  
                     PL = ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront1.get(b)).getCrowdingDistanceR();
                     ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(a)).setCrowdingDistanceR(PL);

                }
                
                }
        }
        }
        
        for (int j = 0 ; j < tempfront.size() ; j++){
        
 ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).setCrowdingDistanceTotal(((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).getCrowdingDistanceE() +
 ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).getCrowdingDistanceT() + ((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).getCrowdingDistanceR()  );
       // System.out.println("The total crowding distance for solution "+j+" in front "+i+" is "+((NSGAII.Solutions.QRTPSolution.OneSolution)tempfront.get(j)).getCrowdingDistanceTotal());
        }
        
        
        //the front is returned back to the general list with the values of crowded distances
        //for each solution
        Fronts.set(i,tempfront);
        
    } 

    
    }
Example #27
0
  public static void main(String[] args) {
    num_users = 0;
    int movie_number = 0;
    MINSUP = Double.parseDouble(args[1]);
    MINCONF = Double.parseDouble(args[3]);
    MAXMOVIES = Integer.parseInt(args[5]);
    String test_raw = args[6];
    test = "";
    test = test_raw.substring(1);
    if (test.equals("comb")) {
      go_to = true;
    }

    if ((MINSUP < 0 || MINSUP > 100)
        || (MINCONF < 0 || MINCONF > 100)
        || MAXMOVIES < 0
        || test == null) {
      System.out.println("Input variables aren't correct!");
      System.exit(0);
    }
    ArrayList<User> users = new ArrayList<User>(Collections.nCopies(945, blank));
    int[] user_exists = new int[945];
    try {
      FileInputStream fstream = new FileInputStream("src/u.data"); // location of file in eclipse
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      while ((strLine = br.readLine()) != null) {
        StringTokenizer tok = new StringTokenizer(strLine);
        String ID = tok.nextToken();
        int userID = Integer.parseInt(ID);
        String MID = tok.nextToken();
        int movieID = Integer.parseInt(MID);
        String RANK = tok.nextToken();
        int movieRating = Integer.parseInt(RANK);
        Movie current_movie = new Movie(movieID, movieRating);

        if (user_exists[userID] == 0) {
          num_users++;
          users.set(userID, new User(userID, movieID, movieRating));
          user_exists[userID] = 1;
        } else {
          users.get(userID).movies.add(current_movie);
        }
      }

      in.close();
    } catch (Exception e) {
      if (e.getMessage() != null) {
        System.err.println("Error: " + e.getMessage());
      }
    }
    try {
      FileInputStream fstream = new FileInputStream("src/u.item"); // location of file in eclipse
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      while ((strLine = br.readLine()) != null) {
        movie_number++;
        StringTokenizer tok = new StringTokenizer(strLine, "|");
        String number = tok.nextToken();
        int movieNumber = Integer.parseInt(number);
        String movieName = tok.nextToken();
        for (int i = 0; i < users.size(); i++) {
          for (int j = 0; j < users.get(i).movies.size(); j++) {
            if (users.get(i).movies.get(j).movieID == movieNumber) {
              users.get(i).movies.get(j).setName(movieName);
            }
          }
        }
      }

      in.close();
    } catch (Exception j) {
      System.err.println("Error: " + j.getMessage());
    }

    // System.out.println("Num users is "+num_users);
    if (test.equals("pos")) {
      for (int user_num = 1; user_num < num_users + 1; user_num++) {
        for (int usermovies = 0; usermovies < users.get(user_num).movies.size(); usermovies++) {
          if (users.get(user_num).movies.get(usermovies).ranking <= 3) {
            users.get(user_num).movies.remove(usermovies);
            usermovies--;
          }
        }
      }
      MINSUP *= num_users;
      MINCONF *= 10;
      System.out.println(MINSUP);
      System.out.println(MINCONF);
      ArrayList<Movie> users_movies = new ArrayList<Movie>();
      Hashtable table = new Hashtable();
      Hashtable master_table = new Hashtable();
      for (int i = 1; i <= num_users; i++) {
        for (int k = 0; k < users.get(i).movies.size(); k++) {
          ArrayList<Integer> add = new ArrayList<Integer>();
          add.add(users.get(i).movies.get(k).movieID);
          // System.out.println(users.get(i).movies.get(k).movieID+ " is the current movie from user
          // "+i);

          // if(users.get(i).movies.get(k).ranking>3){
          if (table.containsKey(add)) {
            int table_value = (Integer) table.get(add);
            table_value++;
            table.put(add, table_value);
            // System.out.println("added 1 to the existing");
          } else {
            table.put(add, 1);
            // System.out.println("added a new");
          }
          // }
        }
      }
      System.out.println(table);
      Iterator final_iter = table.keySet().iterator();
      while (final_iter.hasNext()) {
        ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next();
        // System.out.println(t.get(next));
        // System.out.println(MINSUP);
        if ((Integer) table.get(next) < MINSUP) {
          // System.out.println("hi");
          final_iter.remove();
        }
      }
      // System.out.println(table);
      master_table.putAll(table);
      // System.out.println(master_table);
      for (int i = 2; i <= MAXMOVIES; i++) {
        table = find_combos(table, users, i);
        // System.out.println("table generated is "+table);
        if (!table.isEmpty()) {
          master_table.putAll(table);
        }
        // System.out.println(master_table);
      }
      // System.out.println(master_table+" is before print_up");
      printup(master_table);
    }
    if (test.equals("neg")) {
      for (int user_num = 1; user_num < num_users + 1; user_num++) {
        for (int usermovies = 0; usermovies < users.get(user_num).movies.size(); usermovies++) {
          if (users.get(user_num).movies.get(usermovies).ranking >= 3) {
            users.get(user_num).movies.remove(usermovies);
            usermovies--;
          }
        }
      }
      MINSUP *= num_users;
      MINCONF *= 10;
      ArrayList<Movie> users_movies = new ArrayList<Movie>();
      Hashtable table = new Hashtable();
      Hashtable master_table = new Hashtable();
      for (int i = 1; i <= num_users; i++) {
        for (int k = 0; k < users.get(i).movies.size(); k++) {
          ArrayList<Integer> add = new ArrayList<Integer>();
          add.add(users.get(i).movies.get(k).movieID);
          // System.out.println(users.get(i).movies.get(k).movieID+ " is the current movie from user
          // "+i);

          // if(users.get(i).movies.get(k).ranking>3){
          if (table.containsKey(add)) {
            int table_value = (Integer) table.get(add);
            table_value++;
            table.put(add, table_value);
            // System.out.println("added 1 to the existing");
          } else {
            table.put(add, 1);
            // System.out.println("added a new");
          }
          // }
        }
      }
      // System.out.println(table);
      Iterator final_iter = table.keySet().iterator();
      while (final_iter.hasNext()) {
        ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next();
        // System.out.println(t.get(next));
        // System.out.println(MINSUP);
        if ((Integer) table.get(next) < MINSUP) {
          // System.out.println("hi");
          final_iter.remove();
        }
      }
      // System.out.println(table);
      master_table.putAll(table);
      // System.out.println(master_table);
      for (int i = 2; i <= MAXMOVIES; i++) {
        table = find_combos(table, users, i);
        if (!table.isEmpty()) {
          master_table.putAll(table);
        }
      }
      // System.out.println(master_table+" is before print_up");
      printup(master_table);
    }
    if (test.equals("comb")) {
      for (int user_num = 1; user_num < num_users + 1; user_num++) {
        for (int usermovies = 0; usermovies < users.get(user_num).movies.size(); usermovies++) {
          if (users.get(user_num).movies.get(usermovies).ranking >= 3) {
            users.get(user_num).movies.remove(usermovies);
            usermovies--;
          }
        }
      }
      MINSUP *= num_users;
      MINCONF *= 10;
      ArrayList<Movie> users_movies = new ArrayList<Movie>();
      Hashtable table = new Hashtable();
      Hashtable master_table = new Hashtable();
      for (int i = 1; i <= num_users; i++) {
        for (int k = 0; k < users.get(i).movies.size(); k++) {
          ArrayList<Integer> add = new ArrayList<Integer>();
          add.add(users.get(i).movies.get(k).movieID);
          // System.out.println(users.get(i).movies.get(k).movieID+ " is the current movie from user
          // "+i);

          // if(users.get(i).movies.get(k).ranking>3){
          if (table.containsKey(add)) {
            int table_value = (Integer) table.get(add);
            table_value++;
            table.put(add, table_value);
            // System.out.println("added 1 to the existing");
          } else {
            table.put(add, 1);
            // System.out.println("added a new");
          }
          // }
        }
      }
      // System.out.println(table);
      Iterator final_iter = table.keySet().iterator();
      while (final_iter.hasNext()) {
        ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next();
        // System.out.println(t.get(next));
        // System.out.println(MINSUP);
        if ((Integer) table.get(next) < MINSUP) {
          // System.out.println("hi");
          final_iter.remove();
        }
      }
      // System.out.println(table);
      master_table.putAll(table);
      // System.out.println(master_table);
      for (int i = 2; i <= MAXMOVIES; i++) {
        table = find_combos(table, users, i);
        if (!table.isEmpty()) {
          master_table.putAll(table);
        }
      }
      // System.out.println(master_table+" is before print_up");
      test = "neg";
      printup(master_table);
      test = "comb2";
    }
    if (test.equals("comb2")) {

      users = new ArrayList<User>(Collections.nCopies(945, blank));
      user_exists = new int[945];
      num_users = 0;

      try {
        FileInputStream fstream = new FileInputStream("src/u.data"); // location of file in eclipse
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null) {
          StringTokenizer tok = new StringTokenizer(strLine);
          String ID = tok.nextToken();
          int userID = Integer.parseInt(ID);
          String MID = tok.nextToken();
          int movieID = Integer.parseInt(MID);
          String RANK = tok.nextToken();
          int movieRating = Integer.parseInt(RANK);
          Movie current_movie = new Movie(movieID, movieRating);

          if (user_exists[userID] == 0) {
            num_users++;
            users.set(userID, new User(userID, movieID, movieRating));
            user_exists[userID] = 1;
          } else {
            users.get(userID).movies.add(current_movie);
          }
        }

        in.close();
      } catch (Exception e) {
        if (e.getMessage() != null) {
          System.err.println("Error: " + e.getMessage());
        }
      }
      try {
        FileInputStream fstream = new FileInputStream("src/u.item"); // location of file in eclipse
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null) {
          movie_number++;
          StringTokenizer tok = new StringTokenizer(strLine, "|");
          String number = tok.nextToken();
          int movieNumber = Integer.parseInt(number);
          String movieName = tok.nextToken();
          for (int i = 0; i < users.size(); i++) {
            for (int j = 0; j < users.get(i).movies.size(); j++) {
              if (users.get(i).movies.get(j).movieID == movieNumber) {
                users.get(i).movies.get(j).setName(movieName);
              }
            }
          }
        }

        in.close();
      } catch (Exception j) {
        System.err.println("Error: " + j.getMessage());
      }
      for (int user_num = 1; user_num < num_users + 1; user_num++) {
        for (int usermovies = 0; usermovies < users.get(user_num).movies.size(); usermovies++) {
          if (users.get(user_num).movies.get(usermovies).ranking <= 3) {
            users.get(user_num).movies.remove(usermovies);
            usermovies--;
          }
        }
      }

      ArrayList<Movie> users_movies = new ArrayList<Movie>();
      Hashtable table = new Hashtable();
      Hashtable master_table = new Hashtable();
      for (int i = 1; i <= num_users; i++) {
        for (int k = 0; k < users.get(i).movies.size(); k++) {
          ArrayList<Integer> add = new ArrayList<Integer>();
          add.add(users.get(i).movies.get(k).movieID);
          // System.out.println(users.get(i).movies.get(k).movieID+ " is the current movie from user
          // "+i);

          if (table.containsKey(add)) {
            int table_value = (Integer) table.get(add);
            table_value++;
            table.put(add, table_value);
            // System.out.println("added 1 to the existing");
          } else {
            table.put(add, 1);
            // System.out.println("added a new");
          }
          // }
        }
      }
      // System.out.println(table);
      Iterator final_iter = table.keySet().iterator();
      while (final_iter.hasNext()) {
        ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next();
        // System.out.println(t.get(next));
        // System.out.println(MINSUP);
        if ((Integer) table.get(next) < MINSUP) {
          // System.out.println("hi");
          final_iter.remove();
        }
      }
      // System.out.println(table);
      master_table.putAll(table);
      // System.out.println(master_table);
      for (int i = 2; i < MAXMOVIES; i++) {
        table = find_combos(table, users, i);
        if (!table.isEmpty()) {
          master_table.putAll(table);
        }
      }
      // System.out.println(master_table+" is before print_up");
      test = "pos";
      printup(master_table);
    }
  }
Example #28
0
  public void initialiseWithLines(ArrayList<StringBuilder> lines, ProcessingOptions options)
      throws UnsupportedEncodingException {

    // remove blank rows at the bottom
    boolean done = false;
    int i;
    for (i = lines.size() - 1; i >= 0 && !done; i--) {
      StringBuilder row = lines.get(i);
      if (!StringUtils.isBlank(row.toString())) done = true;
    }
    rows = new ArrayList<StringBuilder>(lines.subList(0, i + 2));

    if (options != null) fixTabs(options.getTabSize());
    else fixTabs(ProcessingOptions.DEFAULT_TAB_SIZE);

    // make all lines of equal length
    // add blank outline around the buffer to prevent fill glitch
    // convert tabs to spaces (or remove them if setting is 0)

    int blankBorderSize = 2;

    int maxLength = 0;
    int index = 0;

    String encoding = null;
    if (options != null) encoding = options.getCharacterEncoding();

    Iterator<StringBuilder> it = rows.iterator();
    while (it.hasNext()) {
      String row = it.next().toString();
      if (encoding != null) {
        byte[] bytes = row.getBytes();
        row = new String(bytes, encoding);
      }
      if (row.length() > maxLength) maxLength = row.length();
      rows.set(index, new StringBuilder(row));
      index++;
    }

    it = rows.iterator();
    ArrayList<StringBuilder> newRows = new ArrayList<StringBuilder>();
    // TODO: make the following depend on blankBorderSize

    StringBuilder topBottomRow =
        new StringBuilder(StringUtils.repeatString(" ", maxLength + blankBorderSize * 2));

    newRows.add(topBottomRow);
    newRows.add(topBottomRow);
    while (it.hasNext()) {
      StringBuilder row = it.next();

      if (row.length() < maxLength) {
        String borderString = StringUtils.repeatString(" ", blankBorderSize);
        StringBuilder newRow = new StringBuilder();

        newRow.append(borderString);
        newRow.append(row);
        newRow.append(StringUtils.repeatString(" ", maxLength - row.length()));
        newRow.append(borderString);

        newRows.add(newRow);
      } else { // TODO: why is the following line like that?
        newRows.add(new StringBuilder("  ").append(row).append("  "));
      }
    }
    // TODO: make the following depend on blankBorderSize
    newRows.add(topBottomRow);
    newRows.add(topBottomRow);
    rows = newRows;

    replaceBullets();
    replaceHumanColorCodes();
  }
  public static void main(String[] args) throws Exception {
    int V, E, s, u, v, w;

    /* // Graph in Figure 4.17
    5 7 2
    2 1 2
    2 3 7
    2 0 6
    1 3 3
    1 4 6
    3 4 5
    0 4 1
        */

    Scanner sc = new Scanner(System.in);
    V = sc.nextInt();
    E = sc.nextInt();
    s = sc.nextInt();

    AdjList.clear();
    for (int i = 0; i < V; i++) {
      ArrayList<IntegerPair> Neighbor = new ArrayList<IntegerPair>();
      AdjList.add(Neighbor); // add neighbor list to Adjacency List
    }

    for (int i = 0; i < E; i++) {
      u = sc.nextInt();
      v = sc.nextInt();
      w = sc.nextInt();
      AdjList.get(u).add(new IntegerPair(v, w)); // first time using weight
    }

    // Dijkstra routine
    ArrayList<Integer> dist = new ArrayList<>();
    // INF = 1*10^9 not MAX_INT to avoid overflow
    dist.addAll(Collections.nCopies(V, INF));
    dist.set(s, 0);
    PriorityQueue<IntegerPair> pq =
        new PriorityQueue<IntegerPair>(
            1,
            new Comparator<IntegerPair>() { // overriding the compare method
              public int compare(IntegerPair i, IntegerPair j) {
                return i.dfs - j.dfs;
              }
            });
    pq.offer(new IntegerPair(s, 0)); // sort based on increasing distance

    while (!pq.isEmpty()) { // main loop
      IntegerPair top = pq.poll(); // greedy: pick shortest unvisited vertex
      int d = top.dfs;
      u = top.vn;
      if (d > dist.get(u)) continue; // We want to process vertex u only once!
      Iterator it = AdjList.get(u).iterator();
      while (it.hasNext()) { // all outgoing edges from u
        IntegerPair p = (IntegerPair) it.next();
        v = p.vn;
        int weight_u_v = p.dfs;
        if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax
          // (note: Record SP spanning tree here if needed. This is similar)
          dist.set(v, dist.get(u) + weight_u_v); // relax
          pq.offer(new IntegerPair(v, dist.get(v))); //   (as printpath in BFS)
          // enqueue this neighbor regardless whether it is already in pq or not
        }
      }
    }

    for (int i = 0; i < V; i++) // index + 1 for final answer
    System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist.get(i));
  }
Example #30
0
 public void setRow(int y, StringBuilder row) {
   if (y > getHeight() || row.length() != getWidth())
     throw new IllegalArgumentException("setRow out of bounds or string wrong size");
   rows.set(y, row);
 }