コード例 #1
1
ファイル: anarc05b.java プロジェクト: sherlockholms/SPOJ
 public static void main(String[] args) throws IOException {
   in = new Reader();
   out = new PrintWriter(System.out, true);
   for (; ; ) {
     int n = in.nextInt();
     if (n == 0) break;
     int[] arr1 = new int[n];
     for (int i = 0; i < n; i++) arr1[i] = in.nextInt();
     int m = in.nextInt();
     int[] arr2 = new int[m];
     for (int i = 0; i < m; i++) arr2[i] = in.nextInt();
     int idx1 = 0, idx2 = 0, sum1 = 0, sum2 = 0, sum = 0;
     for (; ; ) {
       sum1 += arr1[idx1];
       while (idx2 < m && arr1[idx1] > arr2[idx2]) sum2 += arr2[idx2++];
       if (idx2 == m) {
         idx1++;
         break;
       }
       if (arr1[idx1] == arr2[idx2]) {
         sum2 += arr2[idx2++];
         sum += Math.max(sum1, sum2);
         sum1 = sum2 = 0;
       }
       idx1++;
       if (idx1 == n) break;
     }
     while (idx1 < n) sum1 += arr1[idx1++];
     while (idx2 < m) sum2 += arr2[idx2++];
     sum += Math.max(sum1, sum2);
     out.println(sum);
   }
 }
コード例 #2
0
 /**
  * Skip bytes. This method will block until some bytes are available, an I/O error occurs, or
  * the end of the stream is reached.
  *
  * @param n The number of bytes to skip
  * @return The number of bytes actually skipped
  * @throws IllegalArgumentException if n is negative.
  * @throws IOException if the stream is closed.
  * @since ostermillerutils 1.00.00
  */
 @Override
 public long skip(long n) throws IOException, IllegalArgumentException {
   while (true) {
     synchronized (CircularByteBuffer.this) {
       if (inputStreamClosed)
         throw new IOException(
             "InputStream has been closed; cannot skip bytes on a closed InputStream.");
       int available = CircularByteBuffer.this.available();
       if (available > 0) {
         int length = Math.min((int) n, available);
         int firstLen = Math.min(length, buffer.length - readPosition);
         int secondLen = length - firstLen;
         if (secondLen > 0) {
           readPosition = secondLen;
         } else {
           readPosition += length;
         }
         if (readPosition == buffer.length) {
           readPosition = 0;
         }
         ensureMark();
         return length;
       } else if (outputStreamClosed) {
         return 0;
       }
     }
     try {
       Thread.sleep(100);
     } catch (Exception x) {
       throw new IOException("Blocking read operation interrupted.");
     }
   }
 }
コード例 #3
0
ファイル: PlanetWars.java プロジェクト: DaRaFF/aicontest
 // Returns the distance between two planets, rounded up to the next highest
 // integer. This is the number of discrete time steps it takes to get
 // between the two planets.
 public int Distance(int sourcePlanet, int destinationPlanet) {
   Planet source = planets.get(sourcePlanet);
   Planet destination = planets.get(destinationPlanet);
   double dx = source.X() - destination.X();
   double dy = source.Y() - destination.Y();
   return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
 }
コード例 #4
0
ファイル: Silver.java プロジェクト: codding-buddha/spoj
 public double nextDouble() {
   int c = read();
   while (isSpaceChar(c)) c = read();
   int sgn = 1;
   if (c == '-') {
     sgn = -1;
     c = read();
   }
   double res = 0;
   while (!isSpaceChar(c) && c != '.') {
     if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt());
     if (c < '0' || c > '9') throw new InputMismatchException();
     res *= 10;
     res += c - '0';
     c = read();
   }
   if (c == '.') {
     c = read();
     double m = 1;
     while (!isSpaceChar(c)) {
       if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt());
       if (c < '0' || c > '9') throw new InputMismatchException();
       m /= 10;
       res += (c - '0') * m;
       c = read();
     }
   }
   return res * sgn;
 }
コード例 #5
0
ファイル: Params.java プロジェクト: flannelbum/GiantTrees
  public double getShapeRatio(double ratio, int shape) {

    switch (shape) {
        // case CONICAL: return 0.2+0.8*ratio;
        // need real conical shape for lark, fir, etc.
      case CONICAL:
        return ratio; // FIXME: this would be better: 0.05+0.95*ratio; ?
      case SPHERICAL:
        return 0.2 + 0.8 * Math.sin(Math.PI * ratio);
      case HEMISPHERICAL:
        return 0.2 + 0.8 * Math.sin(0.5 * Math.PI * ratio);
      case CYLINDRICAL:
        return 1.0;
      case TAPERED_CYLINDRICAL:
        return 0.5 + 0.5 * ratio;
      case FLAME:
        return ratio <= 0.7 ? ratio / 0.7 : (1 - ratio) / 0.3;
      case INVERSE_CONICAL:
        return 1 - 0.8 * ratio;
      case TEND_FLAME:
        return ratio <= 0.7 ? 0.5 + 0.5 * ratio / 0.7 : 0.5 + 0.5 * (1 - ratio) / 0.3;
      case ENVELOPE:
        if (ratio < 0 || ratio > 1) {
          return 0;
        } else if (ratio < (1 - PruneWidthPeak)) {
          return Math.pow(ratio / (1 - PruneWidthPeak), PrunePowerHigh);
        } else {
          return Math.pow((1 - ratio) / (1 - PruneWidthPeak), PrunePowerLow);
        }
        // tested in prepare() default: throw new ErrorParam("Shape must be between 0 and 8");
    }
    return 0; // shouldn't reach here
  }
コード例 #6
0
 void go3(int x, int y, int v, int at) {
   if (at == -1) return;
   if (y < a[at] || x > b[at]) return;
   val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1) * v;
   go3(x, y, v, left[at]);
   go3(x, y, v, right[at]);
 }
コード例 #7
0
ファイル: LevelScene.java プロジェクト: Califax/MavenMarioAI
  private void renderBlackout(Graphics g, int x, int y, int radius) {
    if (radius > 320) return;

    int[] xp = new int[20];
    int[] yp = new int[20];
    for (int i = 0; i < 16; i++) {
      xp[i] = x + (int) (Math.cos(i * Math.PI / 15) * radius);
      yp[i] = y + (int) (Math.sin(i * Math.PI / 15) * radius);
    }
    xp[16] = 320;
    yp[16] = y;
    xp[17] = 320;
    yp[17] = 240;
    xp[18] = 0;
    yp[18] = 240;
    xp[19] = 0;
    yp[19] = y;
    g.fillPolygon(xp, yp, xp.length);

    for (int i = 0; i < 16; i++) {
      xp[i] = x - (int) (Math.cos(i * Math.PI / 15) * radius);
      yp[i] = y - (int) (Math.sin(i * Math.PI / 15) * radius);
    }
    xp[16] = 320;
    yp[16] = y;
    xp[17] = 320;
    yp[17] = 0;
    xp[18] = 0;
    yp[18] = 0;
    xp[19] = 0;
    yp[19] = y;

    g.fillPolygon(xp, yp, xp.length);
  }
コード例 #8
0
ファイル: CombStat.java プロジェクト: vrodic/Clus
 /**
  * Calculates the difference
  *
  * @return difference
  */
 public double prototypeDifference(CombStat stat) {
   double sumdiff = 0;
   double weight;
   // Numeric atts: abs difference
   for (int i = 0; i < m_RegStat.getNbNumericAttributes(); i++) {
     weight = m_StatManager.getClusteringWeights().getWeight(m_RegStat.getAttribute(i));
     sumdiff += Math.abs(prototypeNum(i) - stat.prototypeNum(i)) * weight;
     // System.err.println("sumdiff: " + Math.abs(prototypeNum(i) - stat.prototypeNum(i)) *
     // weight);
   }
   // Nominal atts: Manhattan distance
   for (int i = 0; i < m_ClassStat.getNbNominalAttributes(); i++) {
     weight = m_StatManager.getClusteringWeights().getWeight(m_ClassStat.getAttribute(i));
     double sum = 0;
     double[] proto1 = prototypeNom(i);
     double[] proto2 = stat.prototypeNom(i);
     for (int j = 0; j < proto1.length; j++) {
       sum += Math.abs(proto1[j] - proto2[j]);
     }
     sumdiff += sum * weight;
     // System.err.println("sumdiff: " + (sum * weight));
   }
   // System.err.println("sumdiff-total: " + sumdiff);
   return sumdiff != 0 ? sumdiff : 0.0;
 }
コード例 #9
0
 private long calculateExpiry(
     URLConnection urlConnection,
     long request_time,
     UrlConnectionExpiryCalculator urlConnectionExpiryCalculator) {
   if ("no-cache".equals(urlConnection.getHeaderField("Pragma"))) {
     return 0L;
   }
   final String cacheControl = urlConnection.getHeaderField("Cache-Control");
   if (cacheControl != null) {
     if (cacheControl.indexOf("no-cache") != -1) {
       return 0L;
     }
     final int max_age = getMaxAge(cacheControl);
     if (-1 != max_age) {
       final long response_time = System.currentTimeMillis();
       final long apparent_age = Math.max(0, response_time - urlConnection.getDate());
       final long corrected_received_age =
           Math.max(apparent_age, urlConnection.getHeaderFieldInt("Age", 0) * 1000L);
       final long response_delay = response_time - request_time;
       final long corrected_initial_age = corrected_received_age + response_delay;
       final long creation_time = response_time - corrected_initial_age;
       return max_age * 1000L + creation_time;
     }
   }
   final long explicitExpiry = urlConnection.getHeaderFieldDate("Expires", -1L);
   if (explicitExpiry != -1L) {
     return explicitExpiry;
   }
   return urlConnectionExpiryCalculator == null
       ? 0L
       : urlConnectionExpiryCalculator.calculateExpiry(urlConnection);
 }
コード例 #10
0
  @Override
  public void trainMostSimilar(List<EnsembleSim> simList) {
    if (simList.isEmpty()) {
      throw new IllegalStateException("no examples to train on!");
    }
    mostSimilarInterpolator.trainMostSimilar(simList);

    // Remove things that have no observed metrics
    List<EnsembleSim> pruned = new ArrayList<EnsembleSim>();
    for (EnsembleSim es : simList) {
      if (es != null && es.getNumMetricsWithScore() > 0) {
        pruned.add(es);
      }
    }

    double[][] X = new double[pruned.size()][numMetrics * 2];
    double[] Y = new double[pruned.size()];
    for (int i = 0; i < pruned.size(); i++) {
      Y[i] = pruned.get(i).knownSim.similarity;
      EnsembleSim es = mostSimilarInterpolator.interpolate(pruned.get(i));
      for (int j = 0; j < numMetrics; j++) {
        X[i][2 * j] = es.getScores().get(j);
        X[i][2 * j + 1] = Math.log(es.getRanks().get(j) + 1);
      }
    }

    OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
    regression.newSampleData(Y, X);

    mostSimilarCoefficients = new TDoubleArrayList(regression.estimateRegressionParameters());
    double pearson = Math.sqrt(regression.calculateRSquared());
    LOG.info("coefficients are " + mostSimilarCoefficients.toString());
    LOG.info("pearson for multiple regression is " + pearson);
  }
コード例 #11
0
  /* Function for calculating laplacePerTerm for individual query terms */
  public static double laplacePerTerm(
      String termFreq, double docLen, double avgLen, long vocabSize, int queryWords) {

    // System.out.println("Query Words:::");

    String[] termFs = termFreq.split(" ");

    // System.out.println("TermFs::: "+ termFreq);

    double log_p_lap = 0.0;

    /*
     * if(termFs.length <= queryWords){
     *
     * for(int j=0;j<(queryWords-termFs.length); j++){ log_p_lap +=
     * Math.log(((0 + 1) / (docLen + vocabSize)); } log_p_lap+= (Math.log((0
     * + 1) / (docLen + vocabSize))) * (queryWords - termFs.length);
     *
     * }
     */
    if (termFs.length < queryWords) {
      log_p_lap += (Math.log((0 + 1) / (docLen + vocabSize))) * (queryWords - termFs.length);
    }

    for (int i = 0; i < termFs.length; i++) {

      log_p_lap += Math.log(((Integer.parseInt(termFs[i])) + 1) / (docLen + vocabSize));
    }

    return log_p_lap;
  }
コード例 #12
0
 private Rectangle layoutRects() {
   int limit = helpers.size();
   int visiCount = 0;
   int maxHeight = 50;
   int maxWidth = 50;
   int nextVisibleCol = Integer.MAX_VALUE;
   for (int i = 0; i < limit; i++) {
     TDHelper thisHelper = helpers.elementAt(i);
     if (thisHelper.indentation > nextVisibleCol) {
       thisHelper.drawRect = null;
       continue;
     }
     if (thisHelper.subsVisible) {
       nextVisibleCol = Integer.MAX_VALUE;
     } else {
       nextVisibleCol = thisHelper.indentation;
     }
     thisHelper.layoutRect(visiCount, thisHelper.indentation, auxData);
     visiCount++;
     maxWidth = Math.max(maxWidth, thisHelper.drawRect.x + thisHelper.drawRect.width);
     maxHeight = Math.max(maxHeight, thisHelper.drawRect.y + thisHelper.drawRect.height);
   }
   Rectangle rtnVal =
       new Rectangle(maxWidth + TDHelper.rowPixelBase, maxHeight + TDHelper.colPixelBase);
   this.setSize(Math.max(500, rtnVal.width), Math.max(500, rtnVal.height));
   return rtnVal;
 }
コード例 #13
0
ファイル: C45.java プロジェクト: Navieclipse/KEEL
  /**
   * Updates all the statistics for the current itemset.
   *
   * @param predictedClassification Distribution of class values predicted for the itemset.
   * @param itemset The itemset.
   * @param nClasses The number of classes.
   */
  private void updateStats(double[] predictedClassification, Itemset itemset, int nClasses) {
    int actualClass = (int) itemset.getClassValue();

    if (!itemset.classIsMissing()) {
      updateMargins(predictedClassification, actualClass, nClasses);

      // Determine the predicted class (doesn't detect multiple classifications)
      int predictedClass = -1;
      double bestProb = 0.0;

      for (int i = 0; i < nClasses; i++) {
        if (predictedClassification[i] > bestProb) {
          predictedClass = i;
          bestProb = predictedClassification[i];
        }
      }

      // Update counts when no class was predicted
      if (predictedClass < 0) {
        return;
      }

      double predictedProb = Math.max(Double.MIN_VALUE, predictedClassification[actualClass]);
      double priorProb =
          Math.max(Double.MIN_VALUE, priorsProbabilities[actualClass] / classPriorsSum);
    }
  }
コード例 #14
0
  private static void solve(int[][] points) {
    int N = points.length;
    int W = (1 << N);
    int[][] dp = new int[N][W];
    int[][] masks = new int[N][N];
    int[][] areas = new int[N][N];
    makeMasksAndAreas(points, masks, areas);

    for (int i = 0; i < N; i++) {
      Arrays.fill(dp[i], Integer.MAX_VALUE);
    }

    dp[0][0] = 0;

    for (int i = 1; i < N; i++) {
      for (int state = 0; state < W; state++) {
        if (dp[i - 1][state] == Integer.MAX_VALUE) continue;
        for (int a = 0; a < N; a++) {
          for (int b = a + 1; b < N; b++) {
            int mask = masks[a][b];
            if ((mask | state) == state) continue;

            dp[i][mask | state] = Math.min(dp[i][mask | state], dp[i - 1][state] + areas[a][b]);
          }
        }
      }
    }

    int res = Integer.MAX_VALUE;
    for (int i = 0; i < N; i++) {
      res = Math.min(res, dp[i][W - 1]);
    }

    System.out.println(res);
  }
コード例 #15
0
ファイル: c.java プロジェクト: ysyshtc/Codeforces
  void run() {
    InputReader in = new InputReader(System.in);
    PrintWriter out = new PrintWriter(System.out);

    int n = in.nextInt(), q = in.nextInt();
    int[] v = new int[n], c = new int[n];
    for (int i = 0; i < n; ++i) v[i] = in.nextInt();
    for (int i = 0; i < n; ++i) c[i] = in.nextInt();

    for (int i = 0; i < q; ++i) {
      int a = in.nextInt(), b = in.nextInt();
      long[] dp = new long[n + 1];
      Node[] heap = new Node[2];
      Arrays.fill(dp, -INF);
      for (int j = 0; j < 2; ++j) heap[j] = new Node(-INF, -1);
      for (int j = 0; j < n; ++j) {
        long val = v[j], maxv = val * b;
        int color = c[j];
        maxv = Math.max(dp[color] + val * a, maxv);
        maxv = Math.max(choose(heap, color) + val * b, maxv);
        dp[color] = Math.max(maxv, dp[color]);
        update(heap, dp[color], color);
      }

      long ret = 0;
      for (int j = 1; j <= n; ++j) ret = Math.max(ret, dp[j]);
      out.println(ret);
    }

    out.close();
  }
コード例 #16
0
 /**
  * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>,
  * <code>nohref</code> Attribute for the specified figure and ellipse.
  *
  * @return Returns true, if the circle is inside of the image bounds.
  */
 private boolean writeCircleAttributes(IXMLElement elem, SVGFigure f, Ellipse2D.Double ellipse) {
     AffineTransform t = TRANSFORM.getClone(f);
     if (t == null) {
         t = drawingTransform;
     } else {
         t.preConcatenate(drawingTransform);
     }
     
     if ((t.getType() &
             (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION)) ==
             t.getType() &&
             ellipse.width == ellipse.height
             ) {
         
         Point2D.Double start = new Point2D.Double(ellipse.x, ellipse.y);
         Point2D.Double end = new Point2D.Double(ellipse.x + ellipse.width, ellipse.y + ellipse.height);
         t.transform(start, start);
         t.transform(end, end);
         ellipse.x = Math.min(start.x, end.x);
         ellipse.y = Math.min(start.y, end.y);
         ellipse.width = Math.abs(start.x - end.x);
         ellipse.height = Math.abs(start.y - end.y);
         
         elem.setAttribute("shape", "circle");
         elem.setAttribute("coords",
                 (int) (ellipse.x + ellipse.width / 2d)+","+
                 (int) (ellipse.y + ellipse.height / 2d)+","+
                 (int) (ellipse.width / 2d)
                 );
         writeHrefAttribute(elem, f);
         return bounds.intersects(ellipse.getBounds());
     } else {
         return writePolyAttributes(elem, f, (Shape) ellipse);
     }
 }
コード例 #17
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    TreeMap<Long, Long> tmap = new TreeMap<>();
    long res = 0;
    while (t-- > 0) {
      res = 0;
      int n = in.nextInt();
      long m = in.nextLong();
      tmap.clear();
      long[] arr = new long[n];
      res = in.nextLong();
      arr[0] = res % m;
      res = Long.MIN_VALUE;
      tmap.put(arr[0], arr[0]);
      for (int i = 1; i < arr.length; i++) {
        arr[i] = in.nextLong();
        arr[i] %= m;
        arr[i] += arr[i - 1];
        arr[i] %= m;

        if (tmap.higherEntry(arr[i]) == null) {
          res = Math.max(res, arr[i]);
          tmap.put(arr[i], arr[i]);
          continue;
        }
        long val = tmap.higherEntry(arr[i]).getValue();
        res = Math.max(res, (arr[i] - val + m) % m);
        tmap.put(arr[i], arr[i]);
      }

      System.out.println(res);
    }
  }
コード例 #18
0
  /**
   * Reads image meta data.
   *
   * @param oimage
   * @return
   */
  public static Map<String, String> readImageData(IIOImage oimage) {
    Map<String, String> dict = new HashMap<String, String>();

    IIOMetadata imageMetadata = oimage.getMetadata();
    if (imageMetadata != null) {
      IIOMetadataNode dimNode = (IIOMetadataNode) imageMetadata.getAsTree("javax_imageio_1.0");
      NodeList nodes = dimNode.getElementsByTagName("HorizontalPixelSize");
      int dpiX;
      if (nodes.getLength() > 0) {
        float dpcWidth = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue());
        dpiX = (int) Math.round(25.4f / dpcWidth);
      } else {
        dpiX = Toolkit.getDefaultToolkit().getScreenResolution();
      }
      dict.put("dpiX", String.valueOf(dpiX));

      nodes = dimNode.getElementsByTagName("VerticalPixelSize");
      int dpiY;
      if (nodes.getLength() > 0) {
        float dpcHeight = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue());
        dpiY = (int) Math.round(25.4f / dpcHeight);
      } else {
        dpiY = Toolkit.getDefaultToolkit().getScreenResolution();
      }
      dict.put("dpiY", String.valueOf(dpiY));
    }

    return dict;
  }
コード例 #19
0
  public static void main(String[] args) throws IOException {
    input.init(System.in);
    PrintWriter out = new PrintWriter(System.out);

    int depth = input.nextInt();
    int n = (1 << (depth + 1));
    int[] as = new int[n];
    for (int i = 2; i < n; i++) as[i] = input.nextInt();
    int[] paths = new int[n];
    int max = 0;
    ArrayList<Integer>[] under = new ArrayList[n];
    for (int i = 0; i < n; i++) under[i] = new ArrayList<Integer>();
    for (int i = (1 << (depth)); i < n; i++) {
      int cur = i;
      while (cur > 1) {
        under[cur].add(i);
        paths[i] += as[cur];
        cur /= 2;
      }
      max = Math.max(max, paths[i]);
    }
    int res = 0;
    for (int i = 2; i < n; i++) {
      int cm = 0;
      for (int x : under[i]) cm = Math.max(cm, paths[x]);
      int diff = max - cm;
      res += diff;
      for (int x : under[i]) paths[x] += diff;
    }
    out.println(res);
    out.close();
  }
コード例 #20
0
ファイル: Snake.java プロジェクト: szamani20/Snake
  private void doesEatRegime() {
    if (isEnd) return;

    if (Math.abs(blocks.peekFirst().getX() - regimeRectangle.getX()) < 10
        && Math.abs(blocks.peekFirst().getY() - regimeRectangle.getY()) < 10
        && System.currentTimeMillis() - currentTime <= 10000) {

      regimeRectangle.setX(1200);
      isRegime = false;
      ++score;
      scoreLabel.setText(String.valueOf(score));

      blocks.pollLast();
      blocks.pollLast();
      blocks.pollLast();

      group.getChildren().remove(rectangles.peekLast());
      rectangles.pollLast();
      group.getChildren().remove(rectangles.peekLast());
      rectangles.pollLast();
      group.getChildren().remove(rectangles.peekLast());
      rectangles.pollLast();
    }

    if (System.currentTimeMillis() - currentTime > 10000) {
      regimeRectangle.setX(1200);
      isRegime = false;
    }
  }
コード例 #21
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);
    }
  }
コード例 #22
0
ファイル: Snake.java プロジェクト: szamani20/Snake
  private void addRegime() {
    if (isEnd) return;

    if (feedCounter2 - feedCounter1 != 4 || isRegime || feedCounter2 == 0) return;

    feedCounter1 = feedCounter2;

    currentTime = System.currentTimeMillis();

    regimeX = Math.abs(random.nextInt()) % 400 + 10;
    regimeY = Math.abs(random.nextInt()) % 400 + 10;

    List<Block> blockTemp = new ArrayList<>(blocks);

    for (int i = 0; i < blockTemp.size(); i++)
      if (blockTemp.get(i).getX() < regimeX
          && blockTemp.get(i).getY() < regimeY
          && blockTemp.get(i).getX() + 10 > regimeX
          && blockTemp.get(i).getY() + 10 > regimeY) {
        regimeX = Math.abs(random.nextInt()) % 400 + 10;
        regimeY = Math.abs(random.nextInt()) % 400 + 10;
      }

    regimeRectangle.setX(regimeX);
    regimeRectangle.setY(regimeY);

    isRegime = true;
  }
コード例 #23
0
ファイル: Site.java プロジェクト: pjmichalski/SpringSaLaD
 // Give the string and horizontal and verical offsets so that the label is
 // drawn in the center.
 public void drawLabel(Graphics g, String label, int hoffset, int voffset) {
   g.setColor(Color.black);
   int pixelsPerNm = DrawPanel.PIXELS_PER_NM;
   int xint = (int) Math.round(pixelsPerNm * z);
   int yint = (int) Math.round(pixelsPerNm * y);
   g.drawString(label, xint - hoffset, yint + voffset);
 }
コード例 #24
0
ファイル: Snake.java プロジェクト: szamani20/Snake
  private void addFeed() {
    if (isEnd) return;

    if (isFeed) return;

    feedX = Math.abs(random.nextInt()) % 400 + 10;
    feedY = Math.abs(random.nextInt()) % 400 + 60;

    List<Block> blockTemp = new ArrayList<>(blocks);

    for (int i = 0; i < blockTemp.size(); i++)
      if (blockTemp.get(i).getX() < feedX
          && blockTemp.get(i).getY() < feedY
          && blockTemp.get(i).getX() + 10 > feedX
          && blockTemp.get(i).getY() + 10 > feedY) {
        feedX = Math.abs(random.nextInt()) % 400 + 10;
        feedY = Math.abs(random.nextInt()) % 400 + 60;
      }

    feedRectangle.setX(feedX);
    feedRectangle.setY(feedY);

    isFeed = true;

    addObstacle();
  }
コード例 #25
0
 /**
  * Write the given text string in the current font, centered on (x, y) and rotated by the
  * specified number of degrees
  *
  * @param x the center x-coordinate of the text
  * @param y the center y-coordinate of the text
  * @param s the text
  * @param degrees is the number of degrees to rotate counterclockwise
  */
 public static void text(double x, double y, String s, double degrees) {
   double xs = scaleX(x);
   double ys = scaleY(y);
   offscreen.rotate(Math.toRadians(-degrees), xs, ys);
   text(x, y, s);
   offscreen.rotate(Math.toRadians(+degrees), xs, ys);
 }
コード例 #26
0
  public double getHu2(int region) {

    double eta20 = this.getEta(region, 2, 0);
    double eta02 = this.getEta(region, 0, 2);
    double eta11 = this.getEta(region, 1, 1);
    return Math.pow(eta20 - eta02, 2) + Math.pow(2 * eta11, 2);
  }
コード例 #27
0
ファイル: NeuralNetwork.java プロジェクト: geomois/ciex2
 private ArrayList<Double> forwardProp(Double[] input) {
   for (int i = 0; i < hiddenLNo; i++) {
     for (int j = 0; j < inputSize + 1; j++) {
       if (j == inputSize) {
         hiddenNodes.set(i, hiddenNodes.get(i) + w1[j][i] * bias);
       } else {
         hiddenNodes.set(i, hiddenNodes.get(i) + w1[j][i] * input[j]);
       }
     }
     double temp = (1.0 / (1.0 + Math.exp(-hiddenNodes.get(i))));
     hiddenNodes.set(i, temp);
   }
   for (int i = 0; i < outputLNo; i++) {
     for (int j = 0; j < hiddenLNo + 1; j++) {
       if (j == hiddenNodes.size()) {
         outputNodes.set(i, outputNodes.get(i) + w2[j][i] * bias);
       } else {
         outputNodes.set(i, outputNodes.get(i) + w2[j][i] * hiddenNodes.get(j));
       }
     }
     //			double temp1 = (1.0 / (1.0 + Math.exp(-outputNodes.get(i))));
     outputNodes.set(i, (1.0 / (1.0 + Math.exp(-outputNodes.get(i)))));
   }
   return outputNodes;
 }
コード例 #28
0
ファイル: PostProcessing.java プロジェクト: COL-IU/GRASPER
 // if left is true --> left is the anchoring End(IS element-known)
 // --> then the right side is the insertion position so we check the rightside.
 public boolean isInsertionPair(Record other, boolean left) {
   if (left) {
     // --this--><--other--
     if (this.fwd2 && !other.fwd2) {
       if ((this.start2 < other.start2)
           && (other.end2 > this.end2)
           && (Math.abs(this.end2 - other.start2) <= 100)) return true;
     }
     // --other--><--this--
     else if (other.fwd2 && !this.fwd2) {
       if ((other.start2 < this.start2)
           && (this.end2 > other.end2)
           && (Math.abs(other.end2 - this.start2) <= 100)) return true;
     }
   } else {
     // --this--><--other--
     if (this.fwd1 && !other.fwd1) {
       if ((this.start1 < other.start1)
           && (other.end1 > this.end1)
           && (Math.abs(this.end1 - other.start1) <= 100)) return true;
     }
     // --other--><--this--
     else if (other.fwd1 && !this.fwd1) {
       if ((other.start1 < this.start1)
           && (this.end1 > other.end1)
           && (Math.abs(other.end1 - this.start1) <= 100)) return true;
     }
   }
   return false;
 }
コード例 #29
0
ファイル: main.java プロジェクト: mamunul/ViolaJones
  public static void testTargetFeaturesAgainstImages(
      Vector<HaarFeature> features, Vector<IntegralImage> images) {
    int numberOfTrue = 0;
    int numberOfFalse = 0;

    for (IntegralImage ii : images) {
      float weightSum = 0.0f;
      float sum = 0.0f;
      for (HaarFeature hf : features) {
        //    			HaarFeature hf = allFeatures.get(slimFeature.featureNumber);
        //    			hf.threshold = slimFeature.threshold;
        float v = hf.weight * ii.evaluateAsClassifier(hf);
        sum += v;
        weightSum += hf.weight;
      }

      boolean success = (sum >= weightSum * 0.5f);
      //    		System.out.println("image " + ii.name + " is a " +  success + " : " + sum + " > " +
      // weightSum*0.5f);
      if (success) {
        numberOfTrue++;
      } else {
        numberOfFalse++;
      }
    }
    System.out.println("*************");
    System.out.println("true: " + numberOfTrue);
    System.out.println("false: " + numberOfFalse);

    int min = Math.min(numberOfFalse, numberOfTrue);
    int max = Math.max(numberOfFalse, numberOfTrue);

    float percentError = min * 100.0f / max;
    System.out.println("percentError = " + percentError);
  }
コード例 #30
0
 /**
  * Read bytes into a portion of an array. This method will block until some input is available,
  * an I/O error occurs, or the end of the stream is reached.
  *
  * @param cbuf Destination buffer.
  * @param off Offset at which to start storing bytes.
  * @param len Maximum number of bytes to read.
  * @return The number of bytes read, or -1 if the end of the stream has been reached
  * @throws IOException if the stream is closed.
  * @since ostermillerutils 1.00.00
  */
 @Override
 public int read(byte[] cbuf, int off, int len) throws IOException {
   while (true) {
     synchronized (CircularByteBuffer.this) {
       if (inputStreamClosed)
         throw new IOException(
             "InputStream has been closed; cannot read from a closed InputStream.");
       int available = CircularByteBuffer.this.available();
       if (available > 0) {
         int length = Math.min(len, available);
         int firstLen = Math.min(length, buffer.length - readPosition);
         int secondLen = length - firstLen;
         System.arraycopy(buffer, readPosition, cbuf, off, firstLen);
         if (secondLen > 0) {
           System.arraycopy(buffer, 0, cbuf, off + firstLen, secondLen);
           readPosition = secondLen;
         } else {
           readPosition += length;
         }
         if (readPosition == buffer.length) {
           readPosition = 0;
         }
         ensureMark();
         return length;
       } else if (outputStreamClosed) {
         return -1;
       }
     }
     try {
       Thread.sleep(100);
     } catch (Exception x) {
       throw new IOException("Blocking read operation interrupted.");
     }
   }
 }