Esempio n. 1
0
  @Override
  public int read(byte[] buffer, int offset, int length) throws IOException {
    if (length < 1) {
      return 0;
    }
    if (!readyBuffer()) {
      return -1;
    }
    // First let's read however much data we happen to have...
    int chunkLength = Math.min(bufferLength - bufferPosition, length);
    System.arraycopy(_decodedBytes, bufferPosition, buffer, offset, chunkLength);
    bufferPosition += chunkLength;

    if (chunkLength == length || !_cfgFullReads) {
      return chunkLength;
    }
    // Need more data, then
    int totalRead = chunkLength;
    do {
      offset += chunkLength;
      if (!readyBuffer()) {
        break;
      }
      chunkLength = Math.min(bufferLength - bufferPosition, (length - totalRead));
      System.arraycopy(_decodedBytes, bufferPosition, buffer, offset, chunkLength);
      bufferPosition += chunkLength;
      totalRead += chunkLength;
    } while (totalRead < length);

    return totalRead;
  }
Esempio n. 2
0
 /**
  * Get the distance between a point and this cuboid.
  *
  * @param pos
  * @return
  */
 public double distance(Vector pos) {
   Vector max = origin.add(new Vector(width, height, length));
   int closestX = Math.max(origin.getBlockX(), Math.min(max.getBlockX(), pos.getBlockX()));
   int closestY = Math.max(origin.getBlockY(), Math.min(max.getBlockY(), pos.getBlockY()));
   int closestZ = Math.max(origin.getBlockZ(), Math.min(max.getBlockZ(), pos.getBlockZ()));
   return pos.distance(new Vector(closestX, closestY, closestZ));
 }
Esempio n. 3
0
  private double rec(int idx, double rem) {
    if (idx >= 3) {
      return rem / walkSpeed;
    }

    double ans = INF;
    double left = 0;
    double right = rem;

    for (int iter = 0; iter < 100; iter++) {
      double m1 = left + (right - left) / 3.0;
      double m2 = right - (right - left) / 3.0;

      double a1 = rec(idx + 1, rem - m1) + Math.sqrt(sq(a[idx][0]) + sq(m1)) / a[idx][1];
      ans = Math.min(ans, a1);

      double a2 = rec(idx + 1, rem - m2) + Math.sqrt(sq(a[idx][0]) + sq(m2)) / a[idx][1];
      ans = Math.min(ans, a2);

      if (a1 < a2) {
        right = m2;
      } else {
        left = m1;
      }
    }

    return ans;
  }
  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);
  }
 /**
  * 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.");
     }
   }
 }
Esempio n. 6
0
  /**
   * n個のr.v.のうち1個以上n-k個以下の変数Xbc の値がxbc であるという条件の下で、1個 以上 k 個以下の変数 Xar の値が xar である条件付き確率 P(Xa0
   * ,...,Xar |Xb0 ,...,Xbc ) を返す (r: P(・|・) のうち、“|” より前で値の定まっている r.v. の数、c: P(・|・) の “|” より
   * 後で値の定まっている r.v. の数)
   *
   * @param rvA |より左側のrvの場所
   * @param rvR |より左側のrvの値
   * @param crvA |より右側のrvの場所
   * @param crvR |より右側のrvの値
   * @return 計算された確率
   */
  public double getConditionalProbability(int[] rvA, int[] rvR, int[] crvA, int[] crvR) {
    /**
     * Hint: 条件付き確率は課題資料に記述されている定義にあるとおり、 「同時確率/同時確率」の形式となっているので、上の getJointProbability
     * ができれば簡単に計算できる。 ただし、上の簡単な方のgetConditionalProbabilityと同様、 分母部分が0となった場合の処理は必要なので注意
     */
    final double condProbability;
    if ((condProbability = getJointProbability(crvA, crvR)) == 0.0) {
      System.out.println("Conditional Probability is 0.");
      return -1.0;
    }
    final int numAvailableR = Math.min(rvA.length, rvR.length);
    final int numAvailableC = Math.min(crvA.length, crvR.length);
    final int numJoint = numAvailableR + numAvailableC;

    int[] joinNums = new int[numJoint];
    int[] joinValues = new int[numJoint];
    System.arraycopy(rvA, 0, joinNums, 0, numAvailableR);
    System.arraycopy(rvR, 0, joinValues, 0, numAvailableR);
    System.arraycopy(crvA, 0, joinNums, numAvailableR, numAvailableC);
    System.arraycopy(crvR, 0, joinValues, numAvailableR, numAvailableC);
    // 合体リストの確率 P(A,B)
    final double joinProbability = getJointProbability(joinNums, joinValues);

    // P(A|B) = P(A,B) / P(B)
    return joinProbability / condProbability;
  }
  private void sendEntityBodyToClient(
      DataOutputStream socketOutputStream, HtmlResponse htmlResponse, boolean isChunked)
      throws IOException {

    byte[] content = htmlResponse.getEntityBody();

    if (!isChunked) {
      try {
        socketOutputStream.write(content, 0, content.length);
        socketOutputStream.flush();
      } catch (IOException e) {
        System.out.println("Writing the answer caused an error" + e.toString());
      }
    } else {

      int currentIndexStart = 0;
      int currentIndexEnd = Math.min(CHUNCKED_BYTES - 1, content.length - 1);
      int lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;

      while (currentIndexStart < content.length - 1) {
        socketOutputStream.writeBytes(Integer.toHexString(lengthOfBytesSent) + CRLF);
        socketOutputStream.write(content, currentIndexStart, lengthOfBytesSent);
        socketOutputStream.writeBytes(CRLF);
        socketOutputStream.flush();

        currentIndexStart = currentIndexEnd + 1;
        currentIndexEnd = Math.min(currentIndexStart + CHUNCKED_BYTES - 1, content.length - 1);
        lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;
      }

      socketOutputStream.writeBytes("0" + CRLF);
      socketOutputStream.writeBytes(CRLF);
      socketOutputStream.flush();
    }
  }
Esempio n. 8
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);
     }
 }
Esempio n. 9
0
  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);
    }
  }
Esempio n. 10
0
 protected void drawImageMosaic(Graphics2D g2) {
   // Break the image up into tiles. Draw each
   //   tile with its own transparency, allowing
   //   the background to show through to varying
   //   degrees.
   int side = 36;
   int width = mImage.getWidth();
   int height = mImage.getHeight();
   for (int y = 0; y < height; y += side) {
     for (int x = 0; x < width; x += side) {
       // Calculate an appropriate transparency value.
       float xBias = (float) x / (float) width;
       float yBias = (float) y / (float) height;
       float alpha = 1.0f - Math.abs(xBias - yBias);
       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
       // Draw the subimage.
       int w = Math.min(side, width - x);
       int h = Math.min(side, height - y);
       BufferedImage tile = mImage.getSubimage(x, y, w, h);
       g2.drawImage(tile, x, y, null);
     }
   }
   // Reset the composite.
   g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
 }
Esempio n. 11
0
  public SampleModel getSampleModel() {
    if (sampleModel != null) return sampleModel;

    int realWidth = (int) Math.min(tileWidth, width);
    int realHeight = (int) Math.min(tileHeight, height);

    if (nComp == 1 && (maxDepth == 1 || maxDepth == 2 || maxDepth == 4))
      sampleModel =
          new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, realWidth, realHeight, maxDepth);
    else if (maxDepth <= 8)
      sampleModel =
          new PixelInterleavedSampleModel(
              DataBuffer.TYPE_BYTE, realWidth, realHeight, nComp, realWidth * nComp, bandOffsets);
    else if (maxDepth <= 16)
      sampleModel =
          new PixelInterleavedSampleModel(
              isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT,
              realWidth,
              realHeight,
              nComp,
              realWidth * nComp,
              bandOffsets);
    else if (maxDepth <= 32)
      sampleModel =
          new PixelInterleavedSampleModel(
              DataBuffer.TYPE_INT, realWidth, realHeight, nComp, realWidth * nComp, bandOffsets);
    else throw new IllegalArgumentException(I18N.getString("J2KReadState11") + " " + +maxDepth);
    return sampleModel;
  }
 /**
  * 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.");
     }
   }
 }
Esempio n. 13
0
  private static void analyzeNext() {
    ArrayList previous = new ArrayList();
    String token = nextToken();
    analysis.add("", token, 0); // Insert 1st token directly.
    previous.add(token);

    while (true) {
      int nWords = Math.min(previous.size(), MAX);
      token = nextToken();
      if (token == PERIOD) break;

      for (int j = 1; j <= nWords; j++) {
        String s1 = concat(previous, j); // ({"a", "b", "c"}, 2) -> "b c"
        analysis.add(s1, token, j);
      }

      previous.add(token);
      if (previous.size() == MAX) previous.remove(0);
    }

    int nWords = Math.min(previous.size(), MAX);
    for (int j = 1; j < nWords; j++) {
      String s1 = concat(previous, j); // ({"a", "b", "c"}, 2) -> "b c"
      analysis.add(s1, PERIOD, j);
    }
  }
Esempio n. 14
0
 public static Color gradientColor(double value) {
   if (value < 0.0) return Color.gray;
   if (value > 1.0) value = 1.0;
   int red = Math.min(255, (int) (512.0 - (value * 512.0)));
   int green = Math.min(255, (int) (value * 512.0));
   int blue = 0;
   return new Color(red, green, blue);
 }
Esempio n. 15
0
 private void setHoverLocation(
     org.eclipse.swt.widgets.Shell shell, org.eclipse.swt.graphics.Point position) {
   org.eclipse.swt.graphics.Rectangle displayBounds = shell.getDisplay().getBounds();
   org.eclipse.swt.graphics.Rectangle shellBounds = shell.getBounds();
   shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0);
   shellBounds.y =
       Math.max(Math.min(position.y + 16, displayBounds.height - shellBounds.height), 0);
   shell.setBounds(shellBounds);
 }
Esempio n. 16
0
 private static int DFS(int si, int sj, int countdown) {
   if (countdown == 0) return -1;
   int i = si, j = sj;
   int step = Integer.MAX_VALUE;
   // search up
   while (i > 0 && map[i - 1][j] == 0) i--;
   if (i != 0) {
     if (map[i - 1][j] == 3) return 1;
     else if (i != si && map[i - 1][j] == 1) {
       map[i - 1][j] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i - 1][j] = 1;
     }
   }
   // search down
   i = si;
   j = sj;
   while (i < H - 1 && map[i + 1][j] == 0) i++;
   if (i != H - 1) {
     if (map[i + 1][j] == 3) return 1;
     if (i != si && map[i + 1][j] == 1) {
       map[i + 1][j] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i + 1][j] = 1;
     }
   }
   // search left
   i = si;
   j = sj;
   while (j > 0 && map[i][j - 1] == 0) j--;
   if (j != 0) {
     if (map[i][j - 1] == 3) return 1;
     if (j != sj && map[i][j - 1] == 1) {
       map[i][j - 1] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i][j - 1] = 1;
     }
   }
   // search right
   i = si;
   j = sj;
   while (j < W - 1 && map[i][j + 1] == 0) j++;
   if (j != W - 1) {
     if (map[i][j + 1] == 3) return 1;
     if (j != sj && map[i][j + 1] == 1) {
       map[i][j + 1] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i][j + 1] = 1;
     }
   }
   if (step == Integer.MAX_VALUE) return -1;
   return step;
 }
Esempio n. 17
0
  // ParserListener methods
  public void noteEvent(Note note) {
    if (layer >= staves) {
      return;
    }
    // System.out.println(note.getMusicString() + " " + note.getMillisDuration() + " " +
    // note.getDecimalDuration());
    Vector<Chord> currChords = chords[layer];
    Iterator<NotePanel> currNote = currNotes[layer];

    if (!currNote.hasNext()) {
      System.err.println("Received noteEvent, but no PostScript notes are left");
      return;
    }

    if (note.getMillisDuration() > 0) {
      NotePanel notePanel = currNote.next();
      // time the last chord ended
      long tempTime = 0;
      for (int i = currChords.size() - 1; i >= 0; --i) {
        if (!currChords.get(i).isTie()) {
          tempTime = currChords.get(i).getTime() + currChords.get(i).getDuration();
          break;
        }
      }

      if (notePanel.isTie) {
        Chord chord = new Chord();
        // for each note in the last chord, set the next note as a tied note
        for (int i = 0; i < currChords.lastElement().size(); ++i) {
          notePanel.setTie(true).setTime(Math.min(tempTime, time - 1)).setTempo(tempo);
          chord.addNote(notePanel);
          notePanel = currNote.next();
        }
        currChords.add(chord);
      }

      while (notePanel.isRest) {
        notePanel
            .setTime(Math.min(tempTime, time - 1)) // hack, in case the rest should be trimmed
            .setTempo(tempo);
        tempTime += notePanel.getDuration();
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
        // System.out.println("REST: " + notePanel.getMusicString() + " " +
        // notePanel.getDuration());
        notePanel = currNote.next();
      }

      notePanel.setNote(note).setTime(time).setTempo(tempo);
      if (currChords.isEmpty() || currChords.lastElement().getTime() != time) {
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
      } else {
        currChords.lastElement().addNote(notePanel);
      }
    }
  }
Esempio n. 18
0
  private void renderDirectionArrow(Graphics g) {
    if (widthArrow < 0) g.setColor(new Color(0, 0, 255, 150));
    else g.setColor(new Color(255, 0, 0, 150));

    g.fillPolygon(
        xPositionsArrow, yPositionsArrow, Math.min(xPositionsArrow.length, yPositionsArrow.length));
    g.setColor(new Color(0, 0, 0, 255));
    g.drawPolygon(
        xPositionsArrow, yPositionsArrow, Math.min(xPositionsArrow.length, yPositionsArrow.length));
  }
Esempio n. 19
0
 private int neighbor(int i) {
   int res = Integer.MAX_VALUE;
   for (Edge e : edges) {
     if (e.from == i) {
       res = Math.min(res, e.to);
     } else if (e.to == i) {
       res = Math.min(res, e.from);
     }
   }
   return res == Integer.MAX_VALUE ? -1 : res;
 }
  static void sweep(ArrayList<Integer> indexes) {
    PriorityQueue<Event> pq = new PriorityQueue<Event>();
    for (int i = 0; i < indexes.size(); i++) {
      pq.offer(new Event(lo[val[indexes.get(i)]] + 1, 1, indexes.get(i)));
      pq.offer(new Event(hi[val[indexes.get(i)]], -1, indexes.get(i)));
    }

    TreeSet<Integer> active = new TreeSet<Integer>();
    while (!pq.isEmpty()) {
      Event curr = pq.poll();
      if (curr.type == 1) active.add(curr.index);
      else if (curr.type == -1) {
        active.remove(curr.index);
        Integer lower = active.lower(curr.index);
        if (lower != null && lower > lo[val[curr.index]]) {
          Interval add = new Interval(lower, curr.index);
          Interval prev = intervals.floor(add);
          Interval next = intervals.ceiling(add);
          boolean intersectPrev = true;
          boolean intersectNext = true;

          if (prev != null) {
            if (Math.max(add.l, prev.l) < Math.min(add.r, prev.r)) {
              if (add.r - add.l <= prev.r - prev.l) {
                intervals.remove(prev);
                intersectPrev = false;
              }
            } else {
              intersectPrev = false;
            }
          } else {
            intersectPrev = false;
          }

          if (next != null) {
            if (Math.max(add.l, next.l) < Math.min(add.r, next.r)) {
              if (add.r - add.l <= next.r - next.l) {
                intervals.remove(next);
                intersectNext = false;
              }
            } else {
              intersectNext = false;
            }
          } else {
            intersectNext = false;
          }

          if (!intersectPrev && !intersectNext) intervals.add(add);
        }
      }
    }
  }
 private WVirtualImage.Rect neighbourhood(long x, long y, int marginX, int marginY) {
   long x1 = x - marginX;
   if (this.imageWidth_ != Infinite) {
     x1 = Math.max((long) 0, x1);
   }
   long y1 = Math.max((long) 0, y - marginY);
   long x2 = x + this.viewPortWidth_ + marginX;
   if (this.imageWidth_ != Infinite) {
     x2 = Math.min(this.imageWidth_, x2);
   }
   long y2 = Math.min(this.imageHeight_, y + this.viewPortHeight_ + marginY);
   return new WVirtualImage.Rect(x1, y1, x2, y2);
 }
  public static void main(String[] args) throws java.lang.Exception {
    // let_me_start

    String s = s();
    String t = s();
    int c[] = new int[150];
    int d[] = new int[150];
    String S = s.toUpperCase();
    String T = t.toUpperCase();
    int C[] = new int[150];
    int D[] = new int[150];

    int n = s.length();
    int m = t.length();

    // int arr[] = is((int)n);

    long ans = 0;
    for (int i = 1; i <= n; i++) {
      c[s.charAt(i - 1)]++;
    }

    for (int i = 1; i <= m; i++) {
      d[t.charAt(i - 1)]++;
    }
    for (int i = 1; i <= n; i++) {
      C[S.charAt(i - 1)]++;
    }

    for (int i = 1; i <= m; i++) {
      D[T.charAt(i - 1)]++;
    }

    int b = 0;
    int min = 1000000000;
    for (int i = 1; i <= 149; i++) {
      b += Math.min(c[i], d[i]);
      d[i] -= Math.min(c[i], d[i]);
    }
    int a = 0;
    min = 1000000000;
    for (int i = 1; i <= 149; i++) {
      a += Math.min(C[i], D[i]);
      D[i] -= Math.min(C[i], D[i]);
    }
    a = a - b;
    out.write("" + b + " " + a + "\n");
    out.flush();
    return;
  }
Esempio n. 23
0
 public void copyNoClose(InputStream is, OutputStream os, int length) {
   int bufSize = Math.min(1024, length);
   byte buf[] = new byte[bufSize];
   try {
     for (int total = 0, read;
         total < length && (read = is.read(buf, 0, Math.min(bufSize, length - total))) != -1;
         total += read) {
       os.write(buf, 0, read);
       os.flush();
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 24
0
 public static void main(String[] args) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader("day2/input2.txt"));
   String line;
   int a, b, c;
   long sum = 0;
   while ((line = br.readLine()) != null) {
     String[] arr = line.split("x");
     a = Integer.parseInt(arr[0]);
     b = Integer.parseInt(arr[1]);
     c = Integer.parseInt(arr[2]);
     sum += (a * b + b * c + a * c) * 2 + Math.min(Math.min(a * b, b * c), a * c);
   }
   System.out.println("the sum was: " + sum);
 }
 private void internalScrollTo(long newX, long newY, boolean moveViewPort) {
   if (this.imageWidth_ != Infinite) {
     newX = Math.min(this.imageWidth_ - this.viewPortWidth_, Math.max((long) 0, newX));
   }
   if (this.imageHeight_ != Infinite) {
     newY = Math.min(this.imageHeight_ - this.viewPortHeight_, Math.max((long) 0, newY));
   }
   if (moveViewPort) {
     this.contents_.setOffsets(new WLength((double) -newX), EnumSet.of(Side.Left));
     this.contents_.setOffsets(new WLength((double) -newY), EnumSet.of(Side.Top));
   }
   this.generateGridItems(newX, newY);
   this.viewPortChanged_.trigger(this.currentX_, this.currentY_);
 }
    @Override
    protected int readChunk(long pos, byte[] buf, int offset, int len, byte[] checksum)
        throws IOException {

      boolean eof = false;
      if (needChecksum()) {
        assert checksum != null; // we have a checksum buffer
        assert checksum.length % CHECKSUM_SIZE == 0; // it is sane length
        assert len >= bytesPerSum; // we must read at least one chunk

        final int checksumsToRead =
            Math.min(
                len / bytesPerSum, // number of checksums based on len to read
                checksum.length / CHECKSUM_SIZE); // size of checksum buffer
        long checksumPos = getChecksumFilePos(pos);
        if (checksumPos != sums.getPos()) {
          sums.seek(checksumPos);
        }

        int sumLenRead = sums.read(checksum, 0, CHECKSUM_SIZE * checksumsToRead);
        if (sumLenRead >= 0 && sumLenRead % CHECKSUM_SIZE != 0) {
          throw new ChecksumException(
              "Checksum file not a length multiple of checksum size "
                  + "in "
                  + file
                  + " at "
                  + pos
                  + " checksumpos: "
                  + checksumPos
                  + " sumLenread: "
                  + sumLenRead,
              pos);
        }
        if (sumLenRead <= 0) { // we're at the end of the file
          eof = true;
        } else {
          // Adjust amount of data to read based on how many checksum chunks we read
          len = Math.min(len, bytesPerSum * (sumLenRead / CHECKSUM_SIZE));
        }
      }
      if (pos != datas.getPos()) {
        datas.seek(pos);
      }
      int nread = readFully(datas, buf, offset, len);
      if (eof && nread > 0) {
        throw new ChecksumException("Checksum error: " + file + " at " + pos, pos);
      }
      return nread;
    }
Esempio n. 27
0
  /**
   * Returns a path which is cappedPath at the ends, to prevent it from drawing under the end caps.
   */
  protected BezierPath getCappedPath() {
    if (cappedPath == null) {
      cappedPath = path.clone();
      if (isClosed()) {
        cappedPath.setClosed(true);
      } else {
        if (cappedPath.size() > 1) {
          if (get(START_DECORATION) != null) {
            BezierPath.Node p0 = cappedPath.get(0);
            BezierPath.Node p1 = cappedPath.get(1);
            Point2D.Double pp;
            if ((p0.getMask() & BezierPath.C2_MASK) != 0) {
              pp = p0.getControlPoint(2);
            } else if ((p1.getMask() & BezierPath.C1_MASK) != 0) {
              pp = p1.getControlPoint(1);
            } else {
              pp = p1.getControlPoint(0);
            }
            double radius = get(START_DECORATION).getDecorationRadius(this);
            double lineLength = Geom.length(p0.getControlPoint(0), pp);
            cappedPath.set(
                0, 0, Geom.cap(pp, p0.getControlPoint(0), -Math.min(radius, lineLength)));
          }
          if (get(END_DECORATION) != null) {
            BezierPath.Node p0 = cappedPath.get(cappedPath.size() - 1);
            BezierPath.Node p1 = cappedPath.get(cappedPath.size() - 2);

            Point2D.Double pp;
            if ((p0.getMask() & BezierPath.C1_MASK) != 0) {
              pp = p0.getControlPoint(1);
            } else if ((p1.getMask() & BezierPath.C2_MASK) != 0) {
              pp = p1.getControlPoint(2);
            } else {
              pp = p1.getControlPoint(0);
            }

            double radius = get(END_DECORATION).getDecorationRadius(this);
            double lineLength = Geom.length(p0.getControlPoint(0), pp);
            cappedPath.set(
                cappedPath.size() - 1,
                0,
                Geom.cap(pp, p0.getControlPoint(0), -Math.min(radius, lineLength)));
          }
          cappedPath.invalidatePath();
        }
      }
    }
    return cappedPath;
  }
Esempio n. 28
0
	double calculate_rho()
	{
		int nr_free1 = 0,nr_free2 = 0;
		double ub1 = INF, ub2 = INF;
		double lb1 = -INF, lb2 = -INF;
		double sum_free1 = 0, sum_free2 = 0;

		for(int i=0;i<active_size;i++)
		{
			if(y[i]==+1)
			{
				if(is_lower_bound(i))
					ub1 = Math.min(ub1,G[i]);
				else if(is_upper_bound(i))
					lb1 = Math.max(lb1,G[i]);
				else
				{
					++nr_free1;
					sum_free1 += G[i];
				}
			}
			else
			{
				if(is_lower_bound(i))
					ub2 = Math.min(ub2,G[i]);
				else if(is_upper_bound(i))
					lb2 = Math.max(lb2,G[i]);
				else
				{
					++nr_free2;
					sum_free2 += G[i];
				}
			}
		}

		double r1,r2;
		if(nr_free1 > 0)
			r1 = sum_free1/nr_free1;
		else
			r1 = (ub1+lb1)/2;

		if(nr_free2 > 0)
			r2 = sum_free2/nr_free2;
		else
			r2 = (ub2+lb2)/2;

		si.r = (r1+r2)/2;
		return (r1-r2)/2;
	}
Esempio n. 29
0
  public int minDiameter(int[] a, int[] b, int K) {
    int res = INF;
    int n = a.length + 1;

    for (int mask = 0; mask < (1 << n); mask++) {
      if (Integer.bitCount(mask) == K) {
        int[][] dist = new int[2 * n][2 * n];
        for (int[] d : dist) {
          Arrays.fill(d, INF);
        }

        for (int i = 0; i < n; i++) {
          if ((mask & (1 << i)) != 0) {
            dist[i][i + n] = 0;
            dist[i + n][i] = 0;
          }
        }

        for (int i = 0; i < n - 1; i++) {
          dist[i][i + 1] = a[i];
          dist[i + 1][i] = a[i];
        }

        for (int i = 0; i < n - 1; i++) {
          dist[i + n][i + n + 1] = b[i];
          dist[i + n + 1][i + n] = b[i];
        }

        for (int k = 0; k < 2 * n; k++) {
          for (int i = 0; i < 2 * n; i++) {
            for (int j = 0; j < 2 * n; j++) {
              dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
            }
          }
        }

        int max = 0;
        for (int i = 0; i < 2 * n; i++) {
          for (int j = i + 1; j < 2 * n; j++) {
            max = Math.max(max, dist[i][j]);
          }
        }

        res = Math.min(res, max);
      }
    }

    return res;
  }
  void getArticulationPoints(int i, int d) {
    visited[i] = true;
    depth[i] = d;
    low[i] = d;
    int childCount = 0;
    boolean isArticulation = false;

    for (Map.Entry<Integer, Boolean> entry : AdjMatrix.get(i).entrySet()) {
      int ni = (int) entry.getKey();

      if (!visited[ni]) {
        parent[ni] = i;
        getArticulationPoints(ni, d + 1);
        childCount++;

        int low_i = low[i];
        int low_ni = low[ni];
        int depth_i = depth[i];

        if (low_ni != -1 && depth_i != -1 && (low_ni >= depth_i)) {
          isArticulation = true;
        }
        if (low_i != -1 && low_ni != -1) {
          low[i] = Math.min(low_i, low_ni);
        } else if (low_i == -1 && low_ni != -1) {
          low[i] = low_ni;
        } else if (low_i != -1 && low_ni == -1) {
          low[i] = low_i;
        }
      } else if (ni != parent[i]) {
        int depth_ni = depth[ni];
        int low_i = low[i];

        if (low_i != -1 && depth_ni != -1) {
          low[i] = Math.min(low_i, depth_ni);
        } else if (low_i == -1 && depth_ni != -1) {
          low[i] = depth_ni;
        } else if (low_i != -1 && depth_ni == -1) {
          low[i] = low_i;
        }
      }
    }

    int parent_i = parent[i];

    if ((parent_i != -1 && isArticulation) || (parent_i == -1 && childCount > 1)) {
      articulationPoints.put(i, true);
    }
  }