Esempio n. 1
1
 public static void main(String[] args) throws IOException {
   in = new Reader();
   out = new PrintWriter(System.out, true);
   while (true) {
     int b = in.nextInt(), g = in.nextInt();
     if (b == -1 && g == -1) break;
     if (g > b) {
       b ^= g;
       g ^= b;
       b ^= g;
     }
     if (g == 0) {
       out.println(b);
       continue;
     }
     out.println((int) Math.ceil((double) b / ((double) g + 1)));
   }
   System.exit(0);
 }
Esempio n. 2
0
  // createPageString -
  // Create list of pages for search results
  private String createPageString(
      int numberOfItems, int itemsPerPage, int currentPage, String baseUrl) {
    StringBuffer pageString = new StringBuffer();

    // Calculate the total number of pages
    int totalPages = 1;
    if (numberOfItems > itemsPerPage) {
      double pages = Math.ceil(numberOfItems / (double) itemsPerPage);
      totalPages = (int) Math.ceil(pages);
    }

    //
    if (totalPages > 1) {
      for (int i = 1; i <= totalPages; i++) {
        if (i == currentPage) {
          pageString.append(i);
        } else {
          pageString.append("<a href=\"" + baseUrl + i + "\" title=\"" + i + "\">" + i + "</a>");
        }

        if (i != totalPages) pageString.append(" ");
      }
    } else {
      pageString.append("1");
    }

    return pageString.toString();
  }
Esempio n. 3
0
  private boolean buildNoteSequence() {

    noteSequence = new NoteSequence();

    double quantizeBeatFactor = quantizeBeatSetting * 1000.0 * 60.0 / (double) getBPM();
    double quantizeDurationFactor = quantizeDurationSetting * 1000.0 * 60.0 / (double) getBPM();

    for (int i = 0; i < noteList.size(); i++) {
      noteListElement = noteList.get(i);

      if (noteListElement.underTone == true) {
        continue;
      }

      note = noteListElement.note;

      if (note < getLowPitch()) continue;
      if (note > getHighPitch()) continue;

      double startTime = (double) (noteListElement.startTime);

      if (quantizeBeatFactor != 0.0)
        startTime = Math.floor(startTime / quantizeBeatFactor) * quantizeBeatFactor;
      long startTick = 1 + (long) (startTime * getTickRate() / 1000.0);

      double endTime = (double) (noteListElement.endTime);

      if (quantizeBeatFactor != 0.0)
        endTime = Math.ceil(endTime / quantizeBeatFactor) * quantizeBeatFactor;
      if (quantizeDurationFactor != 0)
        endTime =
            startTime
                + (Math.ceil((endTime - startTime) / quantizeDurationFactor)
                    * quantizeDurationFactor);

      long endTick = 1 + (long) (endTime * getTickRate() / 1000.0);

      if ((endTick - startTick) < 1) endTick = startTick + 1;
      System.out.println(
          "times: " + startTime + ", " + endTime + ", " + getStartTime() + ", " + getEndTime());
      if (endTime < getStartTime()) continue;
      if (startTime > getEndTime()) continue;

      velocity = 64;
      noteSequence.add(new NoteSequenceElement(note, ON, startTick, velocity));
      noteSequence.add(new NoteSequenceElement(note, OFF, endTick, velocity));
    }

    if (noteSequence.size() == 0) {
      return false;
    } else {
      noteSequence.sort();
      return true;
    }
  }
Esempio n. 4
0
 /**
  * Apply this operator (function) to the supplied argument
  *
  * @param value the argument
  * @return the result
  */
 protected double applyFunction(double value) {
   switch (m_operator) {
     case 'l':
       return Math.log(value);
     case 'b':
       return Math.abs(value);
     case 'c':
       return Math.cos(value);
     case 'e':
       return Math.exp(value);
     case 's':
       return Math.sqrt(value);
     case 'f':
       return Math.floor(value);
     case 'h':
       return Math.ceil(value);
     case 'r':
       return Math.rint(value);
     case 't':
       return Math.tan(value);
     case 'n':
       return Math.sin(value);
   }
   return Double.NaN;
 }
  /** Initialize all the data structures relevant to the domain */
  private void _initializeDataStructures() {
    this.possibleOperators = new Operator[this.numCakes];
    // Initialize the operators (according to the updated position of the pancake)
    for (int i = 0; i < this.numCakes; ++i) {
      this.possibleOperators[i] = new PancakeOperator(i + 1);
    }
    // Set the maximum index (if it is not already defined)
    if (Pancakes.MAX_PANCAKE_FOR_PDB == -1) {
      this.maxPancakeForPDB = this.numCakes - 1;
    } else {
      this.maxPancakeForPDB = Pancakes.MAX_PANCAKE_FOR_PDB;
    }
    // calculate the bits and bitmask to store single pancake
    this.bitsForSinglePancake = Utils.bits(this.numCakes);
    this.maskForSinglePancake = Utils.mask(this.bitsForSinglePancake);
    // System.out.println("mask: " + this.maskForSinglePancake);
    this.packedCakesInSingleLong =
        Math.min(this.numCakes, (int) Math.floor(64.0d / this.bitsForSinglePancake));
    // System.out.println("packedCakesInSingleLong: " + this.packedCakesInSingleLong);
    this.packedLongsCount = (int) Math.ceil(this.numCakes * this.bitsForSinglePancake / 64.0d);
    // System.out.println("packedLongsCount: " + this.packedLongsCount);

    // Current debugs ..
    // assert(this.bitsForSinglePancake == 5);
    // assert this.packedLongsCount == 2;
  }
  /**
   * counts the subintervals of the mutations in the answer object
   *
   * @param answer an answer object that was generated through a query
   * @return Integer array holding the amount of mutations that intersect the subintervals
   */
  public static Integer[] count_mutations(QueryAnswer answer) {
    Integer[] pos = answer.position;
    float interval_length = pos[1] - pos[0];
    int subinterval_length = answer.zoom_level;
    int number_subints = (int) Math.ceil(interval_length / subinterval_length);
    Integer[] counts = new Integer[number_subints];
    for (int i = 0; i < counts.length; i++) {
      counts[i] = 0;
    }
    int[] subint_left_boundaries = new int[number_subints];
    int left = pos[0];
    for (int i = 0; i < number_subints; i++) {
      subint_left_boundaries[i] = left + i * subinterval_length;
    }

    for (IntervalST.Mutation mut : answer.mutations) {
      int mut_low = mut.i_Low;
      int mut_high = mut.i_High;
      int last_index = subint_left_boundaries.length - 1;
      for (int i = 0; i < last_index; i++) {
        int lower = Math.max(subint_left_boundaries[i], mut_low);
        int higher = Math.min(subint_left_boundaries[i + 1], mut_high);
        if (lower <= higher) {
          counts[i]++;
        }
      }
      if (mut_high >= subint_left_boundaries[last_index]) {
        counts[last_index]++;
      }
    }

    return counts;
  }
Esempio n. 7
0
  /**
   * @param gas_seq The sequence which we wish to map it against other sequence(s)
   * @param gas_targetSeqs The target sequence
   */
  private HashMap<Integer, Integer> doMapSeq2Seq(
      GappedAlignmentString gas_seq, GappedAlignmentString[] gas_targetSeqs) {
    int N = gas_seq.gappedLength();
    // making map allocation more efficient
    int initCapacity = (int) Math.ceil(1.5 * N);
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(initCapacity);

    // When a gap position corresponds to a gap remove it from seq
    HashMap<Integer, Integer> gapped2UngappedMap_seq = gas_seq.getGapped2UngappedMap();
    Integer[] gapPositions_seq = gas_seq.determineGapPositions();
    for (Integer e : gapPositions_seq) gapped2UngappedMap_seq.remove(e);

    // When a gap position corresponds to a gap, put -1 as its value
    HashMap<Integer, Integer> gapped2UngappedMap_targetSeq =
        gas_targetSeqs[0].getGapped2UngappedMap();
    Integer[] gapPositions_targetSeq = gas_targetSeqs[0].determineGapPositions();
    for (Integer e : gapPositions_targetSeq) gapped2UngappedMap_targetSeq.put(e, -1);

    Integer[] gappedPositionsNoGaps_seq =
        gapped2UngappedMap_seq.keySet().toArray(new Integer[gapped2UngappedMap_seq.size()]);
    for (Integer gappedPosNoGaps : gappedPositionsNoGaps_seq) {
      Integer ungappedPos = gapped2UngappedMap_targetSeq.get(gappedPosNoGaps);
      if (ungappedPos.equals(null)) {
        ungappedPos = -1;
      }
      map.put(gapped2UngappedMap_seq.get(gappedPosNoGaps), ungappedPos);
    }

    return map;
  } // end of doMapSeq2Seq method
Esempio n. 8
0
 // 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));
 }
 public int minkeys() {
   // if node is the root, minkey is 1
   if (getParent() == null) {
     return 1;
   } else {
     return (int) (Math.ceil(degree / 2.0) - 1);
   }
 }
Esempio n. 10
0
  /**
   * Sets image to be processed.
   *
   * @param xsize width of image
   * @param ysize height of image
   * @param buf pixel data
   * @param rect the bounding rectangle defines the region of the image to be recognized. A
   *     rectangle of zero dimension or <code>null</code> indicates the whole image.
   * @param bpp bits per pixel, represents the bit depth of the image, with 1 for binary bitmap, 8
   *     for gray, and 24 for color RGB.
   */
  private void setImage(int xsize, int ysize, ByteBuffer buf, Rectangle rect, int bpp) {
    int bytespp = bpp / 8;
    int bytespl = (int) Math.ceil(xsize * bpp / 8.0);
    api.TessBaseAPISetImage(handle, buf, xsize, ysize, bytespp, bytespl);

    if (rect != null && !rect.isEmpty()) {
      api.TessBaseAPISetRectangle(handle, rect.x, rect.y, rect.width, rect.height);
    }
  }
 /**
  * Compute the bitfield byte array from the isComplete BitSet
  *
  * @return byte[]
  */
 public byte[] getBitField() {
   int l = (int) Math.ceil((double) this.nbPieces / 8.0);
   byte[] bitfield = new byte[l];
   for (int i = 0; i < this.nbPieces; i++)
     if (this.isComplete.get(i)) {
       bitfield[i / 8] |= 1 << (7 - i % 8);
     }
   return bitfield;
 }
Esempio n. 12
0
  protected int[] computeResizedDimensions(int nw, int nh, int iw, int ih) {
    int[] dims = new int[2];

    // this code keeps thumbnail ratio same as original image
    double thumbRatio = (double) nw / (double) nh;
    double imageRatio = (double) iw / (double) ih;
    if (iw < nw && ih < nh) {
      dims[0] = iw;
      dims[1] = ih;
    } else if (thumbRatio < imageRatio) {
      dims[0] = nw;
      dims[1] = (int) Math.ceil(nw / imageRatio);
    } else {
      dims[0] = (int) Math.ceil(nh * imageRatio);
      dims[1] = nh;
    }

    return dims;
  }
  /**
   * Validates attachment size against maximum allowed of 16MB. Throws error if size is more than
   * allowed.
   */
  public void validateAttachmentSize(List<String> filePathNames) {
    int attachmentsMaxMB = getAttachmentsMaxSizeMB();
    if (attachmentsMaxMB == 0 || filePathNames == null || filePathNames.isEmpty()) {
      return;
    }

    double attachmentSizeBytes = 0;
    double totalLogsSize = 0;
    for (String path : filePathNames) {
      double size = new File(path).length();
      if (size > 0) {
        if (path.equals(SYSTEM_LOGS_FILE_PATH) || path.equals(SYSTEM_EVENT_FILE_PATH)) {
          totalLogsSize += size;
        }

        _log.info("Attachment {} size is {} MB", path, (size / BYTE_TO_MB));
        attachmentSizeBytes += size;
      }
    }

    if (attachmentSizeBytes > 0) {
      long attachmentSizeMB = (long) Math.ceil(attachmentSizeBytes / BYTE_TO_MB);
      if (attachmentSizeMB > attachmentsMaxMB) {
        _log.error(
            "Attachments size {} MB is more than allowed max {} MB ",
            attachmentSizeMB,
            attachmentsMaxMB);
        if (totalLogsSize > 0) {
          totalLogsSize = Math.ceil(totalLogsSize / BYTE_TO_MB);
          _log.info("Logs attachment size is {} MB ", totalLogsSize);
          throw APIException.badRequests.attachmentLogsSizeError(
              attachmentSizeMB,
              (long) totalLogsSize,
              attachmentsMaxMB,
              collectQueryParameters().toString());
        }
        throw APIException.internalServerErrors.attachmentSizeError(
            attachmentSizeMB, attachmentsMaxMB);
      }
    }
  }
  public static void main(String[] args) throws IOException {
    br = new BufferedReader(new InputStreamReader(System.in));
    out = new PrintWriter(new OutputStreamWriter(System.out));
    // br = new BufferedReader(new FileReader("in.txt"));
    // out = new PrintWriter(new FileWriter("out.txt"));

    l = readInt();
    x = readInt();

    out.println((int) Math.ceil(round(l * x / (1.0 / (1.0 - 1.0 / x)))));
    out.close();
  }
Esempio n. 15
0
    /** @param dis - Data input stream to be used to fetch header data. */
    public Header(DataInputStream dis) {

      // We are allocating 1 bit per slot, storing data for 32 slots in one integer.
      int numHeaderInts = (int) Math.ceil((float) numSlots / 32);
      header = new int[numHeaderInts];

      try {
        for (int index = 0; index < numHeaderInts; ++index) {
          header[index] = dis.readInt();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Esempio n. 16
0
 //	http://jira.dotmarketing.net/browse/DOTCMS-2178
 public static String getsize(File fileName) {
   String finalVal;
   long filesize = fileName.length();
   BigDecimal size = new BigDecimal(filesize);
   BigDecimal byteVal = null;
   BigDecimal changedByteVal = null;
   finalVal = "";
   if (filesize <= 0) {
     finalVal = "";
   } else if (filesize < MEGA_BYTE) {
     byteVal = new BigDecimal(KILO_BYTE);
     if (size != null) {
       changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
       finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " KB";
     }
   } else if (filesize < GIGA_BYTE) {
     byteVal = new BigDecimal(MEGA_BYTE);
     if (size != null) {
       changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
       finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " MB";
     }
   } else if (filesize < TERA_BYTE) {
     byteVal = new BigDecimal(GIGA_BYTE);
     if (size != null) {
       changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
       finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " GB";
     }
   } else {
     byteVal = new BigDecimal(TERA_BYTE);
     if (size != null) {
       changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
       finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " TB";
     }
   }
   return finalVal;
 }
Esempio n. 17
0
 private ArrayList<Integer> findRanges() {
   int rowsPerRange = (int) Math.ceil((grid.size()) / (double) threads);
   ArrayList<Integer> ranges = new ArrayList<Integer>();
   int startRow = 0, endRow = rowsPerRange;
   for (int i = 0; i < threads; i++) {
     ranges.add(startRow);
     ranges.add(endRow);
     startRow = endRow;
     ;
     endRow += rowsPerRange;
   }
   ranges.set(ranges.size() - 1, Math.min(grid.size(), ranges.get(ranges.size() - 1)));
   System.out.println(ranges);
   return ranges;
 }
  public static void main(String[] args) throws IOException {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    // INPUT
    for (byte T = Byte.parseByte(br.readLine()); T > 0; --T) {
      String[] input = br.readLine().split(" ");
      int A = Integer.parseInt(input[0]);
      int B = Integer.parseInt(input[1]);

      // SOLVE
      int C = (int) (Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(A)) + 1);
      sb.append(C + "\n");
    }

    // OUTPUT
    System.out.print(sb);
  }
Esempio n. 19
0
  /**
   * Draws a single arrow head
   *
   * @param aG the canvas to draw on;
   * @param aXpos the X position of the arrow head;
   * @param aYpos the (center) Y position of the arrow head;
   * @param aFactor +1 to have a left-facing arrow head, -1 to have a right-facing arrow head;
   * @param aArrowWidth the total width of the arrow head;
   * @param aArrowHeight the total height of the arrow head.
   */
  public static final void drawArrowHead(
      final Graphics2D aG,
      final int aXpos,
      final int aYpos,
      final int aFactor,
      final int aArrowWidth,
      final int aArrowHeight) {
    final double halfHeight = aArrowHeight / 2.0;
    final int x1 = aXpos + (aFactor * aArrowWidth);
    final int y1 = (int) Math.ceil(aYpos - halfHeight);
    final int y2 = (int) Math.floor(aYpos + halfHeight);

    final Polygon arrowHead = new Polygon();
    arrowHead.addPoint(aXpos, aYpos);
    arrowHead.addPoint(x1, y1);
    arrowHead.addPoint(x1, y2);

    aG.fill(arrowHead);
  }
Esempio n. 20
0
 /**
  * Creates a new <code>TIntIntHashMap</code> instance containing all of the entries in the map
  * passed in.
  *
  * @param map a <tt>TIntIntMap</tt> that will be duplicated.
  */
 public TIntIntHashMap(TIntIntMap map) {
   super(map.size());
   if (map instanceof TIntIntHashMap) {
     TIntIntHashMap hashmap = (TIntIntHashMap) map;
     this._loadFactor = hashmap._loadFactor;
     this.no_entry_key = hashmap.no_entry_key;
     this.no_entry_value = hashmap.no_entry_value;
     //noinspection RedundantCast
     if (this.no_entry_key != (int) 0) {
       Arrays.fill(_set, this.no_entry_key);
     }
     //noinspection RedundantCast
     if (this.no_entry_value != (int) 0) {
       Arrays.fill(_values, this.no_entry_value);
     }
     setUp((int) Math.ceil(DEFAULT_CAPACITY / _loadFactor));
   }
   putAll(map);
 }
  private static long toInteger(Object value, Class<?> type, double min, double max) {
    double d = toDouble(value);

    if (Double.isInfinite(d) || Double.isNaN(d)) {
      // Convert to string first, for more readable message
      reportConversionError(ScriptRuntime.toString(value), type);
    }

    if (d > 0.0) {
      d = Math.floor(d);
    } else {
      d = Math.ceil(d);
    }

    if (d < min || d > max) {
      // Convert to string first, for more readable message
      reportConversionError(ScriptRuntime.toString(value), type);
    }
    return (long) d;
  }
Esempio n. 22
0
  /**
   * Returns a set of numerators k_i so that the following constraints are met:
   *
   * <p>1. k_i / 2^d is within range of target[i] +/- this.precision 2. sum_i k_i = 2^d
   *
   * <p>If no such selection of k's is possible, then returns null.
   */
  private int[] getRatios(int depth, double[] target) {
    // construct upper and lower bounds (inclusive) for each k
    int lowerSum = 0;
    int upperSum = 0;
    int[] lower = new int[target.length];
    int[] upper = new int[target.length];
    double unit = 1.0 / Math.pow(2, depth);
    for (int i = 0; i < target.length; i++) {
      lower[i] = (int) Math.ceil(Math.max(0.0, (target[i] - precision)) / unit);
      upper[i] = (int) Math.floor(Math.min(1.0, (target[i] + precision)) / unit);
      lowerSum += lower[i];
      upperSum += upper[i];
      // if there is not a single satisfying point in range,
      // then fail
      if (lower[i] > upper[i]) {
        return null;
      }
    }

    // if we can never get to sum to 2^d, then fail
    int targetSum = (int) Math.pow(2, depth);
    if (lowerSum > targetSum || upperSum < targetSum) {
      return null;
    }

    // now the problem is to select a number from each range so
    // that the total sums to 2^d.  Do this in a simple greedy way
    // -- start with lower bounds, and increase each numerator by
    // one (towards their upper bounds) until finding a combo that
    // is in range.
    while (lowerSum < targetSum) {
      for (int i = 0; i < target.length; i++) {
        if (lowerSum < targetSum && lower[i] < upper[i]) {
          lower[i]++;
          lowerSum++;
        }
      }
    }

    return lower;
  }
Esempio n. 23
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String s = in.next();

    int l = s.length();
    Double sqrl = Math.sqrt(l);
    Double low = Math.floor(sqrl);
    Double high = Math.ceil(sqrl);
    int r = 0;
    int c = 0;

    if (low == high) {
      r = low.intValue();
      c = low.intValue();
    } else if (low * high >= l) {
      r = low.intValue();
      c = high.intValue();
    } else {
      r = high.intValue();
      c = high.intValue();
    }

    //        System.out.println("Row: " + r);
    //        System.out.println("Col: " + c);

    StringBuilder sb = new StringBuilder();
    char en[] = s.toCharArray();
    for (int i = 0; i < c; i++) {
      for (int j = 0; j < r; j++) {
        if (j * c + i < l) {
          sb.append(en[j * c + i]);
        }
      }
      sb.append(" ");
    }

    System.out.println(sb.toString());
  }
Esempio n. 24
0
 byte[] read1bitImage(InputStream in) throws IOException {
   if (fi.compression == FileInfo.LZW)
     throw new IOException("ImageJ cannot open 1-bit LZW compressed TIFFs");
   int scan = (int) Math.ceil(width / 8.0);
   int len = scan * height;
   byte[] buffer = new byte[len];
   byte[] pixels = new byte[nPixels];
   DataInputStream dis = new DataInputStream(in);
   dis.readFully(buffer);
   int value1, value2, offset, index;
   for (int y = 0; y < height; y++) {
     offset = y * scan;
     index = y * width;
     for (int x = 0; x < scan; x++) {
       value1 = buffer[offset + x] & 0xff;
       for (int i = 7; i >= 0; i--) {
         value2 = (value1 & (1 << i)) != 0 ? 255 : 0;
         if (index < pixels.length) pixels[index++] = (byte) value2;
       }
     }
   }
   return pixels;
 }
Esempio n. 25
0
 double solve(Point[] points) {
   int n = points.length;
   Arrays.sort(points);
   Point[] down = getConvex(points);
   Point[] up = reverse(getConvex(reverse(points)));
   int xMin = down[0].x;
   int xMax = down[down.length - 1].x;
   long total = 0;
   double sum = 0.0;
   double squareSum = 0.0;
   for (int x = xMin, i = 0, j = 0; x <= xMax; ++x) {
     while (i + 1 < down.length && down[i + 1].x < x) {
       i++;
     }
     while (j + 1 < up.length && up[j + 1].x < x) {
       j++;
     }
     int yMin =
         (int)
                 Math.ceil(
                     (double) (x - down[i].x)
                         / (down[i + 1].x - down[i].x)
                         * (down[i + 1].y - down[i].y))
             + down[i].y;
     int yMax =
         (int)
                 Math.floor(
                     (double) (x - up[j].x) / (up[j + 1].x - up[j].x) * (up[j + 1].y - up[j].y))
             + up[j].y;
     int count = yMax - yMin + 1;
     total += count;
     sum += (double) count * x;
     squareSum += (double) count * x * x;
   }
   return (total * squareSum - sum * sum) / ((double) total * (total - 1));
 }
  /**
   * Executes the genetic algorithm to determine the minimum number of items necessary to make up
   * the given target volume. The solution will then be written to the console.
   *
   * @param a_knapsackVolume the target volume for which this method is attempting to produce the
   *     optimal list of items
   * @throws Exception
   * @author Klaus Meffert
   * @since 2.3
   */
  public static void findItemsForVolume(double a_knapsackVolume) throws Exception {
    // Start with a DefaultConfiguration, which comes setup with the
    // most common settings.
    // -------------------------------------------------------------
    Configuration conf = new DefaultConfiguration();
    conf.setPreservFittestIndividual(true);
    // Set the fitness function we want to use. We construct it with
    // the target volume passed in to this method.
    // ---------------------------------------------------------
    FitnessFunction myFunc = new KnapsackFitnessFunction(a_knapsackVolume);
    conf.setFitnessFunction(myFunc);
    // Now we need to tell the Configuration object how we want our
    // Chromosomes to be setup. We do that by actually creating a
    // sample Chromosome and then setting it on the Configuration
    // object. As mentioned earlier, we want our Chromosomes to each
    // have as many genes as there are different items available. We want the
    // values (alleles) of those genes to be integers, which represent
    // how many items of that type we have. We therefore use the
    // IntegerGene class to represent each of the genes. That class
    // also lets us specify a lower and upper bound, which we set
    // to senseful values (i.e. maximum possible) for each item type.
    // --------------------------------------------------------------
    Gene[] sampleGenes = new Gene[itemVolumes.length];
    for (int i = 0; i < itemVolumes.length; i++) {
      sampleGenes[i] = new IntegerGene(conf, 0, (int) Math.ceil(a_knapsackVolume / itemVolumes[i]));
    }
    IChromosome sampleChromosome = new Chromosome(conf, sampleGenes);
    conf.setSampleChromosome(sampleChromosome);
    // Finally, we need to tell the Configuration object how many
    // Chromosomes we want in our population. The more Chromosomes,
    // the larger number of potential solutions (which is good for
    // finding the answer), but the longer it will take to evolve
    // the population (which could be seen as bad).
    // ------------------------------------------------------------
    conf.setPopulationSize(50);
    // Create random initial population of Chromosomes.
    // Here we try to read in a previous run via XMLManager.readFile(..)
    // for demonstration purpose!
    // -----------------------------------------------------------------
    Genotype population;
    try {
      Document doc = XMLManager.readFile(new File("knapsackJGAP.xml"));
      population = XMLManager.getGenotypeFromDocument(conf, doc);
    } catch (FileNotFoundException fex) {
      population = Genotype.randomInitialGenotype(conf);
    }
    population = Genotype.randomInitialGenotype(conf);
    // Evolve the population. Since we don't know what the best answer
    // is going to be, we just evolve the max number of times.
    // ---------------------------------------------------------------
    for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) {
      population.evolve();
    }
    // Save progress to file. A new run of this example will then be able to
    // resume where it stopped before!
    // ---------------------------------------------------------------------

    // represent Genotype as tree with elements Chromomes and Genes
    // ------------------------------------------------------------
    DataTreeBuilder builder = DataTreeBuilder.getInstance();
    IDataCreators doc2 = builder.representGenotypeAsDocument(population);
    // create XML document from generated tree
    // ---------------------------------------
    XMLDocumentBuilder docbuilder = new XMLDocumentBuilder();
    Document xmlDoc = (Document) docbuilder.buildDocument(doc2);
    XMLManager.writeFile(xmlDoc, new File("knapsackJGAP.xml"));
    // Display the best solution we found.
    // -----------------------------------
    IChromosome bestSolutionSoFar = population.getFittestChromosome();
    System.out.println(
        "The best solution has a fitness value of " + bestSolutionSoFar.getFitnessValue());
    System.out.println("It contained the following: ");
    int count;
    double totalVolume = 0.0d;
    for (int i = 0; i < bestSolutionSoFar.size(); i++) {
      count = ((Integer) bestSolutionSoFar.getGene(i).getAllele()).intValue();
      if (count > 0) {
        System.out.println("\t " + count + " x " + itemNames[i]);
        totalVolume += itemVolumes[i] * count;
      }
    }
    System.out.println("\nFor a total volume of " + totalVolume + " ccm");
    System.out.println("Expected volume was " + a_knapsackVolume + " ccm");
    System.out.println("Volume difference is " + Math.abs(totalVolume - a_knapsackVolume) + " ccm");
  }
Esempio n. 27
0
 /** Returns the number of pages in this HeapFile. */
 public int numPages() {
   // some code goes here
   return (int) Math.ceil(f.length() / BufferPool.PAGE_SIZE);
 }
Esempio n. 28
0
 // 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(Planet source, Planet destination) {
   double dx = source.X() - destination.X();
   double dy = source.Y() - destination.Y();
   return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
 }
Esempio n. 29
0
  public static void main(String[] args) {
    // boolean makes sure game runs continuously
    boolean run = true;
    String name = null;

    // Creates the grid on which the characters move
    World theWorld = new World(10, 10, "Earth");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    // sets the username
    System.out.println("Welcome User. Please enter your NAME below.");
    try {
      name = br.readLine();
    } catch (IOException ioe) {
      System.out.println("Wow. You broke it. All I asked for was a name.");
      System.exit(1);
    }
    System.out.println("\n\n\n\n\n\nWelcome, " + name + ", to the world.");
    User b = new User(name, theWorld);
    Viewer a = new Viewer(theWorld, b);
    double str = 0;
    double sma = 0;
    double mor = 0;

    try {
      System.out.println(
          "Now, tell me a little about yourself.\n\nOn a scale of one to ten, how strong are you?\n1 is having trouble lifting this laptop, 10 is a participant in the 'World's Strongest Man' competitions.\nFeel free to use decimals.");
      str = (Double.parseDouble(br.readLine()));
      System.out.println(
          "\n\nGreat! Now, on a scale of one to ten, how would you place your intellect?\n1 is never having passed the first grade, 10 is Stephen Hawking.");
      sma = (Double.parseDouble(br.readLine()));
      System.out.println(
          "\n\nWell done! Now, for the final question, on a scale of one to ten, how moral are you?\n1 is cheating, stealing, and possibly even murdering without regret, 10 is never doing anything wrong ever, and feeling terrible when you tell even a little white lie.");
      mor = (Double.parseDouble(br.readLine()));
      b.setStats(str, sma, 10.7, 0, 0, 0, 0, 0, 500, mor);
    } catch (IOException ioe) {
      System.out.println("DON'T DO THAT. EVER.");
      System.exit(1);
    }
    try {
      System.out.println("Hit ENTER to continue.");
      br.readLine();
    } catch (IOException ioe) {
      System.out.println(
          "Really? You just had to hit ENTER. That's it. Nothing special, just a button I know you know how to press, because you just pressed it. God you're stupid. I'm glad you broke it. Saves me the trouble of watching you play.");
      System.exit(1);
    }

    // selects a random number of movers. Movers are the class that are the "characters"
    int characterNum = (int) Math.ceil(Math.random() * 20);

    // makes sure that there are no less than 10 movers at a time. It would be pretty boring to just
    // have one guy walking around on his own.
    while (characterNum < 10) {
      characterNum = (int) Math.ceil(Math.random() * 20);
    }

    // Populates the grid with movers. Their respective locations are randomly selected in their
    // constructors.
    for (int x = 0; x < characterNum; x++) {
      theWorld.createMover();
    }

    // Printing the world prints out a grid that shows where all of the movers are.
    System.out.println(theWorld);

    // Start of it all.
    while (run) {

      // Makes sure the input is readable
      String input = null;
      // String input2 = null;
      // String miscString = null;
      try {
        input = br.readLine();

      } catch (IOException ioe) {
        System.out.println("I don't know what you're saying. You lose. Automatically. Forever.");
        System.exit(1);
      }
      input = input.toLowerCase();

      if (!b.getMode()) {
        a.command(input);
      } else {
        b.start(input);
      }

      // allows the player to "hit enter to continue"
      System.out.println("");
      System.out.println("Type a command, or hit enter to continue");
    }
  }
  /**
   * Removes locks regardless of whether they are owned or not for given version and keys.
   *
   * @param ver Lock version.
   * @param keys Keys.
   */
  @SuppressWarnings({"unchecked"})
  public void removeLocks(GridCacheVersion ver, Collection<? extends K> keys) {
    if (keys.isEmpty()) return;

    try {
      Collection<GridRichNode> affNodes = null;

      int keyCnt = -1;

      Map<GridNode, GridNearUnlockRequest<K, V>> map = null;

      for (K key : keys) {
        // Send request to remove from remote nodes.
        GridNearUnlockRequest<K, V> req = null;

        while (true) {
          GridDistributedCacheEntry<K, V> entry = peekExx(key);

          try {
            if (entry != null) {
              GridCacheMvccCandidate<K> cand = entry.candidate(ver);

              if (cand != null) {
                if (affNodes == null) {
                  affNodes = CU.allNodes(ctx, cand.topologyVersion());

                  keyCnt = (int) Math.ceil((double) keys.size() / affNodes.size());

                  map = new HashMap<GridNode, GridNearUnlockRequest<K, V>>(affNodes.size());
                }

                GridRichNode primary = CU.primary0(ctx.affinity(key, affNodes));

                if (!primary.isLocal()) {
                  req = map.get(primary);

                  if (req == null) {
                    map.put(primary, req = new GridNearUnlockRequest<K, V>(keyCnt));

                    req.version(ver);
                  }
                }

                // Remove candidate from local node first.
                if (entry.removeLock(cand.version())) {
                  if (primary.isLocal()) {
                    dht.removeLocks(primary.id(), ver, F.asList(key), true);

                    assert req == null;

                    continue;
                  }

                  req.addKey(entry.key(), entry.getOrMarshalKeyBytes(), ctx);
                }
              }
            }

            break;
          } catch (GridCacheEntryRemovedException ignored) {
            if (log.isDebugEnabled())
              log.debug(
                  "Attempted to remove lock from removed entry (will retry) [rmvVer="
                      + ver
                      + ", entry="
                      + entry
                      + ']');
          }
        }
      }

      if (map == null || map.isEmpty()) return;

      Collection<GridCacheVersion> committed = ctx.tm().committedVersions(ver);
      Collection<GridCacheVersion> rolledback = ctx.tm().rolledbackVersions(ver);

      for (Map.Entry<GridNode, GridNearUnlockRequest<K, V>> mapping : map.entrySet()) {
        GridNode n = mapping.getKey();

        GridDistributedUnlockRequest<K, V> req = mapping.getValue();

        if (!req.keyBytes().isEmpty()) {
          req.completedVersions(committed, rolledback);

          // We don't wait for reply to this message.
          ctx.io().send(n, req);
        }
      }
    } catch (GridException ex) {
      U.error(log, "Failed to unlock the lock for keys: " + keys, ex);
    }
  }