public Double calculateRating(ArrayList nearestNeighbours, int subjectID, int minOccurences) {
    Double totalSimilarity = 0.0;
    Double totalWeight = 0.0;
    Integer occurenceCounter = 0;
    Iterator<ArrayList<Double>> neighbourIterator = nearestNeighbours.iterator();

    while (neighbourIterator.hasNext()) {
      ArrayList<Double> neighbourMapping = neighbourIterator.next();

      Double neighbourSimilarity = neighbourMapping.get(1);
      try {
        Double neighbourRating =
            getNeighbourRating(userPreferences.get(neighbourMapping.get(0).intValue()), subjectID);
        totalSimilarity += neighbourSimilarity;
        totalWeight += neighbourSimilarity * neighbourRating;
        occurenceCounter++;
      } catch (NullPointerException e) {
        // if the subject isn't found, skip
        continue;
      }
    }

    if (occurenceCounter < minOccurences) {
      return null;
    }
    return totalWeight / totalSimilarity;
  }
Exemplo n.º 2
0
  private void handleNewExternalTransactionsInt(Collection<TransactionEx> transactions)
      throws WapiException {
    // Transform and put into two arrays with matching indexes
    ArrayList<TransactionEx> texArray = new ArrayList<TransactionEx>(transactions.size());
    ArrayList<Transaction> txArray = new ArrayList<Transaction>(transactions.size());
    for (TransactionEx tex : transactions) {
      try {
        txArray.add(Transaction.fromByteReader(new ByteReader(tex.binary)));
        texArray.add(tex);
      } catch (TransactionParsingException e) {
        // We hit a transaction that we cannot parse. Log but otherwise ignore it
        _logger.logError("Received transaction that we cannot parse: " + tex.txid.toString());
        continue;
      }
    }

    // Grab and handle parent transactions
    fetchStoreAndValidateParentOutputs(txArray);

    // Store transaction locally
    for (int i = 0; i < txArray.size(); i++) {
      _backing.putTransaction(texArray.get(i));
      onNewTransaction(texArray.get(i), txArray.get(i));
    }
  }
Exemplo n.º 3
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();
    }
  }
  protected double getAUCLoss(ArrayList<AUCPoint> aucPoints) {
    // order by false positive rate ascending, true positive rate ascending
    Collections.sort(
        aucPoints,
        new Comparator<AUCPoint>() {
          @Override
          public int compare(AUCPoint o1, AUCPoint o2) {
            if (o1.getFalsePositiveRate() > o2.getFalsePositiveRate()) {
              return 1;
            } else if (o1.getFalsePositiveRate() < o2.getFalsePositiveRate()) {
              return -1;
            } else {
              return o1.getTruePositiveRate() >= o2.getTruePositiveRate() ? 1 : -1;
            }
          }
        });

    double sumXY = 0.0;
    // Area over curve OR AUCLoss = (2 - sum((x1-x0)(y1+y0)))/2
    for (int i = 1; i < aucPoints.size(); i++) {
      AUCPoint aucPoint1 = aucPoints.get(i);
      AUCPoint aucPoint0 = aucPoints.get(i - 1);
      sumXY +=
          ((aucPoint1.getFalsePositiveRate() - aucPoint0.getFalsePositiveRate())
              * (aucPoint1.getTruePositiveRate() + aucPoint0.getTruePositiveRate()));
    }
    return (2.0 - sumXY) / 2.0;
  }
Exemplo n.º 5
0
 /**
  * Given a tissue sample, move all unsatisfied agents to a vacant cell
  *
  * @param tissue a 2-D character array that has been initialized
  * @param threshold the percentage of like agents that must surround the agent to be satisfied
  */
 public static int moveAllUnsatisfied(char[][] tissue, int threshold) {
   ArrayList<Integer> list2 = new ArrayList<Integer>();
   int counter = 0;
   ArrayList<Integer> list1 = new ArrayList<Integer>();
   for (int i = 0; i < tissue.length; i++) {
     for (int x = 0; x < tissue[0].length; x++) {
       if (isSatisfied(tissue, i, x, threshold) == false) {
         list1.add(i);
         list2.add(x);
       }
     }
   }
   int num = list1.size();
   char temp;
   int count = 0;
   do {
     int rand = (int) (Math.random() * tissue.length);
     int random = (int) (Math.random() * tissue.length);
     if (tissue[rand][random] == ' ') {
       temp = tissue[rand][random];
       tissue[rand][random] = tissue[list1.get(counter)][list2.get(counter)];
       tissue[list1.get(counter)][list2.get(counter)] = temp;
       counter++;
       count++;
     }
   } while (counter != num);
   return count;
 }
Exemplo n.º 6
0
  private void fixReferencesToStatic(PsiElement classMember) throws IncorrectOperationException {
    final StaticReferencesCollector collector = new StaticReferencesCollector();
    classMember.accept(collector);
    ArrayList<PsiJavaCodeReferenceElement> refs = collector.getReferences();
    ArrayList<PsiElement> members = collector.getReferees();
    ArrayList<PsiClass> classes = collector.getRefereeClasses();
    PsiElementFactory factory =
        JavaPsiFacade.getInstance(classMember.getProject()).getElementFactory();

    for (int i = 0; i < refs.size(); i++) {
      PsiJavaCodeReferenceElement ref = refs.get(i);
      PsiElement namedElement = members.get(i);
      PsiClass aClass = classes.get(i);

      if (namedElement instanceof PsiNamedElement) {
        PsiReferenceExpression newRef =
            (PsiReferenceExpression)
                factory.createExpressionFromText(
                    "a." + ((PsiNamedElement) namedElement).getName(), null);
        PsiExpression qualifierExpression = newRef.getQualifierExpression();
        assert qualifierExpression != null;
        qualifierExpression =
            (PsiExpression) qualifierExpression.replace(factory.createReferenceExpression(aClass));
        qualifierExpression.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified());
        ref.replace(newRef);
      }
    }
  }
  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);
    }
  }
Exemplo n.º 8
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();
  }
Exemplo n.º 9
0
 public Routine() {
   timer = new Timer();
   timer.scheduleAtFixedRate(new ScheduleTask(), 100, 30);
   balls = new ArrayList<>();
   for (int i = 0; i < 20; i++) {
     balls.add(
         new BouncingBall(
             20,
             new Color((int) (0xFFFFFF * Math.random())),
             new WstPoint(Math.random() * Ballz.FRAME_WIDTH, Math.random() * Ballz.FRAME_HEIGHT)));
   }
   for (int i = 0; i < 40; i++) {
     balls.add(
         new JoggingBall(
             5, balls.get((int) (Math.random() * 20)), new Color(0xFFFFFF), Math.random() * 0.2));
   }
   for (int i = 0; i < 10; i++) {
     balls.add(
         new JoggingBall(
             3,
             balls.get((int) (Math.random() * 40 + 20)),
             new Color(0x333333),
             Math.random() * 0.2));
   }
 }
Exemplo n.º 10
0
 private boolean isValid(ArrayList<ScumCard> c) // returns if the move (c) is a valid move
     {
   if (c == null) // if null, the player intends to skip their turn
   {
     // System.out.println(" Skipping your turn...");
     return true;
   }
   if (c.size() != numCardsPlay
       && numCardsPlay != 0) // if the not the correct number of cards, return false
   {
     System.err.println("not enough cards");
     return false;
   }
   if (c.size() > 1) // checks if the multi card play has cards of the same value
   for (int x = 0; x < c.size() - 1; x++)
       if (c.get(x).compareToIgnoreSuit(c.get(x + 1)) != 0) {
         System.err.println("not same cards");
         return false;
       }
   if (discardPile.size() != 0
       && discardPile.get(discardPile.size() - 1).compareToIgnoreSuit(c.get(0))
           >= 0) // checks if the card played is of greater value than the top of discard pile
   {
     System.err.println("lesser value played");
     return false;
   }
   return true;
 }
Exemplo n.º 11
0
  /**
   * Creates a new Game instance*
   *
   * @param p1Id the id of the first player
   * @param p2Id the id of the second player
   * @return a new game instance
   */
  private IGame createGame(String p1Id, String p2Id) {

    String gid = UUID.randomUUID().toString();

    ArrayList<Integer> shuffleArray = new ArrayList<>();
    for (int i = 0; i < 52; i++) {
      shuffleArray.add(i);
    }
    Collections.shuffle(shuffleArray);

    int split = shuffleArray.size() / 2;
    Queue<Integer> player1Cards = new LinkedList<>();
    for (int i = 0; i < split; i++) {
      player1Cards.add(shuffleArray.get(i));
    }

    Queue<Integer> player2Cards = new LinkedList<>();
    for (int i = split; i < shuffleArray.size(); i++) {
      player2Cards.add(shuffleArray.get(i));
    }
    Game game = new Game(gid, p1Id, p2Id, player1Cards, player2Cards);
    games.put(gid, game);

    return game;
  }
Exemplo n.º 12
0
  private void setupRound() // sets up each round right before game time
      {
    reset(); // resets and deals the card related variables
    skippedPlayers = 0; // resets the skipped players
    if (firstRound) // if this is the first round -- find the 3 of clubs holder
    {
      firstRound = false;
      currentPlayer = findThreeClubs();
    } else // if not -- trade the cards and set the first player as the president
    {
      trade(players.get(findPresident()), players.get(findScum()));
      trade(players.get(findPresident()), players.get(findScum()));
      trade(players.get(findVice()), players.get(findViceScum()));
      currentPlayer = findPresident();
      // System.out.println(players.get(currentPlayer));
    }

    /*
    for (Player p : players)
    {
        System.out.println(p);
        System.out.println();
    }
    */

    for (Player p : players) // reset the rank of each player
    {
      p.setRank(-10);
    }
  }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
Exemplo n.º 14
0
 public String printTree() {
   String returnstring = "";
   for (int i = 0; i < stack.size(); i++)
     if (stack.get(i) instanceof Node) returnstring += ((Node) stack.get(i)).printTree();
     else returnstring += stack.get(i).toString();
   return returnstring;
 }
  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;
  }
 @Test
 public void ataqueDe10ElfosNoturnosA10AnosSo3AtacamE29AnoesRecebemAtaques() {
   ExercitoDeElfos exercito = new ExercitoDeElfos();
   ArrayList<Dwarf> dwarves = new ArrayList<Dwarf>();
   for (int i = 0; i < 10; i++) {
     dwarves.add(new Dwarf("" + i));
     exercito.alistarElfo(new ElfoNoturno("" + i));
   }
   exercito.reunirElfosVivoEAtacarDwarves(dwarves);
   for (int i = 0; i < 10; i++) {
     if (i == 9) {
       assertEquals(90.0, dwarves.get(i).getVida(), .0);
       break;
     }
     assertEquals(80.0, dwarves.get(i).getVida(), .0);
   }
   exercito.reunirElfosVivoEAtacarDwarves(dwarves);
   for (int i = 0; i < 10; i++) {
     if (i == 9) {
       assertEquals(70.0, dwarves.get(i).getVida(), .0);
       break;
     }
     assertEquals(60.0, dwarves.get(i).getVida(), .0);
   }
 }
  public static ArrayList<TaggedWord> StopWordRemoval(ArrayList<TaggedWord> taggedWords) {
    ArrayList<TaggedWord> newList = new ArrayList<TaggedWord>();

    try {
      String path = "data/nltk_stoplist.txt";
      File textFile = new File(path);
      BufferedReader br = new BufferedReader(new FileReader(textFile));
      String stopwordsLine = br.readLine();
      br.close();

      String[] stopwords = stopwordsLine.split(",");
      HashMap<String, String> stopwordsDict = new HashMap<String, String>();
      for (int i = 0; i < stopwords.length; i++) {
        stopwordsDict.put(stopwords[i], stopwords[i]);
      }

      for (int i = 0; i < taggedWords.size(); i++) {
        String word = taggedWords.get(i).word();
        String posTag = taggedWords.get(i).tag();

        if (!stopwordsDict.containsKey(word.toLowerCase())) {
          String newWord, newPosTag;
          newWord = word;
          newPosTag = posTag;
          newList.add(new TaggedWord(newWord, newPosTag));
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return newList;
  }
Exemplo n.º 18
0
  /**
   * Applies a list of transformation on a block, if the block is not protected.
   *
   * @param toTransform the Bukkit block object to transform
   * @param transformations the list if transformations to apply
   */
  public static void transform(Block toTransform, List<List<String>> transformations) {
    if (isBlockProtected(toTransform)) {
      return;
    }

    for (List<String> toCheck : transformations) {
      ArrayList<String[]> stateIndex = new ArrayList<String[]>();

      for (int i = 0; i != 2; ++i) {
        String got = toCheck.get(i);

        if (got.contains(":")) { // Check for data _ appended.
          stateIndex.add(got.split(":"));
        } else {
          stateIndex.add(new String[] {got, "0"});
        }
      }

      String[] curState = stateIndex.get(0), toState = stateIndex.get(1);

      if (Integer.valueOf(curState[0]) == toTransform.getTypeId()
          && Integer.valueOf(curState[1]) == toTransform.getData()) {
        toTransform.setTypeIdAndData(Integer.valueOf(toState[0]), Byte.parseByte(toState[1]), true);
        return;
      }
    }
  }
Exemplo n.º 19
0
    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;

    }
Exemplo n.º 20
0
  public int countBlack(String ballSequence, int repetitions) {
    for (int i = 0; i < ballSequence.length(); i++) {
      if (ballSequence.charAt(i) == 'B') fballs.add(1);
      else fballs.add(0);
    }

    for (int i = 0; i < repetitions; i++) {
      balls.addAll(fballs);
    }
    end = balls.size() - 1;
    int c = 0;
    while (start <= end) {
      if (reversed == -1) {
        if ((inverted == -1 && balls.get(start) == 1) || (inverted == 1 && balls.get(start) == 0)) {
          start++;
          c++;
          inverted *= -1;
        } else {
          start++;
          reversed *= -1;
        }
      } else {
        if ((inverted == -1 && balls.get(end) == 1) || (inverted == 1 && balls.get(end) == 0)) {
          start++;
          end--;
          c++;
          inverted *= -1;
        } else {
          end--;
          reversed *= -1;
        }
      }
    }
    return c;
  }
  /**
   * This method will read the bill info from the database and return the whole set in a properly
   * formatted arraylist in order to be displayed in the report jtable of the program
   */
  protected void readDBReport() {

    super.runQuery(sql1);
    ArrayList results = this.getIds();
    if (results.isEmpty()) {
      System.out.println("result set is empty. Dump database operation aborted");
      results = new ArrayList();
      // System.exit(1);

    } else {

      for (int i = 0; i < results.size(); i += 8) {
        // with ids
        String[] row = {
          (String) results.get(i),
          (String) results.get(i + 1),
          (String) results.get(i + 2),
          (String) results.get(i + 3),
          (String) results.get(i + 4),
          (String) results.get(i + 5),
          (String) results.get(i + 6),
          (String) results.get(i + 7)
        };

        rows.add(row);
      }
    }
  }
Exemplo n.º 22
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);
  }
Exemplo n.º 23
0
 public static void main(String[] args) throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("barn1.in"));
   out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   StringTokenizer nstr = new StringTokenizer(f.readLine());
   int m = Integer.parseInt(nstr.nextToken());
   int s = Integer.parseInt(nstr.nextToken());
   occupied = new ArrayList<ArrayList<Integer>>();
   occupied.add(new ArrayList<Integer>());
   for (int i = 0; i < s; i++) {
     try {
       nstr = new StringTokenizer(f.readLine());
       occupied.get(0).add(Integer.parseInt(nstr.nextToken()));
     } catch (NullPointerException e) {
       break;
     }
   }
   Collections.sort(occupied.get(0));
   int bound = m - 1;
   if (occupied.get(0).size() - 1 < bound) {
     bound = occupied.get(0).size() - 1;
   }
   for (int i = 0; i < bound; i++) {
     findMaxCut();
   }
   int total = 0;
   int len = occupied.size();
   for (int i = 0; i < len; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len2 = arr.size();
     total += arr.get(len2 - 1) - arr.get(0) + 1;
   }
   out.println(total);
   out.close();
   System.exit(0);
 }
Exemplo n.º 24
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;
  }
  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);
  }
Exemplo n.º 26
0
 private int min(ArrayList<Integer> points) {
   int res = points.get(0);
   for (int i = 1; i < points.size(); i++) {
     res = Math.min(res, points.get(i));
   }
   return res;
 }
Exemplo n.º 27
0
  private void updateVpInfo() {

    String key;
    String vps;
    for (int j = 0; j < keys.size(); j++) {
      key = (String) keys.get(j);
      vps = (String) vpInfo.get(j);
      if (vps == null || vps.length() <= 0 || vps.equals("all")) {
        for (int i = 0; i < nviews; i++) {
          tp_paneInfo[i].put(key, "yes");
        }
      } else {
        for (int i = 0; i < nviews; i++) tp_paneInfo[i].put(key, "no");
        StringTokenizer tok = new StringTokenizer(vps, " ,\n");
        while (tok.hasMoreTokens()) {
          int vp = Integer.valueOf(tok.nextToken()).intValue();
          vp--;
          if (vp >= 0 && vp < nviews) {
            tp_paneInfo[vp].remove(key);
            tp_paneInfo[vp].put(key, "yes");
          }
        }
      }
    }
  }
Exemplo n.º 28
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;
 }
 public void init() {
   Scanner scan = new Scanner(System.in);
   count = scan.nextInt();
   x0 = scan.nextLong();
   y0 = scan.nextLong();
   int result = 0;
   boolean special = false;
   for (int i = 0; i < count; i++) {
     long tempx = scan.nextLong();
     long tempy = scan.nextLong();
     if (tempx == x0 && tempy == y0) {
       special = true;
       continue;
     }
     boolean isDuplicate = false;
     for (int j = 0; j < result; j++) {
       long x1 = xList.get(j);
       long y1 = yList.get(j);
       if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) {
         isDuplicate = true;
         break;
       }
     }
     if (!isDuplicate) {
       xList.add(tempx);
       yList.add(tempy);
       result++;
     }
   }
   if (special && result == 0) result = 1;
   System.out.println(result);
   scan.close();
 }
Exemplo n.º 30
0
 /*
  * Takes a set of sketch nodes, and returns an ArrayList<Integer> such that
  * arr.get(i) gives the index of the sketch node that node i is closest too.
  *
  * Need to work the return values a little bit. Make a proper data
  * structure.
  */
 public ArrayList<ArrayList<Integer>> distSketch(int len, Counter sketchNodes) {
   ArrayList<Integer> closestIndex = new ArrayList<Integer>();
   for (int i = 0; i < len; i++) closestIndex.set(i, -1);
   ArrayList<Double> closestDist = new ArrayList<Double>();
   for (int i = 0; i < len; i++) closestDist.set(i, Double.MAX_VALUE);
   ArrayList<ArrayList<Integer>> sketchReverseIndex = new ArrayList<ArrayList<Integer>>();
   for (int index : sketchNodes.keySet()) {
     Counter distances = this.bfs(index);
     for (int j = 0; j < len; j++) {
       double curDist = closestDist.get(j);
       double dist = distances.getPath(index);
       if (dist < curDist) {
         closestIndex.set(j, index);
       }
     }
     sketchReverseIndex.add(new ArrayList<Integer>());
   }
   for (int j = 0; j < len; j++) {
     int closest = closestIndex.get(j);
     sketchReverseIndex.get(closest).add(j);
   }
   // Return sketchReverseIndex, closestIndex forward index, and index
   // correspondence bimap
   return sketchReverseIndex;
 }