private void getDataToPlot() {
    switch (position) {
      case 0: // Humidity
        dataToPlot = humidityData;
        min = Collections.min(humidityData);
        max = Collections.max(humidityData);
        break;

      case 1: // Light
        dataToPlot = lightData;
        min = Collections.min(lightData);
        max = Collections.max(lightData);
        break;

      case 2: // Moisture
        dataToPlot = moistureData;
        min = Collections.min(moistureData);
        max = Collections.max(moistureData);
        break;

      case 3: // Temperature
        dataToPlot = temperatureData;
        min = Collections.min(temperatureData);
        max = Collections.max(temperatureData);
        break;
    }
  }
  static void displayStats() {
    if (training_time_stats.size() > 0)
      // TODO format floating point
      System.out.println(
          "Iteration time: min="
              + Collections.min(training_time_stats)
              + ", max="
              + Collections.max(training_time_stats)
              + ", avg="
              + Utils.average(training_time_stats)
              + " seconds");

    if (eval_time_stats.size() > 0)
      System.out.println(
          "Evaluation time: min="
              + Collections.min(eval_time_stats)
              + ", max="
              + Collections.max(eval_time_stats)
              + ", avg="
              + Utils.average(eval_time_stats)
              + " seconds");

    if (compute_fit && fit_time_stats.size() > 0)
      System.out.println(
          "fit_time: min="
              + Collections.min(fit_time_stats)
              + ", max="
              + Collections.max(fit_time_stats)
              + ", avg="
              + Utils.average(fit_time_stats)
              + " seconds");

    System.out.println("Memory: " + Memory.getUsage() + " MB");
  }
  public final String correct(String word) {
    if (nWords.containsKey(word)) return word;
    ArrayList<String> list = edits(word);
    HashMap<Integer, String> candidates = new HashMap<Integer, String>();
    for (String s : list) if (nWords.containsKey(s)) candidates.put(nWords.get(s), s);

    if (candidates.size() > 0) return candidates.get(Collections.max(candidates.keySet()));
    return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet())) : word;
  }
Exemplo n.º 4
0
  public void writeResults(String outputFile) {

    try {
      // Create file
      FileWriter fStream = new FileWriter(outputFile);
      BufferedWriter out = new BufferedWriter(fStream);

      out.write(
          "Attribute Type"
              + SEPARATOR
              + "numberOfDiffValues"
              + SEPARATOR
              + "min"
              + SEPARATOR
              + "max"
              + SEPARATOR
              + "Example\n");
      for (Map.Entry<String, Set<String>> entry : attrByValue.entrySet()) {
        Set<String> attrValues = entry.getValue();
        String lineToWrite = entry.getKey();

        Collections.max(attrValues);

        String sampleValues = "";
        int maxNumberOfSampleValues = 0;

        for (String s : attrValues) {
          sampleValues = sampleValues + " " + s;
          if (maxNumberOfSampleValues > MAX_EXAMPLE_COUNT) break;
          maxNumberOfSampleValues++;
        }

        String max = Collections.max(attrValues);
        String min = Collections.min(attrValues);

        lineToWrite =
            lineToWrite
                + SEPARATOR
                + attrValues.size()
                + SEPARATOR
                + max
                + SEPARATOR
                + min
                + SEPARATOR
                + sampleValues.trim();

        out.write(lineToWrite + "\n");
      }

      out.flush();
      // Close the output stream
      out.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
  public void findStudentResult(String name) {
    System.out.println("Student name:" + name);

    Map<Subject, Double> subjectDoubleMap = new HashMap<>();
    Map<Subject, Integer> subjectIntegerMap = new HashMap<>();

    /**
     * бежим по группам с типом результатов double и ищем студента если есть, то записываем в
     * subjectDoubleMap
     */
    for (Group<Double> indexDGroup : dGroups) {
      if (indexDGroup.getEvalByName(name) == null) {
        continue;
      } else {
        subjectDoubleMap.put(indexDGroup.getSubject(), indexDGroup.getEvalByName(name));
      }
    }
    /*
     * результируюзщий map не пустой, то выводим на экран
     *
     */
    if (!subjectDoubleMap.isEmpty()) {
      System.out.println(subjectDoubleMap);
      double max1 = Collections.max(subjectDoubleMap.values());

      for (Subject s : subjectDoubleMap.keySet()) {
        if (subjectDoubleMap.get(s) == max1) {
          System.out.println(s + ":" + max1);
        }
      }
    }

    /**
     * бежим по группам с типом результатов integer и ищем студента если есть, то записываем в
     * subjectDoubleMap
     */
    for (Group<Integer> indexIGroup : iGroups) {
      if (indexIGroup.getEvalByName(name) == null) {
        continue;
      } else {
        subjectIntegerMap.put(indexIGroup.getSubject(), indexIGroup.getEvalByName(name));
      }
    }
    if (!subjectIntegerMap.isEmpty()) {
      System.out.println(subjectIntegerMap);
      int max2 = Collections.max(subjectIntegerMap.values());
      for (Subject s : subjectIntegerMap.keySet()) {
        if (subjectIntegerMap.get(s) == max2) {
          System.out.println(s + ":" + max2);
        }
      }
    }
  }
Exemplo n.º 6
0
  public static void evaluateCircuitSNR(LogicCircuit lc, Args options) {

    /*for(Gate g: lc.get_logic_gates()) {
        evaluateGateSNR(g, options);
    }
    for(Gate g: lc.get_output_gates()) {
        evaluateGateSNR(g, options);
    }*/

    ArrayList<Double> input_ons = new ArrayList<>();
    ArrayList<Double> input_offs = new ArrayList<>();

    for (Gate input : lc.get_input_gates()) {
      for (int i = 0; i < input.get_logics().size(); ++i) {
        if (input.get_logics().get(i) == 1) {
          input_ons.add(input.get_outreus().get(i));
        } else if (input.get_logics().get(i) == 0) {
          input_offs.add(input.get_outreus().get(i));
        }
      }
    }

    Double input_on_min = Collections.min(input_ons);
    Double input_off_max = Collections.max(input_offs);

    ArrayList<Double> output_ons = new ArrayList<>();
    ArrayList<Double> output_offs = new ArrayList<>();

    for (Gate output : lc.get_output_gates()) {
      for (int i = 0; i < output.get_logics().size(); ++i) {
        if (output.get_logics().get(i) == 1) {
          output_ons.add(output.get_outreus().get(i));
        } else if (output.get_logics().get(i) == 0) {
          output_offs.add(output.get_outreus().get(i));
        }
      }
    }

    Double output_on_min = Collections.min(output_ons);
    Double output_off_max = Collections.max(output_offs);

    Double out_snr =
        20 * Math.log10((Math.log10(output_on_min / output_off_max)) / (2 * Math.log10(3.2)));

    Double in_snr =
        20 * Math.log10((Math.log10(input_on_min / input_off_max)) / (2 * Math.log10(3.2)));

    Double dsnr = out_snr - in_snr;

    lc.get_scores().set_snr(out_snr);
    lc.get_scores().set_dsnr(dsnr);
  }
 public void switchSubtask(@NotNull Document document, int fromSubtask, int toSubtask) {
   Set<Integer> indexes = mySubtaskInfos.keySet();
   int visibleLength = getVisibleLength(fromSubtask);
   if (indexes.contains(toSubtask)) {
     if (!myUseLength) {
       String replacementText = mySubtaskInfos.get(toSubtask).getPossibleAnswer();
       EduUtils.replaceAnswerPlaceholder(document, this, visibleLength, replacementText);
       return;
     }
   }
   Integer minIndex = Collections.min(indexes);
   if (fromSubtask < toSubtask) {
     if (minIndex > fromSubtask && minIndex <= toSubtask) {
       Integer maxIndex =
           Collections.max(ContainerUtil.filter(indexes, integer -> integer <= toSubtask));
       AnswerPlaceholderSubtaskInfo maxInfo = mySubtaskInfos.get(maxIndex);
       String replacementText =
           myUseLength ? maxInfo.getPlaceholderText() : maxInfo.getPossibleAnswer();
       EduUtils.replaceAnswerPlaceholder(document, this, visibleLength, replacementText);
       return;
     }
   }
   if (fromSubtask > toSubtask) {
     if (minIndex > toSubtask && minIndex <= fromSubtask) {
       AnswerPlaceholderSubtaskInfo minInfo = mySubtaskInfos.get(minIndex);
       if (minInfo.isNeedInsertText()) {
         EduUtils.replaceAnswerPlaceholder(document, this, visibleLength, "");
       } else {
         String replacementText = minInfo.getPlaceholderText();
         EduUtils.replaceAnswerPlaceholder(document, this, visibleLength, replacementText);
       }
       return;
     }
     if (indexes.contains(fromSubtask)) {
       List<Integer> filtered = ContainerUtil.filter(indexes, index -> index < fromSubtask);
       if (filtered.isEmpty()) {
         return;
       }
       Integer maxIndex = Collections.max(filtered);
       AnswerPlaceholderSubtaskInfo maxInfo = mySubtaskInfos.get(maxIndex);
       if (maxInfo.isNeedInsertText()) {
         EduUtils.replaceAnswerPlaceholder(document, this, visibleLength, "");
       } else {
         String replacementText =
             myUseLength ? maxInfo.getPlaceholderText() : maxInfo.getPossibleAnswer();
         EduUtils.replaceAnswerPlaceholder(document, this, visibleLength, replacementText);
       }
     }
   }
 }
Exemplo n.º 8
0
  static double getSmirnovDistance(
      Map<Integer, Integer> frequencyTable1, Map<Integer, Integer> frequencyTable2) {
    Map<Integer, Double> cumulMap1 = createCumulativeDistribution(frequencyTable1);
    Object[] keyArray1 = cumulMap1.keySet().toArray();
    Map<Integer, Double> cumulMap2 = createCumulativeDistribution(frequencyTable2);
    Object[] keyArray2 = cumulMap2.keySet().toArray();

    ArrayList<Double> diffList = new ArrayList<Double>();
    int minSize = Math.min(keyArray1.length, keyArray2.length);
    for (int i = 0; i < minSize; i++) {
      diffList.add(
          Math.abs(cumulMap1.get((Integer) keyArray1[i]) - cumulMap2.get((Integer) keyArray2[i])));
    }
    if (keyArray1.length > minSize) {
      for (int i = minSize + 1; i < keyArray1.length; i++) {
        diffList.add(1.0 - cumulMap1.get((Integer) keyArray1[i]));
      }

    } else if (keyArray2.length > minSize) {
      for (int i = minSize + 1; i < keyArray2.length; i++) {
        diffList.add(1.0 - cumulMap2.get((Integer) keyArray2[i]));
      }
    }

    return Collections.max(diffList);
  }
 /**
  * Aggregate all of the {@link FlowExecutionStatus}es of the {@link FlowExecution}s into one
  * status. The aggregate status will be the status with the highest precedence.
  *
  * @see FlowExecutionAggregator#aggregate(Collection)
  */
 @Override
 public FlowExecutionStatus aggregate(Collection<FlowExecution> executions) {
   if (executions == null || executions.size() == 0) {
     return FlowExecutionStatus.UNKNOWN;
   }
   return Collections.max(executions).getStatus();
 }
Exemplo n.º 10
0
  /**
   * Gets the maximum amount of fields a player can place
   *
   * @param player
   * @param fs the field settings of the field you need to get the limit of
   * @return the limit, -1 if no limit
   */
  public int getLimit(Player player, FieldSettings fs) {
    List<Integer> limits = fs.getLimits();

    if (limits.isEmpty()) {
      return -1;
    }

    List<Integer> playersLimits = new ArrayList<Integer>();

    // get all the counts for all limits the player has

    for (int i = limits.size() - 1; i >= 0; i--) {
      if (plugin.getPermissionsManager().has(player, "preciousstones.limit" + (i + 1))) {
        playersLimits.add(limits.get(i));
      }
    }

    // return the highest one

    if (!playersLimits.isEmpty()) {
      return Collections.max(playersLimits);
    }

    return -1;
  }
Exemplo n.º 11
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.º 12
0
  @Test
  public void shouldHaveDifferentNotificationIDs() {
    for (int i = 0; i < 10; i++) {
      this.question.answer(this.andrew, "Answer " + i);
    }
    assertEquals(this.norbert.getNotifications().size(), 10);

    Notification first = Collections.max(this.norbert.getNotifications());
    assertEquals(this.norbert.getNotification(first.id()), first);
    // What is this about and why is it tested here? and #get(9) should
    // equal first?
    assertEquals(this.norbert.getNotifications().get(9), first);

    for (int i = 0; i < 9; i++) {
      assertTrue(
          this.norbert.getNotifications().get(i).id()
              > this.norbert.getNotifications().get(i + 1).id());
    }

    Notification last = Collections.min(this.norbert.getNotifications());
    assertEquals(this.norbert.getNotifications().get(0), last);
    assertEquals(this.norbert.getVeryRecentNewNotification(), last);

    last.unsetNew();
    assertEquals(
        this.norbert.getVeryRecentNewNotification(), this.norbert.getNotifications().get(1));

    assertNull(this.norbert.getNotification(-1));
  }
Exemplo n.º 13
0
  public static void main(String args[]) {
    String os[] = {"GNU/Linux", "Windows 7", "Solaris", "Amiga OS", "FreeBSD", "Mac OS X"};

    LinkedList<String> al_operating_systems =
        new LinkedList<>(Arrays.asList(os)); // Lista di os
    Collections.sort(al_operating_systems); // ordina la collezione
    System.out.print("Collezione ordinata: ");
    System.out.println(al_operating_systems);

    int ix =
        Collections.binarySearch(
            al_operating_systems, "Be OS", null); // ricerca se presente l'elemento Be Os
    if (ix < 0) // se non è presente aggiungilo
    al_operating_systems.add(-(ix + 1), "Be OS");

    System.out.print("Collezione con elemento Be OS aggiunto: ");
    System.out.println(al_operating_systems);

    Collections.rotate(al_operating_systems, 3); // ruota gli elementi di 3 posizioni
    System.out.print("Collezione con elementi ruotati: ");
    System.out.println(al_operating_systems);

    System.out.print("Elemento della collezione minore: ["); // elemento più piccolo
    System.out.println(Collections.min(al_operating_systems) + "]");

    System.out.print("Elemento della collezione maggiore: ["); // elemento più grande
    System.out.println(Collections.max(al_operating_systems) + "]");
  }
Exemplo n.º 14
0
  public String wordTester(IAutoPlayer player, ILexicon lex, ArrayList<Integer> log, int count) {

    BoggleBoardFactory.setRandom(new Random(12345));
    log.clear();
    double start = System.currentTimeMillis();
    int hiScore = 0;
    BoggleBoard hiBoard = null;
    for (int k = 0; k < count; k++) {
      BoggleBoard board = BoggleBoardFactory.getBoard(5);
      player.clear();
      player.findAllValidWords(board, lex, MIN_WORD);
      log.add(player.getScore());
      if (player.getScore() > hiScore) {
        hiScore = player.getScore();
        hiBoard = board;
      }
    }

    double end = System.currentTimeMillis();
    int max = Collections.max(log);
    return String.format(
        "%s %s\t count: %d\tmax: %d\ttime: %f" + hiBoard.toString(),
        player.getClass().getName(),
        lex.getClass().getName(),
        count,
        max,
        (end - start) / 1000.0);
  }
Exemplo n.º 15
0
  private int getTypeOfHousehold(List<Id<Person>> members) {
    // [Single],[Single Parent], [Couple], [Couple with ch], [Complex]
    ArrayList<Integer> ages = new ArrayList<Integer>();

    for (int i = 0; i <= members.size() - 1; i++) {

      Id<Person> m_id = members.get(i);
      int m_age =
          Integer.parseInt(
              (String)
                  microcensus
                      .getHouseholdPersonsAttributes()
                      .getAttribute(m_id.toString(), MZConstants.AGE));
      ages.add(m_age);
    }

    int max_age = Collections.max(ages);

    List<Id<Person>> heads = getHeadsOfHouseholdIds(members, max_age);
    ArrayList<Id<Person>> kids = new ArrayList<Id<Person>>(members);
    kids.removeAll(heads);

    if (members.size() == 1) {
      return 0;
    } else if (heads.size() == 1) {
      return 1;
    } else if (heads.size() == 2 && kids.size() == 0) {
      return 2;
    } else if (heads.size() == 2 && kids.size() != 0) {
      return 3;
    } else {
      return 4;
    }
  }
Exemplo n.º 16
0
 /**
  * Logs the time and the number of needed queries for a specific QSS type
  *
  * @param queries
  * @param times
  * @param type
  * @param statisticName
  */
 private void logStatistics(
     Map<QSSType, List<Double>> queries,
     Map<QSSType, DurationStat> times,
     QSSType type,
     String statisticName) {
   List<Double> queriesOfType = queries.get(type);
   double res = 0;
   for (Double qs : queriesOfType) {
     res += qs;
   }
   logger.info(
       statisticName
           + " needed time "
           + type
           + ": "
           + getStringTime(times.get(type).getOverall())
           + ", max "
           + getStringTime(times.get(type).getMax())
           + ", min "
           + getStringTime(times.get(type).getMin())
           + ", avg2 "
           + getStringTime(times.get(type).getMean())
           + ", Queries max "
           + Collections.max(queries.get(type))
           + ", min "
           + Collections.min(queries.get(type))
           + ", avg2 "
           + res / queriesOfType.size());
 }
Exemplo n.º 17
0
  private static void showHistogram(String label, Map<Integer, Long> data) {
    System.out.println();
    System.out.printf("%s\n===============\n", label);
    Long max = Collections.max(data.values());
    double[] heights = new double[data.size()];
    String[] groupStarts = new String[data.size()];
    int idx = 0;
    for (Entry<Integer, Long> pair : data.entrySet()) {
      heights[idx] = Double.valueOf(pair.getValue()) / Double.valueOf(max) * 10;
      groupStarts[idx] = String.format("%2d ", pair.getKey());
      idx++;
    }
    for (int row = 10; row >= 0; row--) {
      System.out.printf("%5d", max / 10 * row);
      for (int col = 0; col < heights.length; col++) {
        if (heights[col] >= row) {
          System.out.print(" x ");
        } else {
          System.out.print("   ");
        }
      }
      System.out.println();
    }
    System.out.print("     ");
    for (int col = 0; col < groupStarts.length; col++) {
      System.out.print(groupStarts[col]);
    }

    System.out.println();
  }
Exemplo n.º 18
0
  <T extends Number> void test(T num) {

    @SuppressWarnings("unchecked")
    List<T> list =
        new ArrayList<T>((Collection<? extends T>) Arrays.asList(1, 32.4, 54, 23, 45, 2));
    Collections.sort(
        list,
        new Comparator<T>() {

          @Override
          public int compare(T lhs, T rhs) {
            // TODO Auto-generated method stub
            return 0;
          }
        });
    Collections.max(
        list,
        new Comparator<T>() {

          @Override
          public int compare(T lhs, T rhs) {
            // TODO Auto-generated method stub
            return 0;
          }
        });
  };
Exemplo n.º 19
0
 private int getLastIdx() {
   Set<Integer> indices = Sets.newHashSet();
   for (Type type : footer.getTypesList()) {
     indices.addAll(type.getSubtypesList());
   }
   return Collections.max(indices);
 }
Exemplo n.º 20
0
  public static void main(String[] args) {
    // Create a HashMap with three key/value pairs.
    HashMap<String, Integer> hm = new HashMap<String, Integer>();
    hm.put("One", new Integer(1));
    hm.put("Two", new Integer(2));
    hm.put("Three", new Integer(3));
    System.out.println("HashMap:" + hm);
    // Get the value associated with the key "Three".
    Object v = hm.get("Three");
    if (v != null) {
      System.out.println("The value associated with \"Three\" is " + v);
    } else {
      System.out.println("There is no key named \"Three\" " + "in the HashMap.");
    }
    DecimalFormat df = new DecimalFormat("0");
    String a = "$123";
    a = a.replace("$", "");
    System.out.println(a);
    Float x = Float.parseFloat(a);
    System.out.println("Converted Strign to int is " + df.format(x));

    int maxValueInMap = (Collections.max(hm.values())); // This will return max value in the Hashmap
    for (Entry<String, Integer> entry : hm.entrySet()) { // Itrate through hashmap
      if (entry.getValue() == maxValueInMap) {
        System.out.println(entry.getKey()); // Print the key with max value
      }
    }
  }
Exemplo n.º 21
0
 public static void main(String[] args) {
   ArrayList nums = new ArrayList();
   nums.add(2);
   nums.add(-5);
   nums.add(3);
   nums.add(0);
   // 输出:[2, -5, 3, 0]
   System.out.println(nums);
   // 输出最大元素,将输出3
   System.out.println(Collections.max(nums));
   // 输出最小元素,将输出-5
   System.out.println(Collections.min(nums));
   // 将nums中的0使用1来代替
   Collections.replaceAll(nums, 0, 1);
   // 输出:[2, -5, 3, 1]
   System.out.println(nums);
   // 判断-5 在List集合中出现的次数,返回1
   System.out.println(Collections.frequency(nums, -5));
   // 对nums集合排序
   Collections.sort(nums);
   // 输出:[-5, 1, 2, 3]
   System.out.println(nums);
   // 只有排序后的List集合才可用二分法查询,输出3
   System.out.println(Collections.binarySearch(nums, 3));
 }
Exemplo n.º 22
0
 public Integer work(List<Integer> scores, TurnTrackerMinion mule) {
   if (mule.getCurrentMarker().equals(mule.getInitializerMarker())) {
     return Collections.max(scores);
   } else {
     return Collections.min(scores);
   }
 }
Exemplo n.º 23
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int arr[][] = new int[6][6];
    for (int i = 0; i < 6; i++) {
      for (int j = 0; j < 6; j++) {
        arr[i][j] = in.nextInt();
      }
    }

    List sum = new ArrayList();
    for (int i = 1; i < 5; i++) {
      for (int j = 1; j < 5; j++) {
        int temp =
            arr[i][j]
                + arr[i - 1][j - 1]
                + arr[i - 1][j]
                + arr[i - 1][j + 1]
                + arr[i + 1][j - 1]
                + arr[i + 1][j]
                + arr[i + 1][j + 1];
        sum.add(temp);
      }
    }

    System.out.println(Collections.max(sum));
  }
Exemplo n.º 24
0
  private void caracteristicasCamera(
      int width, int height) { // metodo responsavel por atribuir as caracteristicas das cameras

    try {
      for (String cameraId : manager.getCameraIdList()) {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        StreamConfigurationMap map =
            characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (map == null) {
          continue;
        }

        // serve para atribuir o tamanho da imagem
        Size largest =
            Collections.max(
                Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
        imageReader =
            ImageReader.newInstance(
                largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/ 2);
        imageReader.setOnImageAvailableListener(mOnImageAvailableListener, backgroundHandler);

        // textureView.setAspectRatio(
        //       previewSize.getHeight(), previewSize.getWidth());

        return;
      }
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      informaErro
          .newInstance(getString(R.string.camera_error))
          .show(getChildFragmentManager(), FRAGMENT_DIALOG);
    }
  }
Exemplo n.º 25
0
  public ArrayList<String> getPosteriorDecodingPath(
      SingleDPMatrix fMatrix, SingleDPMatrix bMatrix) {
    ArrayList<String> pdPath = new ArrayList<String>();
    State states[] = fMatrix.states();
    double fScore = fMatrix.getScore();
    double fMatrixScores[][] = fMatrix.scores;
    double bMatrixScores[][] = bMatrix.scores;

    int numberOfObservations = fMatrixScores.length;
    int numberOfStates = states.length;
    for (int i = 1; i < numberOfObservations - 1; i++) {
      ArrayList<Double> probOfStates = new ArrayList<Double>();
      for (int s = 0; s < numberOfStates; s++) {
        double probOfOneState = Math.exp(fMatrixScores[i][s] + bMatrixScores[i][s] - fScore);
        probOfStates.add(probOfOneState);
      }
      Object max_obj = Collections.max(probOfStates);
      int maxValueIndex = probOfStates.indexOf(max_obj);
      State topScoredState = states[maxValueIndex];
      pdPath.add(topScoredState.getName());
      // System.out.print(topScoredState.getName());
    }
    // System.out.println();
    // System.out.println("\n number of rows is " + numberOfObservations);
    // System.out.println("\n length of posterior decoding path is " + pdPath.size());
    return pdPath;
  } /*getPosteriorDecodingPath*/
  private void initializeTimeClasses() {
    int endOfTimeClass = 0;
    int classCounter = 0;
    double minTime = Collections.min(allDurDiffs);
    double maxTime = Collections.max(allDurDiffs);

    timeClasses.add(endOfTimeClass);

    while (endOfTimeClass <= maxTime) {
      endOfTimeClass = 100 * (int) Math.pow(2, classCounter);
      classCounter++;
      timeClasses.add(endOfTimeClass);
    }

    endOfTimeClass = 0;
    classCounter = 0;
    while (endOfTimeClass <= -minTime) {
      endOfTimeClass = 100 * (int) Math.pow(2, classCounter);
      classCounter++;
      timeClasses.add(-endOfTimeClass);
    }
    Collections.sort(timeClasses);
    ActivityType2DurationHandler.LOG.info(
        "Following activity duration classes are defined: " + timeClasses.toString());
  }
Exemplo n.º 27
0
 public int getMostWarsInGame(int nbrOfWarsPerBattle) {
   if (nbrOfWarsPerBattle < 0) {
     throw new IllegalArgumentException("Expecting a value of 0 or more.");
   }
   List<Integer> counts = warCounts.get(nbrOfWarsPerBattle);
   return counts == null ? 0 : Collections.max(counts);
 }
 private Set<Integer> getPossibleNumberOfDepartures(
     Set<Integer> unvisitedDays,
     HashMap<Integer, Set<Integer>> individualVesselDeparturePatterns,
     int alreadyVisitedDaysAvailable) {
   int maxDeparturesInPattern =
       Collections.max(
           problemData
               .getVesselDeparturePatterns()
               .keySet()); // the maximum number of departures found in any vessel pattern
   int minimumNumberOfDepartures =
       Math.max(
           0,
           maxDeparturesInPattern
               - alreadyVisitedDaysAvailable); // e.g. if the patterns have max 3 visits and only 1
                                               // day that is already visited can be a part of the
                                               // pattern, the minimum pattern size is 2 (since
                                               // there are 2 unvisited days)
   Set<Integer> allNumberOfDepartures = problemData.getVesselDeparturePatterns().keySet();
   Set<Integer> possibleNumberOfDepartures = new HashSet<Integer>();
   for (Integer numberOfDepartures : allNumberOfDepartures) {
     if (numberOfDepartures >= minimumNumberOfDepartures) {
       possibleNumberOfDepartures.add(numberOfDepartures);
     }
   }
   return possibleNumberOfDepartures;
 }
Exemplo n.º 29
0
 @Nullable
 public static TextRange findNext(
     @NotNull Editor editor,
     @NotNull String pattern,
     final int offset,
     boolean ignoreCase,
     final boolean forwards) {
   final List<TextRange> results =
       findAll(editor, pattern, 0, -1, shouldIgnoreCase(pattern, ignoreCase));
   if (results.isEmpty()) {
     return null;
   }
   final int size = EditorHelper.getFileSize(editor);
   final TextRange max =
       Collections.max(
           results,
           new Comparator<TextRange>() {
             @Override
             public int compare(TextRange r1, TextRange r2) {
               final int d1 = distance(r1, offset, forwards, size);
               final int d2 = distance(r2, offset, forwards, size);
               if (d1 < 0 && d2 >= 0) {
                 return Integer.MAX_VALUE;
               }
               return d2 - d1;
             }
           });
   if (!Options.getInstance().isSet("wrapscan")) {
     final int start = max.getStartOffset();
     if (forwards && start < offset || start >= offset) {
       return null;
     }
   }
   return max;
 }
Exemplo n.º 30
0
 public static void main(String... orange) throws IOException {
   Scanner scan = new Scanner(new File("barn1.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   int bars = scan.nextInt();
   int total = scan.nextInt();
   int have = scan.nextInt();
   ArrayList<Integer> values = new ArrayList<Integer>();
   ArrayList<Integer> locations = new ArrayList<Integer>();
   for (int i = 0; i < have; i++) {
     values.add(scan.nextInt());
   }
   Collections.sort(values);
   int first = values.get(0);
   for (int i = 1; i < have; i++) {
     int current = values.get(i);
     locations.add(current - first);
     first = current;
   }
   if (bars >= have) {
     out.println(have);
   } else {
     for (int i = 0; i < bars - 1; i++) {
       locations.remove(Collections.max(locations));
     }
     int sum = 0;
     for (int i = 0; i < locations.size(); i++) sum += locations.get(i);
     sum += bars;
     out.println(sum);
   }
   out.close();
   System.exit(0);
 }