private String getPercentsTailHelper(BigDecimal percents) {
   return ((percents.doubleValue() - Math.floor(percents.doubleValue())) > 0)
       ? " целых "
           + Math.round((percents.doubleValue() - Math.floor(percents.doubleValue())) * 100)
           + " сотых"
       : "";
 }
 public int getPercentFromAmount(int amount) {
   double blocksRequired = required * size;
   if (Math.floor((amount / blocksRequired) * 100) > 100) {
     return 100;
   }
   if (Math.floor((amount / blocksRequired) * 100) < 0) {
     return 0;
   }
   return (int) Math.floor((amount / blocksRequired) * 100);
 }
 public int getPercent() {
   double blocksRequired = required * size;
   if (Math.floor((complete / blocksRequired) * 100) > 100) {
     return 100;
   }
   if (Math.floor((complete / blocksRequired) * 100) < 0) {
     return 0;
   }
   return (int) Math.floor((complete / blocksRequired) * 100);
 }
Exemple #4
0
 public troll(int id, String nom, int att, int deg, int esq, int tailleEchiquier) {
   idTroll = id;
   nomTroll = nom;
   this.att = att;
   this.deg = deg;
   this.esq = esq;
   this.vie = 40 - (att + deg + esq);
   paRestants = 6;
   positionX = (int) Math.floor(Math.random() * (tailleEchiquier)) + 1;
   positionY = (int) Math.floor(Math.random() * (tailleEchiquier)) + 1;
   valeur = "" + nomTroll.charAt(0);
 }
 /**
  * Transliterated from Python solution available here:
  * http://stackoverflow.com/questions/6463297/algorithm-to-fill-rectangle-with-small-squares
  */
 private int bestSquare(float w, float h, float n) {
   float hi = Math.max(w, h);
   float lo = 0;
   while (Math.abs(hi - lo) > 0.0001) {
     float mid = (lo + hi) / 2;
     float midval = (float) Math.floor(w / mid) * (float) Math.floor(h / mid);
     if (midval >= n) {
       lo = mid;
     } else if (midval < n) {
       hi = mid;
     }
   }
   return (int) Math.min(w / Math.floor(w / lo), h / Math.floor(h / lo));
 }
  private boolean computeNewMeans() {
    boolean changed = false;
    double avg_delta = 0;
    for (int i = 0; i < m_numClusters; i++) {
      long delta = 0;

      int sampleToCopyFrom = (int) Math.floor(Math.random() * m_initSamples.length);

      if (m_tmpClusterCount[i] == 0) {
        System.out.println("    Warning: zero sized cluster");
      }

      for (int j = 0; j < m_dimensions; j++) {
        int newValue = 0;

        if (m_tmpClusterCount[i] != 0) {
          newValue = (int) Math.round((float) m_tmpClusterAccum[i][j] / m_tmpClusterCount[i]);
        } else {
          try {
            newValue = m_initSamples[sampleToCopyFrom][j];
          } catch (NullPointerException npe) {
            int count = 0;
            do {
              sampleToCopyFrom = (int) Math.floor(Math.random() * m_initSamples.length);
              count++;
              if (count == 50) {
                throw new RuntimeException();
              }
            } while (m_initSamples[sampleToCopyFrom] == null);
          }
        }

        if (!changed) {
          if (newValue != m_clusters[i][j]) {
            changed = true;
          }
        }

        delta += sqrLookup[Math.abs(newValue - m_clusters[i][j])];

        m_clusters[i][j] = newValue;
      }
      avg_delta += (delta / m_dimensions);
    }
    avg_delta /= m_numClusters;
    //		System.out.println("avg_delta per dimension: " + avg_delta);

    return changed;
  }
Exemple #7
0
  public static long toUintX(Object o, int size) {
    double d = getDouble(o);
    if (d == 0 || Double.isNaN(d) || Double.isInfinite(d)) return 0;

    int sign = o.toString().startsWith("-") ? -1 : 1;
    return (sign * (long) Math.floor(Math.abs(d))) % (long) Math.pow(2, size);
  }
  /** @return true if number of instances are evenly distributed across the specified containers */
  public static boolean isEvenlyDistributedAcrossContainers(
      ProcessingUnit pu, GridServiceContainer[] containers) {

    if (!isProcessingUnitIntact(pu, containers)) {
      return false;
    }

    boolean evenlyDistributed = true;
    int numberOfInstances = pu.getTotalNumberOfInstances();
    int numberOfContainers = containers.length;
    if (numberOfInstances < numberOfContainers) {
      evenlyDistributed = false;
    } else {
      double expectedAverageNumberOfInstancesPerContainer =
          1.0 * numberOfInstances / numberOfContainers;
      int numberOfServicesPerContainerUpperBound =
          (int) Math.ceil(expectedAverageNumberOfInstancesPerContainer);
      int numberOfServicesPerContainerLowerBound =
          (int) Math.floor(expectedAverageNumberOfInstancesPerContainer);

      for (GridServiceContainer container : containers) {

        int puNumberOfInstances = container.getProcessingUnitInstances(pu.getName()).length;

        if (puNumberOfInstances < numberOfServicesPerContainerLowerBound
            || puNumberOfInstances > numberOfServicesPerContainerUpperBound) {
          evenlyDistributed = false;
          break;
        }
      }
    }
    return evenlyDistributed;
  }
  public void testMultiThreadAddsAndRemoves() {
    int size = TOTAL_THREADS + REMOVE_THREADS;
    ArrayList threadList = new ArrayList(size);
    for (int i = MIN_TRANS; i <= MAX_TRANS; i++) {
      int index = i - MIN_TRANS;
      threadList.add(new TransformerThread("Trans" + prettyNum(index, 2), i));
    }

    int factor = (int) Math.floor(TOTAL_THREADS / REMOVE_THREADS);
    for (int i = 0; i < REMOVE_THREADS; i++) {
      threadList.add(factor * i, new RemoveThread("Remove" + i));
    }

    Thread[] threads = (Thread[]) threadList.toArray(new Thread[size]);
    setExecThread(new ExecuteTransformersThread());
    getExecThread().start();
    for (int i = threads.length - 1; i >= 0; i--) {
      threads[i].start();
    }

    while (!testCompleted()) {
      Thread.currentThread().yield();
    }
    assertTrue(finalCheck());

    // printTransformers();
  }
Exemple #10
0
  public int score_Des(int nbDes) {

    int score = 0;
    for (int i = 0; i < nbDes; i++) {
      score = score + (int) Math.floor(Math.random() * (3)) + 1;
    }
    return (score);
  }
Exemple #11
0
 public void updateRoll(int i) {
   _dieRoll = i;
   twoDice =
       new int[] {
         (int) Math.max(Math.floor(Math.random() * Math.min(_dieRoll - 1, 5)) + 1, _dieRoll - 6), 1
       };
   twoDice[1] = _dieRoll - twoDice[0];
   repaint();
 }
Exemple #12
0
 /**
  * Adds a mover to the room. Ensures that if there is more than 1 person in the room, they will
  * interact.
  *
  * <p>The purpose for "rollForInitiative", aside from being a reference, is to randomize which of
  * the two movers will be interacting. Because I go through through the list of movers one at a
  * time to make them move, there would always be the same hierarchy of who would get the priority
  * in the interaction. (i.e. who acts and who reacts) So I randomized it for the sake of fairness.
  */
 public void addMover(Mover newMover) {
   if (newMover != null) {
     int rollForInitiative = (int) Math.floor(Math.random() * 2);
     peopleInRoom.add(newMover);
     if (peopleInRoom.size() > 1) {
       peopleInRoom.get(rollForInitiative).interact(peopleInRoom.get(1 - rollForInitiative));
     }
   }
 }
Exemple #13
0
  public static void compPlayer(ArrayList<Card> hand) {
    // how the computer plays the cards
    if (check(hand) > 0) {
      choice = (int) Math.floor(3 * Math.random() + 1);

      while (choice > check(hand)) {
        choice = (int) Math.floor(3 * Math.random() + 1);
      }
      // "playing" of the cards
      for (int i = 0; i < choice; i++) {
        for (int j = 0; j < hand.size(); j++) {
          if (hand.get(j).getRank() == currentRank) {
            temp = hand.get(j);
            pile.add(temp);
            hand.remove(temp);
          }
        }
      }
      // computer did not cheat
      lastPlayerCheated = false;

    } else {
      // if computer has to cheat
      choice = (int) Math.floor(3 * Math.random() + 1);

      while ((choice > 4) || (choice > hand.size())) {
        choice = (int) Math.floor(3 * Math.random() + 1);
      }
      // playing of the cards
      for (int i = 0; i < choice; i++) {
        temp = hand.get(0);
        pile.add(temp);
        hand.remove(temp);
      }
      // the computer did cheat
      lastPlayerCheated = true;
    }
    // getting the details for the last player
    lastPlayerHand = hand;
    lastPlayerRank = currentRank;
    lastPlayerNum = choice;
    // increase the rank
    increaseRank();
  }
  /**
   * Return a new dateTime with the same normalized value, but in a different timezone.
   *
   * @param timezone the new timezone offset, in minutes
   * @return the date/time in the new timezone. This will be a new DateTimeValue unless no change
   *     was required to the original value
   */
  public CalendarValue adjustTimezone(int timezone) {
    if (!hasTimezone()) {
      CalendarValue in = (CalendarValue) copyAsSubType(typeLabel);
      in.setTimezoneInMinutes(timezone);
      return in;
    }
    int oldtz = getTimezoneInMinutes();
    if (oldtz == timezone) {
      return this;
    }
    int tz = timezone - oldtz;
    int h = hour;
    int mi = minute;
    mi += tz;
    if (mi < 0 || mi > 59) {
      h += Math.floor(mi / 60.0);
      mi = (mi + 60 * 24) % 60;
    }

    if (h >= 0 && h < 24) {
      return new DateTimeValue(
          year, month, day, (byte) h, (byte) mi, second, microsecond, timezone);
    }

    // Following code is designed to handle the corner case of adjusting from -14:00 to +14:00 or
    // vice versa, which can cause a change of two days in the date
    DateTimeValue dt = this;
    while (h < 0) {
      h += 24;
      DateValue t = DateValue.yesterday(dt.getYear(), dt.getMonth(), dt.getDay());
      dt =
          new DateTimeValue(
              t.getYear(),
              t.getMonth(),
              t.getDay(),
              (byte) h,
              (byte) mi,
              second,
              microsecond,
              timezone);
    }
    if (h > 23) {
      h -= 24;
      DateValue t = DateValue.tomorrow(year, month, day);
      return new DateTimeValue(
          t.getYear(),
          t.getMonth(),
          t.getDay(),
          (byte) h,
          (byte) mi,
          second,
          microsecond,
          timezone);
    }
    return dt;
  }
  public void draw(GOut g) {
    Coord c = new Coord(xoff, 0);
    for (Spec s : inputs) {
      GOut sg = g.reclip(c, Inventory.invsq.sz());
      sg.image(Inventory.invsq, Coord.z);
      s.draw(sg);
      c = c.add(Inventory.sqsz.x, 0);
    }
    if (qmod != null) {
      g.image(qmodl.tex(), new Coord(0, qmy + 4));
      c = new Coord(xoff, qmy);
      int mx = -1;
      int pw = 0;
      int vl = 1;
      for (Indir<Resource> qm : qmod) {
        try {
          Tex t = qm.get().layer(Resource.imgc).tex();
          g.image(t, c);
          c = c.add(t.sz().x + 1, 0);
          if (c.x > mx) mx = c.x;

          try {
            Glob.CAttr attr = ui.gui.chrwdg.findattr(qm.get().basename());
            if (attr != null) {
              pw++;
              vl *= attr.comp;
              Tex txt = attr.comptex();
              g.image(txt, c);
              c = c.add(txt.sz().x + 8, 0);
            }
          } catch (Exception ignored) {
          }

        } catch (Loading l) {
        }
      }
      if (pw > 0) {
        g.image(
            Text.renderstroked(
                    String.format("Cap: %.0f", Math.floor(Math.pow(vl, 1.0f / pw))),
                    Color.WHITE,
                    Color.BLACK,
                    new Text.Foundry(Text.fraktur, 14).aa(true))
                .tex(),
            new Coord(mx + 30, qmy));
      }
    }
    c = new Coord(xoff, outy);
    for (Spec s : outputs) {
      GOut sg = g.reclip(c, Inventory.invsq.sz());
      sg.image(Inventory.invsq, Coord.z);
      s.draw(sg);
      c = c.add(Inventory.sqsz.x, 0);
    }
    super.draw(g);
  }
Exemple #16
0
  private int[] setUpNearest(MouseEvent e) {

    int mousex = e.getX() - _display_offset[0];
    int mousey = e.getY() - _display_offset[1];

    int i = 0;
    int j;

    j = (int) Math.round((mousey - hextop) * 1.0 / intervalUp);

    if ((j % 2 + (rings - 1) % 2) == 0 || (((j - 1) % 2 + (rings) % 2) == 0)) {
      int glob = 1;
      for (i = 0;
          (Math.floor((i + 1) / 2) * radius + Math.floor(i / 2) * radius * 2)
              < mousex - hexleft - radius / 2;
          i++) glob += (((i % 2) == 0) ? 1 : 3);

      double dx =
          (Math.floor((i + 1) / 2) * radius + Math.floor(i / 2) * radius * 2)
              - (mousex - hexleft - radius / 2);

      if ((i % 2) == 1 && dx > radius / 2) {
        i = i - 1;
        glob -= 1;
      } else if ((i % 2) == 0 && dx > radius) {
        i = i - 1;
        glob -= 3;
      }

      i = glob;

    } else {
      int glob = 0;
      for (i = 0;
          (Math.floor((i + 1) / 2) * radius * 2 + Math.floor(i / 2) * radius) < mousex - hexleft;
          i++) glob += (((i % 2) == 0) ? 3 : 1);

      double dx =
          (Math.floor((i + 1) / 2) * radius * 2 + Math.floor(i / 2) * radius) - (mousex - hexleft);

      if ((i % 2) == 0 && dx > radius / 2) {
        i = i - 1;
        glob -= 1;
      } else if ((i % 2) == 1 && dx > radius) {
        i = i - 1;
        glob -= 3;
      }

      i = glob;
    }

    return new int[] {i, j};
  }
Exemple #17
0
 public boolean loi_reussite() {
   int proba = (int) Math.floor(Math.random() * (100)) + 1;
   if (proba <= 80) {
     System.out.println("Action REUSSIE ! (" + proba + " sur 80%)");
     return (true);
   } else {
     System.out.println("Action RATEE ! (" + proba + " sur 80%)");
     return (false);
   }
 }
Exemple #18
0
  public static void main(String[] args) {
    if (args.length != 1) {
      System.err.println("Usage: Generator number_of_data.");
      System.exit(-1);
    }

    Random rand = new Random();

    int numberOfObjects = new Integer(args[0]).intValue();
    HashMap data = new HashMap(numberOfObjects);

    for (int i = 0; i < numberOfObjects; i++) {
      MyRegion r =
          new MyRegion(rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
      data.put(new Integer(i), r);

      System.out.println(
          "1 " + i + " " + r.m_xmin + " " + r.m_ymin + " " + r.m_xmax + " " + r.m_ymax);
    }

    int A = (int) (Math.floor((double) numberOfObjects * 0.1));

    for (int T = 100; T > 0; T--) {
      System.err.println(T);
      HashSet examined = new HashSet();

      for (int a = 0; a < A; a++) {
        // find an id that is not yet examined.
        Integer id = new Integer((int) ((double) numberOfObjects * rand.nextDouble()));
        boolean b = examined.contains(id);

        while (b) {
          id = new Integer((int) ((double) numberOfObjects * rand.nextDouble()));
          b = examined.contains(id);
        }
        examined.add(id);
        MyRegion r = (MyRegion) data.get(id);

        System.out.println(
            "0 " + id + " " + r.m_xmin + " " + r.m_ymin + " " + r.m_xmax + " " + r.m_ymax);

        r =
            new MyRegion(
                rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
        data.put(id, r);

        System.out.println(
            "1 " + id + " " + r.m_xmin + " " + r.m_ymin + " " + r.m_xmax + " " + r.m_ymax);
      }

      double stx = rand.nextDouble();
      double sty = rand.nextDouble();
      System.out.println("2 9999999 " + stx + " " + sty + " " + (stx + 0.01) + " " + (sty + 0.01));
    }
  }
  protected ArrayList<SquareZone> createSquaresGrid(
      int UTMZone,
      String hemisphere,
      Sector UTMZoneSector,
      double minEasting,
      double maxEasting,
      double minNorthing,
      double maxNorthing) {
    ArrayList<SquareZone> squares = new ArrayList<SquareZone>();
    double startEasting = Math.floor(minEasting / ONEHT) * ONEHT;
    double startNorthing = Math.floor(minNorthing / ONEHT) * ONEHT;
    int cols = (int) Math.ceil((maxEasting - startEasting) / ONEHT);
    int rows = (int) Math.ceil((maxNorthing - startNorthing) / ONEHT);
    SquareZone[][] squaresArray = new SquareZone[rows][cols];
    int col = 0;
    for (double easting = startEasting; easting < maxEasting; easting += ONEHT) {
      int row = 0;
      for (double northing = startNorthing; northing < maxNorthing; northing += ONEHT) {
        SquareZone sz =
            new SquareZone(UTMZone, hemisphere, UTMZoneSector, easting, northing, ONEHT);
        if (sz.boundingSector != null && !sz.isOutsideGridZone()) {
          squares.add(sz);
          squaresArray[row][col] = sz;
        }
        row++;
      }
      col++;
    }

    // Keep track of neighbors
    for (col = 0; col < cols; col++) {
      for (int row = 0; row < rows; row++) {
        SquareZone sz = squaresArray[row][col];
        if (sz != null) {
          sz.setNorthNeighbor(row + 1 < rows ? squaresArray[row + 1][col] : null);
          sz.setEastNeighbor(col + 1 < cols ? squaresArray[row][col + 1] : null);
        }
      }
    }

    return squares;
  }
  /**
   * @param container - the container for which planned min number of instances is requested
   * @param approvedContainers - the containers approved for deployment for the specified pu
   * @param pu - the processing unit
   * @return the planned minimum number of instances for the specified container
   */
  public static int getPlannedMinimumNumberOfInstancesForContainer(
      GridServiceContainer container,
      GridServiceContainer[] approvedContainers,
      ProcessingUnit pu) {

    int min = 0;
    if (Arrays.asList(approvedContainers).contains(container)) {
      min = (int) Math.floor(getAverageNumberOfInstancesPerContainer(approvedContainers, pu));
    }
    return min;
  }
 @Override
 public String ageName() {
   final int cat = ageCategory();
   if (cat < Race.AGE_ANCIENT) return Race.AGE_DESCS[cat];
   int age = getStat(STAT_AGE);
   final int[] chart = getMyRace().getAgingChart();
   final int diff = chart[Race.AGE_ANCIENT] - chart[Race.AGE_VENERABLE];
   age = age - chart[Race.AGE_ANCIENT];
   final int num = (diff > 0) ? (int) Math.abs(Math.floor(CMath.div(age, diff))) : 0;
   if (num <= 0) return Race.AGE_DESCS[cat];
   return Race.AGE_DESCS[cat] + " " + CMath.convertToRoman(num);
 }
Exemple #22
0
  private double calculateEnchantedDamage(double basicDamage, GlowLivingEntity entity) {
    int level = 0; // TODO: calculate explosion protection level of entity's equipment

    if (level > 0) {
      float sub = level * 0.15f;
      double damage = basicDamage * sub;
      damage = Math.floor(damage);
      return basicDamage - damage;
    }

    return basicDamage;
  }
Exemple #23
0
 boolean solve2() {
   int t = nextInt();
   if (t == 0) return false;
   int n = nextInt();
   Tower[] towers = new Tower[t];
   for (int i = 0; i < t; i++) {
     towers[i] = new Tower(new Point(nextInt(), nextInt()), nextInt());
   }
   n++;
   Point[] p = new Point[n];
   for (int i = 0; i < n; i++) {
     p[i] = new Point(nextInt(), nextInt());
   }
   // System.err.println(Arrays.toString(p));
   ArrayList<Point> points = new ArrayList<Point>();
   double r = 1;
   for (int i = 0; i < n - 1; i++) {
     double dist = p[i].dist(p[i + 1]) - (1 - r);
     int e = (int) Math.floor(dist + 1 - EPS);
     Point v = p[i + 1].subtract(p[i]).norm();
     for (int j = 0; j < e; j++) {
       points.add(p[i].add(v.multiply(j).add(v.multiply(1 - r))));
     }
     r = p[i + 1].dist(points.get(points.size() - 1));
   }
   if (p[n - 1].dist(points.get(points.size() - 1)) > 0.5 - EPS) {
     points.add(p[n - 1]);
   }
   // System.err.println(points);
   char last = 0;
   ArrayList<String> ans = new ArrayList<String>();
   for (int i = 0; i < points.size(); i++) {
     double maxP = Integer.MIN_VALUE;
     char here = 0;
     for (int j = 0; j < t; j++) {
       double w = towers[j].get(points.get(i));
       if (maxP < w - EPS) {
         maxP = w;
         here = (char) (j + 'A');
       }
     }
     if (here != last) {
       ans.add("(" + i + "," + here + ")");
     }
     last = here;
   }
   for (int i = 0; i < ans.size(); i++) {
     if (i != 0) out.print(" ");
     out.print(ans.get(i));
   }
   out.println();
   return true;
 }
Exemple #24
0
  public void run() {
    ArrayList<Double> output = new ArrayList();

    while (true) {
      int numStudents = Integer.parseInt(Main.ReadLn(1000000));

      double runningTotal = 0;
      double current = 0;
      double average = 0;
      double runningTransfer = 0;

      if (numStudents == 0) break;
      else if (numStudents > 1000) throw new NumberFormatException();
      else if (numStudents % 2 == 0) throw new NumberFormatException();

      ArrayList<Double> expenses = new ArrayList();

      for (int i = 0; i < numStudents; i++) {
        current = Double.parseDouble(Main.ReadLn(1000000));
        runningTotal = runningTotal + current;

        expenses.add(current);

        if (current > 10000 || current < 0) throw new NumberFormatException();
      }

      average = Math.floor((runningTotal * 100) / numStudents) / 100;

      for (Double d : expenses) {
        if (d.doubleValue() < average) {
          runningTransfer = runningTransfer + (average - d.doubleValue());
        }
      }

      output.add(runningTransfer);
    }

    Iterator it = output.iterator();
    StringBuilder builder = new StringBuilder();

    while (it.hasNext()) {
      builder.append("$" + String.format("%.2f", it.next()));

      if (it.hasNext()) {
        builder.append("\n");
      } else {
        break;
      }
    }

    System.out.println(builder);
  }
  public Color getColorAt(double x, double y) {
    int col = img.getRGB((int) x, (int) y);
    double r = col >> 16 & 0xff;
    double g = col >> 8 & 0xff;
    double b = col & 0xff;

    int col_r = img.getRGB((int) x + 1, (int) y);
    double rr = col_r >> 16 & 0xff;
    double gr = col_r >> 8 & 0xff;
    double br = col_r & 0xff;

    double fact = x - Math.floor(x);

    double rf = r + (rr - r) * fact;
    double gf = g + (gr - g) * fact;
    double bf = b + (br - b) * fact;

    col = img.getRGB((int) x, (int) y + 1);
    r = col >> 16 & 0xff;
    g = col >> 8 & 0xff;
    b = col & 0xff;

    col_r = img.getRGB((int) x + 1, (int) y + 1);
    rr = col_r >> 16 & 0xff;
    gr = col_r >> 8 & 0xff;
    br = col_r & 0xff;

    double rf2 = r + (rr - r) * fact;
    double gf2 = g + (gr - g) * fact;
    double bf2 = b + (br - b) * fact;

    fact = y - Math.floor(y);

    double rff = rf + (rf2 - rf) * fact;
    double gff = gf + (gf2 - gf) * fact;
    double bff = bf + (bf2 - bf) * fact;

    return new Color((int) rff, (int) gff, (int) bff);
  }
Exemple #26
0
  public void accumulateBilinear(double x, double y, double s)
        /* Bilinearly accumulates 's' to the four integer grid points surrounding
         *   the continuous coordinate (x, y). */
      {
    double xpf = Math.floor(x);
    int xi = (int) xpf;
    double xf = x - xpf;

    double ypf = Math.floor(y);
    int yi = (int) ypf;
    double yf = y - ypf;

    double b;
    b = (1.0 - xf) * (1.0 - yf);
    accumulate(xi, yi, s * b);
    b = xf * (1.0 - yf);
    accumulate(xi + 1, yi, s * b);
    b = (1.0 - xf) * yf;
    accumulate(xi, yi + 1, s * b);
    b = xf * yf;
    accumulate(xi + 1, yi + 1, s * b);
  }
 private static int estimateRowOverhead(final int count) {
   // calculate row overhead
   try (final OpOrder.Group group = new OpOrder().start()) {
     int rowOverhead;
     MemtableAllocator allocator = MEMORY_POOL.newAllocator();
     ConcurrentNavigableMap<PartitionPosition, Object> partitions = new ConcurrentSkipListMap<>();
     final Object val = new Object();
     for (int i = 0; i < count; i++)
       partitions.put(
           allocator.clone(
               new BufferDecoratedKey(new LongToken(i), ByteBufferUtil.EMPTY_BYTE_BUFFER), group),
           val);
     double avgSize = ObjectSizes.measureDeep(partitions) / (double) count;
     rowOverhead =
         (int) ((avgSize - Math.floor(avgSize)) < 0.05 ? Math.floor(avgSize) : Math.ceil(avgSize));
     rowOverhead -= ObjectSizes.measureDeep(new LongToken(0));
     rowOverhead += AtomicBTreePartition.EMPTY_SIZE;
     allocator.setDiscarding();
     allocator.setDiscarded();
     return rowOverhead;
   }
 }
Exemple #28
0
 public void printDebug() {
   Iterator<StringBuilder> it = rows.iterator();
   int i = 0;
   System.out.println(
       "    " + StringUtils.repeatString("0123456789", (int) Math.floor(getWidth() / 10) + 1));
   while (it.hasNext()) {
     String row = it.next().toString();
     String index = Integer.toString(i);
     if (i < 10) index = " " + index;
     System.out.println(index + " (" + row + ")");
     i++;
   }
 }
Exemple #29
0
  public void tick() {
    int newID = contents[0] == null ? 0 : Item.getId(contents[0].getItem());
    // Has the item been changed?
    if (newID != lastID) {
      // Then reset the progress!
      myCookTime = 0.0D;
      lastID = newID;
      // And, most important: change the melt speed
      meltSpeed = getMeltSpeed(contents[0]);
    }
    // So, can we now finally burn?
    if (canBurn() && !isBurning() && (getFuelTime(contents[1]) > 0)) {
      // I have no idea what "ticksForCurrentFuel" is good for, but it
      // works fine like this
      burnTime = ticksForCurrentFuel = getFuelTime(contents[1]);
      // Before we remove the item: how fast does it burn?
      burnSpeed = getBurnSpeed(contents[1]);
      // If it's a container item (lava bucket), we only consume its
      // contents (not like evil Notch!)

      // If it's not a container, consume it! Om nom nom nom!
      {
        contents[1].count--;
        // Let 0 be null
        if (contents[1].count <= 0) {
          contents[1] = null;
        }
      }
    }
    // Now, burning?
    if (isBurning()) {
      // Then move on
      burnTime--;
      // I'm using a double here because of the custom recipes.
      // The faster this fuel burns and the faster the recipe melts, the
      // faster we're done
      myCookTime += burnSpeed * meltSpeed;
      // Finished burning?
      if (myCookTime >= 200.0D) {
        myCookTime -= 200.0D;
        burn();
      }
    }
    // If it's not burning, we reset the burning progress!
    else {
      myCookTime = 0.0D;
    }
    // And for the display (I'm using floor rather than round to not cause
    // the client to do shit when we not really reached 200):
    cookTime = (int) Math.floor(myCookTime);
  }
Exemple #30
0
  public double getBilinear(double x, double y)
        /* Returns: the bilinearly-interpolated value of the continuous field
         *   at (x, y).
         * Requires: (x, y) is inside the domain of the field */
      {
    if (!inBounds(x, y))
      throw new RuntimeException(
          "ScalarImage.getBilinear: RuntimeException at (" + x + "," + y + ")");

    int xi, yi;
    double xf, yf;
    if (x == (double) (width - 1)) {
      xi = width - 2;
      xf = 1.0;
    } else {
      double xpf = Math.floor(x);
      xi = (int) xpf;
      xf = x - xpf;
    }
    if (y == (double) (height - 1)) {
      yi = height - 2;
      yf = 1.0;
    } else {
      double ypf = Math.floor(y);
      yi = (int) ypf;
      yf = y - ypf;
    }

    double b1 = get(xi, yi);
    double b2 = get(xi + 1, yi);
    double b3 = get(xi, yi + 1);
    double b4 = get(xi + 1, yi + 1);

    double bb1 = b1 + xf * (b2 - b1);
    double bb2 = b3 + xf * (b4 - b3);

    return bb1 + yf * (bb2 - bb1);
  }