コード例 #1
4
  public ListNode mergeKLists(ArrayList<ListNode> lists) {

    if (lists.size() == 0) return null;

    PriorityQueue<ListNode> q =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {

              public int compare(ListNode a, ListNode b) {
                if (a.val > b.val) return 1;
                else if (a.val == b.val) return 0;
                else return -1;
              }
            });

    for (ListNode i : lists) if (i != null) q.add(i);

    ListNode head = new ListNode(-1);
    ListNode pre = head;

    while (q.size() != 0) {

      ListNode temp = q.poll();
      pre.next = temp;

      if (temp.next != null) q.add(temp.next);

      pre = pre.next;
    }

    return head.next;
  }
コード例 #2
1
  public static Hashtable findConfidence(Hashtable table) {
    Hashtable confidences = new Hashtable();
    Iterator key_iter = table.keySet().iterator();
    while (key_iter.hasNext()) {
      // System.out.println("here");
      ArrayList<Integer> combo = (ArrayList<Integer>) key_iter.next();
      // System.out.println("current combo"+combo);
      if (combo.size() >= 2) {
        ArrayList<Integer> current_combo =
            new ArrayList<Integer>(combo.subList(0, combo.size() - 1));
        ArrayList<Integer> last_combo =
            new ArrayList<Integer>(combo.subList(combo.size() - 1, combo.size()));
        /*System.out.println(combo);
        System.out.println(current_combo);
        System.out.println(last_combo);
        System.out.println(table.get(current_combo));*/

        if (table.get(current_combo) != null) {
          // System.out.println("it contains!");
          int first = (Integer) table.get(current_combo);
          int second = (Integer) table.get(combo);
          double dub_first = (double) first;
          double dub_second = (double) second;
          double combo_conf = dub_second / dub_first;
          confidences.put(combo, combo_conf);
          // System.out.println("combo:"+combo+" has the confience: "+combo_conf);
        }
      }
    }
    // System.out.println(confidences+"O");

    return confidences;
  }
コード例 #3
0
  @NotNull
  public EditorWindow[] getOrderedWindows() {
    final ArrayList<EditorWindow> res = new ArrayList<EditorWindow>();

    // Collector for windows in tree ordering:
    class Inner {
      final void collect(final JPanel panel) {
        final Component comp = panel.getComponent(0);
        if (comp instanceof Splitter) {
          final Splitter splitter = (Splitter) comp;
          collect((JPanel) splitter.getFirstComponent());
          collect((JPanel) splitter.getSecondComponent());
        } else if (comp instanceof JPanel || comp instanceof JBTabs) {
          final EditorWindow window = findWindowWith(comp);
          if (window != null) {
            res.add(window);
          }
        }
      }
    }

    // get root component and traverse splitters tree:
    if (getComponentCount() != 0) {
      final Component comp = getComponent(0);
      LOG.assertTrue(comp instanceof JPanel);
      final JPanel panel = (JPanel) comp;
      if (panel.getComponentCount() != 0) {
        new Inner().collect(panel);
      }
    }

    LOG.assertTrue(res.size() == myWindows.size());
    return res.toArray(new EditorWindow[res.size()]);
  }
コード例 #4
0
  protected void finishedWith(
      String sourceLocator,
      CompilationResult result,
      char[] mainTypeName,
      ArrayList definedTypeNames,
      ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null) previousTypeNames = new char[][] {mainTypeName};
    IPath packagePath = null;
    next:
    for (int i = 0, l = previousTypeNames.length; i < l; i++) {
      char[] previous = previousTypeNames[i];
      for (int j = 0, m = definedTypeNames.size(); j < m; j++)
        if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) continue next;

      SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
      if (packagePath == null) {
        int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        packagePath =
            sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
      }
      if (this.secondaryTypesToRemove == null)
        this.secondaryTypesToRemove = new SimpleLookupTable();
      ArrayList types =
          (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
      if (types == null) types = new ArrayList(definedTypeNames.size());
      types.add(packagePath.append(new String(previous)));
      this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
  }
コード例 #5
0
  void terminate_all() {
    log("Stopping " + schs.size() + " schnauzer(s)");

    for (int i = 0; i < schs.size(); i++) {
      schs.get(i).keep_running = false;
    }
  }
コード例 #6
0
 public Cube(double x, double y, double z, double w) {
   super();
   id = "Cube";
   width = w;
   ArrayList<Point3D> pts = new ArrayList<Point3D>();
   pts.add(new Point3D(x, y, z));
   pts.add(new Point3D(x + w, y, z));
   pts.add(new Point3D(x + w, y + w, z));
   pts.add(new Point3D(x, y + w, z));
   for (int i = 0; i < pts.size() - 1; i++) {
     lines.add(new Line3D(pts.get(i), pts.get(i + 1)));
   }
   lines.add(new Line3D(pts.get(0), new Point3D(x, y + w, z)));
   int size = lines.size();
   for (int i = 0; i < size; i++) {
     lines.add(
         new Line3D(
             new Point3D(lines.get(i).point1.x, lines.get(i).point1.y, lines.get(i).point1.z + w),
             new Point3D(
                 lines.get(i).point2.x, lines.get(i).point2.y, lines.get(i).point2.z + w)));
   }
   size = pts.size();
   for (int i = 0; i < size; i++) {
     pts.add(new Point3D(pts.get(i).x, pts.get(i).y, pts.get(i).z + w));
   }
   for (int i = 0; i < 4; i++) {
     lines.add(new Line3D(pts.get(i), pts.get(i + 4)));
   }
   pan(new Point3D(0, 0, 0));
 }
コード例 #7
0
  private boolean isPossible(int[] expression) {
    ArrayList<Integer> open = new ArrayList<>();
    for (int i = 0; i < expression.length; ++i) {
      int character = expression[i];

      if (character < 3) {
        open.add(character);
      } else {
        if (open.size() == 0) {
          return false;
        }

        if (open.get(open.size() - 1) != character - 3) {
          return false;
        }

        open.remove(open.size() - 1);
      }
    }

    if (open.size() != 0) {
      return false;
    }

    return true;
  }
コード例 #8
0
ファイル: PlusOne.java プロジェクト: goke-epapa/DSInJava
  // TODO Check https://leetcode.com/discuss/58149/my-simple-java-solution
  public int[] plusOne(int[] digits) {
    if (digits == null || digits.length == 0) return digits;

    ArrayList<Integer> list = new ArrayList<Integer>();

    int elementToAdd = 1;
    for (int i = digits.length - 1; i >= 0; i--) {
      int newElem = digits[i] + elementToAdd;

      elementToAdd = 0;
      if (newElem > 9) {
        elementToAdd = 1;
        newElem = 0;
      }
      list.add(newElem);
    }

    if (elementToAdd == 1) {
      list.add(elementToAdd);
    }

    int[] result = new int[list.size()];

    for (int i = 0; i < list.size(); i++) {
      result[list.size() - i - 1] = list.get(i);
    }

    return result;
  }
コード例 #9
0
ファイル: Employee.java プロジェクト: VictoriaLacroix/umple
  public boolean setWards(Ward... newWards) {
    boolean wasSet = false;
    ArrayList<Ward> verifiedWards = new ArrayList<Ward>();
    for (Ward aWard : newWards) {
      if (verifiedWards.contains(aWard)) {
        continue;
      }
      verifiedWards.add(aWard);
    }

    if (verifiedWards.size() != newWards.length || verifiedWards.size() < minimumNumberOfWards()) {
      return wasSet;
    }

    ArrayList<Ward> oldWards = new ArrayList<Ward>(wards);
    wards.clear();
    for (Ward aNewWard : verifiedWards) {
      wards.add(aNewWard);
      if (oldWards.contains(aNewWard)) {
        oldWards.remove(aNewWard);
      } else {
        aNewWard.addEmployee(this);
      }
    }

    for (Ward anOldWard : oldWards) {
      anOldWard.removeEmployee(this);
    }
    wasSet = true;
    return wasSet;
  }
コード例 #10
0
  @Nullable
  private synchronized Loader getLoader(int i) {
    while (myLoaders.size() < i + 1) {
      boolean lastOne;
      URL url;
      synchronized (myUrls) {
        if (myUrls.empty()) {
          if (myCanUseCache) myCache.nameSymbolsLoaded();
          return null;
        }
        url = myUrls.pop();
        lastOne = myUrls.isEmpty();
      }

      if (myLoadersMap.containsKey(url)) continue;

      Loader loader;
      try {
        loader = getLoader(url, myLoaders.size());
        if (loader == null) continue;
      } catch (IOException ioexception) {
        continue;
      }

      myLoaders.add(loader);
      myLoadersMap.put(url, loader);
      if (lastOne && myCanUseCache) {
        myCache.nameSymbolsLoaded();
      }
    }

    return myLoaders.get(i);
  }
コード例 #11
0
  private double computeAverageScores(ArrayList<Double> s) {
    double result = 0.0;
    if (s == null || s.size() == 0) return result;
    for (int i = 0; i < s.size(); i++) result += s.get(i);

    return result / (s.size());
  }
コード例 #12
0
  // evaluate Fisher score of all indexes in current ^ featIndex
  private double evaluateFisher(HashSet<Integer> current, int featIndex) {
    ArrayList<Integer> d = new ArrayList<Integer>(current);
    d.add(featIndex);
    ArrayList<ArrayList<Integer>> vectors = new ArrayList<ArrayList<Integer>>();
    for (int i = 0; i < getA().get_classes().size(); i++) {
      ArrayList<ArrayList<Integer>> cl = getA().features.get(getA().get_classes().get(i));
      ArrayList<Integer> tmp = new ArrayList<Integer>();
      for (int j = 0; j < cl.size(); j++) {
        int sum = 0;
        for (int k = 0; k < d.size(); k++) sum += cl.get(j).get(d.get(k));
        if (sum == d.size()) tmp.add(1);
        else tmp.add(0);
      }
      vectors.add(tmp);
    }
    ArrayList<double[]> stats = new ArrayList<double[]>();
    int count = 0;
    double sum = 0.0;
    for (int i = 0; i < vectors.size(); i++) {
      double[] res = computeMeanVariance(vectors.get(i));
      sum += (vectors.get(i).size() * res[0]);
      count += vectors.get(i).size();
      stats.add(res);
    }
    sum = sum / count;

    double num = 0.0;
    double denom = 0.0;
    for (int i = 0; i < stats.size(); i++) {
      num += (vectors.get(i).size() * Math.pow(stats.get(i)[0] - sum, 2));
      denom += (vectors.get(i).size() * Math.pow(stats.get(i)[1], 2));
    }
    if (denom == 0.0) return 0;
    else return num / denom;
  }
コード例 #13
0
  private void extendFeatures() {
    for (int i = 0; i < getA().get_classes().size(); i++) {
      ArrayList<ArrayList<Integer>> cl = getA().features.get(getA().get_classes().get(i));
      for (int j = 0; j < cl.size(); j++) {
        ArrayList<Integer> sample = cl.get(j);
        for (int m = 0; m < getConjuncts().size(); m++) {

          ArrayList<Integer> d = new ArrayList<Integer>(getConjuncts().get(m));
          int sum = 0;
          for (int k = 0; k < d.size(); k++) sum += sample.get(d.get(k));
          if (sum == d.size()) sample.add(1);
          else sample.add(0);
          inv_conjunct.put(getConjuncts().get(m), sample.size() - 1);
          double score = conjunct_scores.get(getConjuncts().get(m));
          if (!getScoremap().containsKey(score)) getScoremap().put(score, new HashSet<Integer>());
          getScoremap().get(score).add(sample.size() - 1);
          getScores().add(score);
          setFeats_num(getFeats_num() + 1);
        }
      }
    }
    Collections.sort(getScores());
    ArrayList<Double> tmp = new ArrayList<Double>();
    for (int i = getScores().size() - 1; i >= 0; i--) tmp.add(getScores().get(i));
    setScores(tmp);
  }
コード例 #14
0
  public void updatePickups() {
    for (int i = 0; i < pickupList.size(); i++) {
      if (pickupList.get(i).pickedUp) pickupList.remove(i);
    } // end for

    while (pickupList.size() < startNumPickups) pickupList.add(new Pickup(frameWidth, frameHeight));
  } // end updatePickups
コード例 #15
0
  public EntityPainting(World par1World, int par2, int par3, int par4, int par5) {
    this(par1World);
    xPosition = par2;
    yPosition = par3;
    zPosition = par4;
    ArrayList arraylist = new ArrayList();
    EnumArt aenumart[] = EnumArt.values();
    int i = aenumart.length;

    for (int j = 0; j < i; j++) {
      EnumArt enumart = aenumart[j];
      art = enumart;
      func_179_a(par5);

      if (onValidSurface()) {
        arraylist.add(enumart);
      }
    }

    if (arraylist.size() > 0) {
      art = (EnumArt) arraylist.get(rand.nextInt(arraylist.size()));
    }

    func_179_a(par5);
  }
コード例 #16
0
  public static void main(String[] args) {
    ArrayList<Pattern> patterns = new ArrayList<Pattern>();
    ArrayList<Cut> cuts;
    ArrayList<Garment> garments;

    patterns.add(new Pattern(2, 2, 1, "Tie"));
    patterns.add(new Pattern(2, 6, 4, "Skirt"));
    patterns.add(new Pattern(4, 2, 3, "Blouse"));
    patterns.add(new Pattern(5, 3, 5, "Dress"));
    int width = 30;
    int height = 15;
    ClothCutter cutter = new ClothCutter(width, height, patterns);
    System.out.println("Optimized value: " + cutter.optimize());
    cuts = cutter.getCuts();
    garments = cutter.getGarments();

    ClothPanel panel = new ClothPanel(width, height);
    JFrame frame = new JFrame("A luxurious bolt of fabric");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    sleep(1000);
    for (int i = 0; i < cuts.size(); i++) {
      panel.drawCut(cuts.get(i));
      sleep(100);
    }
    for (int i = 0; i < garments.size(); i++) {
      System.out.println(garments.get(i));
      panel.drawGarment(garments.get(i));
      sleep(100);
    }
  }
コード例 #17
0
  /**
   * Parse a method declaration. The declaration should be in the following format:
   *
   * <p>fully-qualified-method-name (args)
   *
   * <p>where the arguments are comma separated and all arguments other than primitives should have
   * fully qualified names. Arrays are indicating by trailing brackets. For example:
   *
   * <p>int int[] int[][] java.lang.String java.util.Date[]
   *
   * <p>The arguments are translated into BCEL types and a MethodDef is returned.
   */
  private MethodDef parse_method(StrTok st) {

    // Get the method name
    String method_name = st.need_word();

    // Get the opening paren
    st.need("(");

    // Read the arguments
    ArrayList<String> args = new ArrayList<String>();
    String tok = st.nextToken();
    if (tok != ")") {
      st.pushBack();
      do {
        tok = st.need_word();
        args.add(tok);
      } while (st.nextToken() == ",");
      st.pushBack();
      st.need(")");
    }

    // Convert the arguments to Type
    Type[] targs = new Type[args.size()];
    for (int ii = 0; ii < args.size(); ii++) {
      targs[ii] = BCELUtil.classname_to_type(args.get(ii));
    }

    return new MethodDef(method_name, targs);
  }
コード例 #18
0
ファイル: fence.java プロジェクト: ahu888/usaco-training
  public int[] solve(String[] edgeStrings) {

    ArrayList<Integer> oddPoints = new ArrayList<Integer>();

    int min = Integer.MAX_VALUE;
    for (String s : edgeStrings) {
      StringTokenizer st = new StringTokenizer(s);
      int from = Integer.parseInt(st.nextToken());
      int to = Integer.parseInt(st.nextToken());
      edges.add(new Edge(from, to));

      min = Math.min(min, from);
      min = Math.min(min, to);
      oddPoint(oddPoints, from);
      oddPoint(oddPoints, to);
    }

    assert (oddPoints.size() < 3);

    if (oddPoints.size() > 0) {
      dfs(min(oddPoints));
      return toArray(circuit);
    } else {
      dfs(min);
      return toArray(circuit);
    }
  }
コード例 #19
0
ファイル: Update.java プロジェクト: dmsl/smartp2p
     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);
		}
    

    }
コード例 #20
0
 private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException {
   if (processedLinks.contains(url)) {
     return false;
   } else {
     processedLinks.add(url);
   }
   URLConnection connection = url.openConnection();
   InputStream in = new BufferedInputStream(connection.getInputStream());
   ArrayList list = processPage(in, baseDir, url);
   if ((status != null) && (list.size() > 0)) {
     status.setMaximum(list.size());
   }
   for (int i = 0; i < list.size(); i++) {
     if (status != null) {
       status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i);
     }
     if ((!((String) list.get(i)).startsWith("RUN"))
         && (!((String) list.get(i)).startsWith("SAVE"))
         && (!((String) list.get(i)).startsWith("LOAD"))) {
       processURL(
           new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)),
           baseDir,
           status);
     }
   }
   in.close();
   return true;
 }
コード例 #21
0
 public static void findMaxCut() {
   int arrayCut = Integer.MAX_VALUE;
   int indexCut = Integer.MAX_VALUE;
   int max = Integer.MIN_VALUE;
   int numArrays = occupied.size();
   for (int i = 0; i < numArrays; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len = arr.size();
     for (int j = 0; j < len - 1; j++) {
       if (arr.get(j + 1) - arr.get(j) > max) {
         max = arr.get(j + 1) - arr.get(j);
         indexCut = j;
         arrayCut = i;
       }
     }
   }
   ArrayList<Integer> arr1 = new ArrayList<Integer>();
   ArrayList<Integer> arr2 = new ArrayList<Integer>();
   ArrayList<Integer> arr = occupied.get(arrayCut);
   for (int i = 0; i <= indexCut; i++) {
     arr1.add(arr.get(i));
   }
   for (int i = indexCut + 1; i < arr.size(); i++) {
     arr2.add(arr.get(i));
   }
   occupied.remove(arrayCut);
   occupied.add(arr1);
   occupied.add(arr2);
 }
コード例 #22
0
  public static ArrayList<ArrayList<TaggedWord>> getPhrasesNaive(
      String sentence, LexicalizedParser lp, AbstractSequenceClassifier<CoreLabel> classifier) {
    ArrayList<ArrayList<TaggedWord>> newList = new ArrayList<ArrayList<TaggedWord>>();
    ArrayList<TaggedWord> taggedWords = StanfordNER.parse(sentence, lp, classifier);
    HashMap<String, String> phraseBoundaries = new HashMap<String, String>();
    phraseBoundaries.put(",", ",");
    phraseBoundaries.put("\"", "\"");
    phraseBoundaries.put("''", "''");
    phraseBoundaries.put("``", "``");
    phraseBoundaries.put("--", "--");
    // List<Tree> leaves = parse.getLeaves();
    ArrayList<TaggedWord> temp = new ArrayList<TaggedWord>();
    int index = 0;
    while (index < taggedWords.size()) {
      if ((phraseBoundaries.containsKey(taggedWords.get(index).word()))) {
        if (temp.size() > 0) {
          // System.out.println(temp);
          ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
          newList.add(Preprocess(tempCopy));
        }
        temp.clear();
      } else {
        // System.out.println(taggedWords.get(index).toString());
        temp.add(taggedWords.get(index));
      }
      index += 1;
    }
    if (temp.size() > 0) {
      ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
      newList.add(Preprocess(tempCopy));
    }

    // System.out.println(newList);
    return newList;
  }
コード例 #23
0
  static void method1(int len, int arr[]) {
    if (len == 100000 && arr[0] == 1) {
      System.out.print("1 1");
      return;
    }
    int start = 0, end = 0, size = 0, small = len + 1, l = 0, r = 0, big = 0;
    HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(len);
    ArrayList<Integer> arrl = null;
    for (int i = 0; i < len; i++) {
      addToMap(arr[i], i, map);
    }

    for (Map.Entry<Integer, ArrayList<Integer>> e : map.entrySet()) {
      arrl = (ArrayList<Integer>) e.getValue();
      if ((arrl.size() >= big && arrl.size() != 1)) {
        big = arrl.size();
        start = arrl.get(0);
        end = arrl.get(arrl.size() - 1);
        size = end - start + 1;
        if (size < small) {
          small = size;
          l = start + 1;
          r = end + 1;
        }
      }
    }

    System.out.println(l + " " + r);
  }
コード例 #24
0
 /**
  * Return certificates for signed bundle, otherwise null.
  *
  * @return An array of certificates or null.
  */
 public ArrayList getCertificateChains(boolean onlyTrusted) {
   if (checkCerts) {
     Certificate[] c = archive.getCertificates();
     checkCerts = false;
     if (c != null) {
       ArrayList failed = new ArrayList();
       untrustedCerts = Util.getCertificateChains(c, failed);
       if (!failed.isEmpty()) {
         // NYI, log Bundle archive has invalid certificates
         untrustedCerts = null;
       }
     }
   }
   ArrayList res = trustedCerts;
   if (!onlyTrusted && untrustedCerts != null) {
     if (res == null) {
       res = untrustedCerts;
     } else {
       res = new ArrayList(trustedCerts.size() + untrustedCerts.size());
       res.addAll(trustedCerts);
       res.addAll(untrustedCerts);
     }
   }
   return res;
 }
コード例 #25
0
  private void removeProgress(@NotNull InlineProgressIndicator progress) {
    synchronized (myOriginals) {
      if (!myInline2Original.containsKey(progress)) return;

      final boolean last = myOriginals.size() == 1;
      final boolean beforeLast = myOriginals.size() == 2;

      myPopup.removeIndicator(progress);

      final ProgressIndicatorEx original = removeFromMaps(progress);
      if (myOriginals.contains(original)) return;

      if (last) {
        restoreEmptyStatus();
        if (myShouldClosePopupAndOnProcessFinish) {
          hideProcessPopup();
        }
      } else {
        if (myPopup.isShowing() || myOriginals.size() > 1) {
          buildInProcessCount();
        } else if (beforeLast) {
          buildInInlineIndicator(createInlineDelegate(myInfos.get(0), myOriginals.get(0), true));
        } else {
          restoreEmptyStatus();
        }
      }

      runQuery();
    }
  }
コード例 #26
0
ファイル: CountryBin.java プロジェクト: baldleif/workspace
  public void calcSigma() {

    Double summation = new Double(0);

    // Take the sum of gdplist and divide by n

    for (Double x1 : gdplist) summation += x1;

    average = summation / gdplist.size();

    // Now we have the mean

    // Take the difference of the GDP by year and the mean
    // Sum all of the squares of the differences
    // Take the square root of the sum == std deviation

    summation = new Double(0);

    for (Double x1 : gdplist) { // look at each year GDP
      Double x2 = x1 - average; // subtract the average from that year GDP

      summation += (x2 * x2); // square the result and add it to a total sum
    }

    summation = summation / gdplist.size();

    stdev = Math.sqrt(summation);
  }
コード例 #27
0
  public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    // Start typing your Java solution below
    // DO NOT write main() function

    ArrayList<Interval> res = new ArrayList<Interval>();
    if (intervals.size() == 0) return res;
    Collections.sort(intervals, new MyC());
    int start = 0;
    int end = 0;
    for (int i = 0; i < intervals.size(); i++) {
      if (i == 0) {
        start = intervals.get(i).start;
        end = intervals.get(i).end;
      } else {
        if (intervals.get(i).start <= end) {
          end = Math.max(end, intervals.get(i).end);
        } else {
          res.add(new Interval(start, end));
          start = intervals.get(i).start;
          end = intervals.get(i).end;
        }
      }
    }
    res.add(new Interval(start, end));
    return res;
  }
コード例 #28
0
ファイル: MergeSort.java プロジェクト: Tazmere/APCS-HW
    public ArrayList<String> mergeString(ArrayList<String> a, ArrayList<String> b) {
        ArrayList<String> result = new ArrayList<String>();
        int countA = 0;
        int countB = 0;
	int count = 0;
        while (count < (a.size() + b.size())) {
            if (countA == a.size()) {
                result.add(b.get(countB));
	        countB++;
            }
            else if (countB == b.size()) {
                result.add(a.get(countA));
                countA++;
            }
            else if (a.get(countA).compareTo(b.get(countB)) > 0) {

		result.add(b.get(countB));
	        countB++;
            }
            else {
                result.add(a.get(countA));
                countA++;
            }
            count++;
        }
        return result;
    }
コード例 #29
0
ファイル: MergeSort.java プロジェクト: Tazmere/APCS-HW
    public ArrayList<String> mergeSortString(ArrayList<String> l) {
        ArrayList<String> a;
        ArrayList<String> b;
        if (l.size() <= 1) {
            return l;
        }
        else {
            int n = l.size()/2;
            a = new ArrayList<String>();
            b = new ArrayList<String>();
            for (int i = 0; i < l.size(); i++) {
                if (i < n) {
                    a.add(l.get(i));
                }
                else {
                    b.add(i-n, l.get(i));
                }
            }
	}
        a = mergeSortString(a);
        b = mergeSortString(b);
        l = mergeString(a, b);
        return l;

    }
コード例 #30
0
 private PackageSource findRequiredSource(String pkgName, KeyedHashSet visited) {
   if (requiredBundles == null) return null;
   synchronized (requiredSources) {
     PackageSource result = (PackageSource) requiredSources.getByKey(pkgName);
     if (result != null) return result.isNullSource() ? null : result;
   }
   if (visited == null) visited = new KeyedHashSet(false);
   visited.add(bundle); // always add ourselves so we do not recurse back to ourselves
   ArrayList result = new ArrayList(3);
   for (int i = 0; i < requiredBundles.length; i++) {
     BundleLoader requiredLoader = requiredBundles[i].getBundleLoader();
     requiredLoader.addExportedProvidersFor(proxy.getSymbolicName(), pkgName, result, visited);
   }
   // found some so cache the result for next time and return
   PackageSource source;
   if (result.size() == 0) {
     // did not find it in our required bundles lets record the failure
     // so we do not have to do the search again for this package.
     source = NullPackageSource.getNullPackageSource(pkgName);
   } else if (result.size() == 1) {
     // if there is just one source, remember just the single source
     source = (PackageSource) result.get(0);
   } else {
     // if there was more than one source, build a multisource and cache that.
     PackageSource[] srcs = (PackageSource[]) result.toArray(new PackageSource[result.size()]);
     source = createMultiSource(pkgName, srcs);
   }
   synchronized (requiredSources) {
     requiredSources.add(source);
   }
   return source.isNullSource() ? null : source;
 }