private void adjustDateLineCrossingPoints() {
      ArrayList<LatLon> corners = new ArrayList<LatLon>(Arrays.asList(sw, se, nw, ne));
      if (!LatLon.locationsCrossDateLine(corners)) return;

      double lonSign = 0;
      for (LatLon corner : corners) {
        if (Math.abs(corner.getLongitude().degrees) != 180)
          lonSign = Math.signum(corner.getLongitude().degrees);
      }

      if (lonSign == 0) return;

      if (Math.abs(sw.getLongitude().degrees) == 180
          && Math.signum(sw.getLongitude().degrees) != lonSign)
        sw = new Position(sw.getLatitude(), sw.getLongitude().multiply(-1), sw.getElevation());
      if (Math.abs(se.getLongitude().degrees) == 180
          && Math.signum(se.getLongitude().degrees) != lonSign)
        se = new Position(se.getLatitude(), se.getLongitude().multiply(-1), se.getElevation());
      if (Math.abs(nw.getLongitude().degrees) == 180
          && Math.signum(nw.getLongitude().degrees) != lonSign)
        nw = new Position(nw.getLatitude(), nw.getLongitude().multiply(-1), nw.getElevation());
      if (Math.abs(ne.getLongitude().degrees) == 180
          && Math.signum(ne.getLongitude().degrees) != lonSign)
        ne = new Position(ne.getLatitude(), ne.getLongitude().multiply(-1), ne.getElevation());
    }
Exemple #2
0
  private void doesEatRegime() {
    if (isEnd) return;

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

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

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

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

    if (System.currentTimeMillis() - currentTime > 10000) {
      regimeRectangle.setX(1200);
      isRegime = false;
    }
  }
 double oblicz_wage(int x1, int y1, int x2, int y2) {
   double x = (double) Math.pow(Math.abs((x1 - x2)), 2);
   double y = (double) Math.pow(Math.abs((y1 - y2)), 2);
   double wynik = Math.sqrt(x + y) * 1000;
   wynik = Math.round(wynik);
   return (wynik / 1000);
 }
Exemple #4
0
  public Panther() {
    super();
    final Random randomizer = new Random(System.currentTimeMillis());

    username = "******";
    setDescription(
        "A powerful cat with a deep chest and muscular limbs, covered in midnight black fur.");
    setDisplayText("A panther slowly stalks prey.");
    CMLib.factions().setAlignment(this, Faction.Align.NEUTRAL);
    setMoney(0);
    basePhyStats.setWeight(20 + Math.abs(randomizer.nextInt() % 45));
    setWimpHitPoint(2);

    basePhyStats.setWeight(200 + Math.abs(randomizer.nextInt() % 55));

    baseCharStats().setStat(CharStats.STAT_INTELLIGENCE, 1);
    baseCharStats().setStat(CharStats.STAT_STRENGTH, 12);
    baseCharStats().setStat(CharStats.STAT_DEXTERITY, 17);
    baseCharStats().setMyRace(CMClass.getRace("GreatCat"));
    baseCharStats().getMyRace().startRacing(this, false);

    basePhyStats().setDamage(8);
    basePhyStats().setSpeed(2.0);
    basePhyStats().setAbility(0);
    basePhyStats().setLevel(4);
    basePhyStats().setArmor(80);

    baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(), 20, basePhyStats().level()));

    recoverMaxState();
    resetToMaxState();
    recoverPhyStats();
    recoverCharStats();
  }
Exemple #5
0
 public static int threeSumClosest(int[] nums, int target) {
   int small = Integer.MAX_VALUE;
   int result = 0;
   int j = 0, k = nums.length - 1;
   Arrays.sort(nums);
   for (int i = 0; i < nums.length; i++) {
     int sum = 0;
     j = i + 1;
     k = nums.length - 1;
     while (j < k) {
       sum = nums[i] + nums[j] + nums[k];
       if (sum > target) k--;
       else if (sum < target) j++;
       else {
         k--;
         j++;
       }
       if (Math.abs(sum - target) < small) {
         small = Math.abs(sum - target);
         result = sum;
       }
     }
   }
   return result;
 }
Exemple #6
0
  public StoneGiant() {
    super();
    Random randomizer = new Random(System.currentTimeMillis());

    Username = "******";
    setDescription("A tall humanoid standing about 18 feet tall with gray, hairless flesh.");
    setDisplayText("A Stone Giant glares at you.");
    CMLib.factions().setAlignment(this, Faction.ALIGN_EVIL);
    setMoney(0);
    baseEnvStats.setWeight(8000 + Math.abs(randomizer.nextInt() % 1001));

    baseCharStats().setStat(CharStats.STAT_INTELLIGENCE, 8 + Math.abs(randomizer.nextInt() % 3));
    baseCharStats().setStat(CharStats.STAT_STRENGTH, 20);
    baseCharStats().setStat(CharStats.STAT_DEXTERITY, 13);

    baseEnvStats().setDamage(20);
    baseEnvStats().setSpeed(1.0);
    baseEnvStats().setAbility(0);
    baseEnvStats().setLevel(14);
    baseEnvStats().setArmor(0);

    baseState.setHitPoints(CMLib.dice().roll(baseEnvStats().level(), 20, baseEnvStats().level()));

    addBehavior(CMClass.getBehavior("Aggressive"));

    recoverMaxState();
    resetToMaxState();
    recoverEnvStats();
    recoverCharStats();
  }
Exemple #7
0
 static void recursive(List<List<String>> nqueens, List<Integer> list, int n) {
   if (list.size() == n) {
     List<String> board = new ArrayList<String>();
     for (int i = 0; i < n; i++) {
       StringBuilder row = new StringBuilder();
       for (int j = 0; j < n; j++) row.append(list.get(i) == j ? "Q" : ".");
       board.add(row.toString());
     }
     nqueens.add(board);
     list.remove(list.size() - 1);
     return;
   }
   for (int i = 0; i < n; i++) {
     boolean isValid = true;
     int x1 = list.size();
     int y1 = i;
     for (int j = 0; j < list.size(); j++) {
       int x2 = j;
       int y2 = list.get(j);
       if (y1 == y2 || Math.abs(x1 - x2) == Math.abs(y1 - y2)) {
         isValid = false;
         break;
       }
     }
     if (isValid) {
       list.add(i);
       recursive(nqueens, list, n);
     }
   }
   if (!list.isEmpty()) list.remove(list.size() - 1);
 }
Exemple #8
0
  /**
   * Get the bounding rectangle
   *
   * @return minimum bounding rectangle
   */
  public BoundingRectangle2D getBounds() {
    if (boundsChanged == true) {
      boolean first = true;
      double minX = 0;
      double maxX = 0;
      double minY = 0;
      double maxY = 0;

      for (Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
        Vector2D vertex = (Vector2D) e.nextElement();
        if (first) {
          minX = vertex.getX();
          maxX = vertex.getX();
          minY = vertex.getY();
          maxY = vertex.getY();
          first = false;
        } else {
          minX = Math.min(minX, vertex.getX());
          maxX = Math.max(maxX, vertex.getX());
          minY = Math.min(minY, vertex.getY());
          maxY = Math.max(maxY, vertex.getY());
        }
      }

      bounds.set(minX, minY, Math.abs(maxX - minX), Math.abs(maxY - minY));

      boundsChanged = false;
    }

    return bounds;
  }
  public Point getEmptyPosition(Dimension spriteSize) {
    Rectangle trialSpaceOccupied = new Rectangle(0, 0, spriteSize.width, spriteSize.height);
    Random rand = new Random(System.currentTimeMillis());
    boolean empty = false;
    int numTries = 0;

    // Search for an empty position
    while (!empty && numTries++ < 100) {
      // Get a trial position
      trialSpaceOccupied.x = Math.abs(rand.nextInt() % backgroundImage.getSize().width);
      trialSpaceOccupied.y = Math.abs(rand.nextInt() % backgroundImage.getSize().height);
      // Iterate through existing
      // sprites, checking if position
      // is empty
      boolean collision = false;
      for (int cnt = 0; cnt < size(); cnt++) {
        Rectangle testSpaceOccupied = ((Sprite) elementAt(cnt)).getSpaceOccupied();
        if (trialSpaceOccupied.intersects(testSpaceOccupied)) {
          collision = true;
        } // end if
      } // end for loop
      empty = !collision;
    } // end while loop
    return new Point(trialSpaceOccupied.x, trialSpaceOccupied.y);
  } // end getEmptyPosition()
Exemple #10
0
  public static double FDRExactPrint(Map observed, Map[] expected, double k) {
    EmpiricalDistribution[] randomTDist = makeDistributions(observed, expected);
    double RkEstimate = randomTDist[0].getNumberOfValuesLargerThan(Math.abs(k));
    double[] VkVector = new double[randomTDist.length];
    for (int i = 0; i < randomTDist.length; i++) {
      VkVector[i] = randomTDist[i].getNumberOfValuesLargerThan(Math.abs(k));
    }
    double VkEstimate = expected(VkVector);

    double Rk = countNumGreaterThanThresh(observed, k);
    double[] Vk = countNumGreaterThanThresh(expected, k);
    double EVk = expected(Vk);

    double FDRkEstimate = VkEstimate / RkEstimate;
    double FDRk = EVk / Rk;

    System.err.println(
        k
            + " "
            + FDRkEstimate
            + " "
            + FDRk
            + " "
            + RkEstimate
            + " "
            + VkEstimate
            + " "
            + Rk
            + " "
            + EVk);

    // double FDRk=EVk/Rk;
    return FDRk;
  }
Exemple #11
0
  private void addRegime() {
    if (isEnd) return;

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

    feedCounter1 = feedCounter2;

    currentTime = System.currentTimeMillis();

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

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

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

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

    isRegime = true;
  }
  protected String buildAssertForArray(String expression, Object array) {
    Random r = new Random();
    String type = array.getClass().getCanonicalName();
    String arrayLocalVar1 = "array_" + Math.abs(r.nextInt());
    String arrayLocalVar2 = "array_" + Math.abs(r.nextInt());

    String forLoop =
        "\tfor(int ii = 0; ii <"
            + arrayLocalVar1
            + ".length; ii++) {\n\t\t"
            + junitAssertClassName
            + ".assertEquals("
            + arrayLocalVar1
            + "[ii], "
            + arrayLocalVar2
            + "[ii]);\n\t}";

    return type
        + " "
        + arrayLocalVar1
        + " = "
        + primitiveArrayToString(array)
        + ";\n\t"
        + type
        + " "
        + arrayLocalVar2
        + " = "
        + "("
        + type
        + ")"
        + expression
        + ";\n"
        + forLoop;
  }
Exemple #13
0
 public static int distanceLevel(String geohash1, String geohash2, int treeDepth) {
   long[] bits1 = decomposeLatLng(geohash1, treeDepth);
   long[] bits2 = decomposeLatLng(geohash2, treeDepth);
   long latDelta = Math.abs(bits1[1] - bits2[1]);
   long lngDelta = Math.abs(bits1[0] - bits2[0]);
   return (int) Math.max(latDelta, lngDelta);
 }
 /**
  * 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);
     }
 }
Exemple #15
0
  public InvisibleStalker() {
    super();
    Random randomizer = new Random(System.currentTimeMillis());

    username = "******";
    setDescription("A shimmering blob of energy.");
    setDisplayText("An invisible stalker hunts here.");
    CMLib.factions().setAlignment(this, Faction.ALIGN_NEUTRAL);
    setMoney(0);
    basePhyStats.setWeight(10 + Math.abs(randomizer.nextInt() % 10));

    baseCharStats().setStat(CharStats.STAT_INTELLIGENCE, 12 + Math.abs(randomizer.nextInt() % 3));
    baseCharStats().setStat(CharStats.STAT_STRENGTH, 20);
    baseCharStats().setStat(CharStats.STAT_DEXTERITY, 13);

    basePhyStats().setDamage(16);
    basePhyStats().setSpeed(1.0);
    basePhyStats().setAbility(0);
    basePhyStats().setLevel(4);
    basePhyStats().setArmor(0);
    basePhyStats().setDisposition(basePhyStats().disposition() | PhyStats.IS_INVISIBLE);

    baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(), 20, basePhyStats().level()));

    addBehavior(CMClass.getBehavior("Aggressive"));
    addBehavior(CMClass.getBehavior("Mobile"));

    recoverMaxState();
    resetToMaxState();
    recoverPhyStats();
    recoverCharStats();
  }
Exemple #16
0
  /**
   * The transaction registers the negated sum of the shares as an expense by a group of
   * contributors. Additionally all the shares in the map are registered with the same entry id.
   * Those names in the deals map that are empty <code>String</code> trigger transfers of internal
   * amounts. Such an internal transfer is not allowed if the transaction causes a negative total.
   *
   * @param deals the names of the contributors and their contributions who expended an amount
   *     matching the negated sum of the deals
   * @param comment a <code>String</code> to make the transaction recognizable
   * @param shares a <code>ShareMap</code> containing the shares of participants involved
   * @return the entry id of the transaction or a negative value in case the transaction failed
   */
  public int performComplexExpense(ShareMap deals, String comment, ShareMap shares) {
    int entryId = -1;

    int transactionCode = 3;
    int flags = composeFlags(transactionCode, true);

    double amount = deals.sum();
    if (Math.abs(amount + shares.sum()) < ShareUtil.delta) {
      if (deals.option != null)
        switch (deals.option) {
          default:
            setDebtLimit(1000. * deals.option);
            break;
        }

      if (deals.rawMap.containsKey(kitty))
        entryId = performTransfer(kitty, -deals.rawMap.get(kitty), comment, kitty);
      else entryId = getNewEntryId();

      Collection<String> dealers = ShareUtil.filter(deals.rawMap.keySet(), true, ShareUtil.isKitty);

      for (String name : dealers) {
        long rowId =
            addRecord(
                entryId,
                name,
                deals.rawMap.get(name),
                currency,
                Helper.timestampNow(),
                comment,
                flags);
        if (rowId < 0) {
          entryId = -1;
          break;
        }
      }
    } else
      Log.w(
          TAG,
          String.format(
              "the sum of the deals (%f) for '%s' doesn't match the sum of the shares (%f)",
              amount, comment, shares.sum()));

    if (entryId > -1) {
      if (allocate(flags, entryId, shares.rawMap)) {
        Log.i(
            TAG,
            String.format(
                "entry %d: %s expended %f %s for '%s' shared by %s",
                entryId, deals.toString(), Math.abs(amount), currency, comment, shares.toString()));
      } else {
        removeEntry(entryId);
        entryId = -1;
      }
    }

    if (entryId < 0) removeEntry(entryId);

    return entryId;
  }
Exemple #17
0
 // if left is true --> left is the anchoring End(IS element-known)
 // --> then the right side is the insertion position so we check the rightside.
 public boolean isInsertionPair(Record other, boolean left) {
   if (left) {
     // --this--><--other--
     if (this.fwd2 && !other.fwd2) {
       if ((this.start2 < other.start2)
           && (other.end2 > this.end2)
           && (Math.abs(this.end2 - other.start2) <= 100)) return true;
     }
     // --other--><--this--
     else if (other.fwd2 && !this.fwd2) {
       if ((other.start2 < this.start2)
           && (this.end2 > other.end2)
           && (Math.abs(other.end2 - this.start2) <= 100)) return true;
     }
   } else {
     // --this--><--other--
     if (this.fwd1 && !other.fwd1) {
       if ((this.start1 < other.start1)
           && (other.end1 > this.end1)
           && (Math.abs(this.end1 - other.start1) <= 100)) return true;
     }
     // --other--><--this--
     else if (other.fwd1 && !this.fwd1) {
       if ((other.start1 < this.start1)
           && (this.end1 > other.end1)
           && (Math.abs(other.end1 - this.start1) <= 100)) return true;
     }
   }
   return false;
 }
Exemple #18
0
  private void addFeed() {
    if (isEnd) return;

    if (isFeed) return;

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

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

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

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

    isFeed = true;

    addObstacle();
  }
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    // Read in the number of elements
    int n = in.nextInt();

    // Store the list of cities in an array
    int[] cities = new int[n];
    for (int i = 0; i < n; i++) {
      cities[i] = in.nextInt();
    }

    // Since the list is in ascending order (as specified in the problem
    // statement), the minimum difference will be to either the left or right
    // of the element, and the maximum will either be to the first or last
    // element
    for (int i = 0; i < n; i++) {
      int left = Integer.MAX_VALUE;
      int right = Integer.MAX_VALUE;
      if (i > 0) {
        left = Math.abs(cities[i] - cities[i - 1]);
      }
      if (i < n - 1) {
        right = Math.abs(cities[i] - cities[i + 1]);
      }
      int min = Math.min(left, right);

      left = Math.abs(cities[i] - cities[0]);
      right = Math.abs(cities[i] - cities[n - 1]);
      int max = Math.max(left, right);

      System.out.println(min + " " + max);
    }
  }
Exemple #20
0
  @Override
  public BoundingBox getBounds() {
    // If there are no charges, return an empty box.
    if (charges.size() <= 0) return new BoundingBox(0, 0, 0, 0, 0, 0);

    if (cachedBounds == null) {
      // Start with the box of the first charge.
      Charge c = charges.get(0);
      double ext = Math.abs(c.w);
      double corr = 1.0 + (0.1 / hardness); // see note
      cachedBounds =
          new BoundingBox(
              new Vec3(c.x - ext, c.y - ext, c.z - ext).times(corr),
              new Vec3(c.x + ext, c.y + ext, c.z + ext).times(corr));

      // A note on "corr":
      // As blobs are blobby, we can't use their weight/radius
      // directly. This would result in unwanted cut-off's. To
      // correct this, we extend the bounding box of a charge "a
      // bit". That "bit" can be smaller if the charge is harder.

      // Iteratively add the remaining charges.
      for (int i = 1; i < charges.size(); i++) {
        c = charges.get(i);
        ext = Math.abs(c.w);
        corr = 1.0 + (0.1 / hardness);
        cachedBounds.extend(
            new BoundingBox(
                new Vec3(c.x - ext, c.y - ext, c.z - ext).times(corr),
                new Vec3(c.x + ext, c.y + ext, c.z + ext).times(corr)));
      }
    }

    return cachedBounds;
  }
Exemple #21
0
 public boolean ok(String out, String reference) {
   // log.fine("out1: " + a);
   // log.fine("out2: " + b);
   Scanner sa = new Scanner(out);
   Scanner sb = new Scanner(reference);
   while (sa.hasNext() && sb.hasNext()) {
     if (sa.hasNextDouble() || sb.hasNextDouble()) {
       if (!sa.hasNextDouble() || !sb.hasNextDouble()) return true;
       double da = sa.nextDouble();
       double db = sb.nextDouble();
       double d_abs = Math.abs(da - db);
       double d_rel = d_abs / Math.abs(db);
       if (!(d_abs < EPS || d_rel < EPS)) {
         log.fine("NOK, " + da + " too far from " + db);
         return false;
       }
     } else {
       String xa = sa.next();
       String xb = sb.next();
       if (!xa.equals(xb)) {
         log.fine("NOK, " + xa + " != " + xb);
         return false;
       }
     }
   }
   if (sa.hasNext() || sb.hasNext()) {
     log.fine("NOK: different number of tokens.");
     return false;
   }
   return true;
 }
Exemple #22
0
 /*
 public void updateCollision(Player b) {
  Point topLeft = new Point();
  topLeft.x = (int) b.getPosition().getX();
  topLeft.y = (int) b.getPosition().getY();
  Point topRight = new Point();
  topRight.x = (int) (b.getPosition().getX() + b.RADIUS * 2);
  topRight.y = (int) b.getPosition().getY();
  Point bottomLeft = new Point();
  bottomLeft.x = (int) b.getPosition().getX();
  bottomLeft.y = (int) (b.getPosition().getY() + b.RADIUS * 2);
  Point bottomRight = new Point();
  bottomRight.x = (int) (b.getPosition().getX() + b.RADIUS * 2);
  bottomRight.y = (int) (b.getPosition().getY() + b.RADIUS * 2);
  if (poly.contains(topLeft) || poly.contains(topRight) || poly.contains(bottomRight) || poly.contains(bottomLeft)) {
   reflect (b);
   System.out.println("TRIGGERED");
  }
 }
 */
 public void reflect(Player b) {
   double barrierSlope = ((double) (y1 - y2)) / ((double) (x1 - x2));
   if (barrierSlope == 1) {
     Point p = new Point();
     p.x = (int) b.getVel().getY();
     p.y = (int) b.getVel().getX();
   }
   if (Math.abs(barrierSlope) < 1) {
     System.out.print("shallow");
     double newX = (1 - barrierSlope) * b.getVel().getX();
     double newY = -1 * (b.VEL * 2) - newX;
     Point p = new Point();
     p.x = (int) newX;
     p.y = (int) newY;
     b.setVel(p);
   }
   if (Math.abs(barrierSlope) > 1) {
     System.out.println("steep");
     double newY = (1 - 1 / barrierSlope) * b.getVel().getY();
     double newX = -1 * (b.VEL * 2) - newY;
     Point p = new Point();
     p.x = (int) newX;
     p.y = (int) newY;
     b.setVel(p);
   }
 }
  private boolean isNotSeparatorRoom(Room separatorRoom, Room joinerRoom) {
    if (separatorRoom == null) return false;

    if (separatorRoom.isRotatable() && separatorRoom != joinerRoom) {
      separatorRoom.rotateRightRotatedType();
      rotationMap.put(
          separatorRoom.getDistance() - Math.abs(separatorRoom.getRotation()), separatorRoom);
      return false;
    }

    if (separatorRoom.isRotatable()
        && separatorRoom == joinerRoom
        && separatorRoom.getExit() != null) {
      if (separatorRoom.getRotatedType() == RoomType.TYPE_7) {
        separatorRoom.rotateRightRotatedType();
      } else if (separatorRoom.getRotatedType() == RoomType.TYPE_8
          && separatorRoom.getEntrance() == Direction.LEFT) {
        separatorRoom.rotateLeftRotatedType();
      } else if (separatorRoom.getRotatedType() == RoomType.TYPE_8
          && separatorRoom.getEntrance() == Direction.RIGHT) {
        separatorRoom.rotateRightRotatedType();
      } else if (separatorRoom.getRotatedType() == RoomType.TYPE_9
          && separatorRoom.getEntrance() == Direction.TOP) {
        separatorRoom.rotateLeftRotatedType();
      } else if (separatorRoom.getRotatedType() == RoomType.TYPE_9
          && separatorRoom.getEntrance() == Direction.LEFT) {
        separatorRoom.rotateRightRotatedType();
      }
      rotationMap.put(
          separatorRoom.getDistance() - Math.abs(separatorRoom.getRotation()), separatorRoom);
      return false;
    }

    return true;
  }
Exemple #24
0
  /**
   * Uses the Haversine formula to calculate the distnace between to lat-long coordinates
   *
   * @param latitude1 The first point's latitude
   * @param longitude1 The first point's longitude
   * @param latitude2 The second point's latitude
   * @param longitude2 The second point's longitude
   * @return The distance between the two points in meters
   */
  public static double CalculateDistance(
      double latitude1, double longitude1, double latitude2, double longitude2) {
    /*
    Haversine formula:
    A = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
    C = 2.atan2(√a, √(1−a))
    D = R.c
    R = radius of earth, 6371 km.
    All angles are in radians
    */

    double deltaLatitude = Math.toRadians(Math.abs(latitude1 - latitude2));
    double deltaLongitude = Math.toRadians(Math.abs(longitude1 - longitude2));
    double latitude1Rad = Math.toRadians(latitude1);
    double latitude2Rad = Math.toRadians(latitude2);

    double a =
        Math.pow(Math.sin(deltaLatitude / 2), 2)
            + (Math.cos(latitude1Rad)
                * Math.cos(latitude2Rad)
                * Math.pow(Math.sin(deltaLongitude / 2), 2));

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return 6371 * c * 1000; // Distance in meters
  }
Exemple #25
0
 @Override
 public void map(Chunk chks[], NewChunk nchks[]) {
   long rstart = chks[0]._start;
   int rlen = chks[0]._len; // Total row count
   int rx = 0; // Which row to in/ex-clude
   int rlo = 0; // Lo/Hi for this block of rows
   int rhi = rlen;
   while (true) { // Still got rows to include?
     if (_rows != null) { // Got a row selector?
       if (rx >= _rows.length) break; // All done with row selections
       long r = _rows[rx++] - 1; // Next row selector
       if (r < 0) { // Row exclusion
         if (rx > 0 && _rows[rx - 1] < _rows[rx]) throw H2O.unimpl();
         long er = Math.abs(r) - 2;
         if (er < rstart) continue;
         // scoop up all of the rows before the first exclusion
         if (rx == 1 && ((int) (er + 1 - rstart)) > 0 && _ex) {
           rlo = (int) rstart;
           rhi = (int) (er - rstart);
           _ex = false;
           rx--;
         } else {
           rlo = (int) (er + 1 - rstart);
           // TODO: handle jumbled row indices ( e.g. -c(1,5,3) )
           while (rx < _rows.length && (_rows[rx] + 1 == _rows[rx - 1] && rlo < rlen)) {
             if (rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl();
             rx++;
             rlo++; // Exclude consecutive rows
           }
           rhi = rx >= _rows.length ? rlen : (int) Math.abs(_rows[rx] - 1) - 2;
           if (rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl();
         }
       } else { // Positive row list?
         if (r < rstart) continue;
         rlo = (int) (r - rstart);
         rhi = rlo + 1; // Stop at the next row
         while (rx < _rows.length && (_rows[rx] - 1 - rstart) == rhi && rhi < rlen) {
           rx++;
           rhi++; // Grab sequential rows
         }
       }
     }
     // Process this next set of rows
     // For all cols in the new set
     for (int i = 0; i < _cols.length; i++) {
       Chunk oc = chks[_cols[i]];
       NewChunk nc = nchks[i];
       if (oc._vec.isInt()) { // Slice on integer columns
         for (int j = rlo; j < rhi; j++)
           if (oc.isNA0(j)) nc.addNA();
           else nc.addNum(oc.at80(j), 0);
       } else { // Slice on double columns
         for (int j = rlo; j < rhi; j++) nc.addNum(oc.at0(j));
       }
     }
     rlo = rhi;
     if (_rows == null) break;
   }
 }
  /**
   * Set the Y magnification factor
   *
   * @param tym the Y magnification factor
   */
  public final void setYMagnitude(double tym) {
    double ym = tym;
    if (Math.abs(ym) < MIN_MAGNITUDE) ym = MIN_MAGNITUDE;

    if (Math.abs(ym) > MAX_MAGNITUDE) ym = MAX_MAGNITUDE;

    yMagnitude = ym;
  }
Exemple #27
0
 /**
  * Determines whether this circle is adjacent to another.
  *
  * @param circle Circle we're comparing with.
  */
 public boolean adjacentTo(AtroposCircle circle) {
   return (((Math.abs(this.height - circle.height()) == 1)
           && (this.leftDistance == circle.leftDistance()))
       || ((Math.abs(this.leftDistance - circle.leftDistance()) == 1)
           && (this.height == circle.height()))
       || ((Math.abs(this.height - circle.height()) == 1)
           && (this.rightDistance == circle.rightDistance())));
 }
  /**
   * Set the X magnification factor
   *
   * @param txm the X magnification factor
   */
  public final void setXMagnitude(double txm) {
    double xm = txm;
    if (Math.abs(xm) < MIN_MAGNITUDE) xm = MIN_MAGNITUDE;

    if (Math.abs(xm) > MAX_MAGNITUDE) xm = MAX_MAGNITUDE;

    xMagnitude = xm;
  }
 @Test
 public void percentileTestSpecific()
     throws IOException, SqlParseException, SQLFeatureNotSupportedException {
   Aggregations result =
       query(String.format("SELECT PERCENTILES(age,25.0,75.0) x FROM %s/account", TEST_INDEX));
   Percentiles percentiles = result.get("x");
   Assert.assertTrue(Math.abs(percentiles.percentile(25.0) - 25.0) < 0.001);
   Assert.assertTrue(Math.abs(percentiles.percentile(75.0) - 35.0) < 0.001);
 }
Exemple #30
0
 public static boolean fuzzyEqual(double x, double y, double epsilon) {
   if (Math.abs(x - y) <= epsilon) {
     return true;
   }
   if ((Math.abs(x) <= epsilon) || (Math.abs(y) <= epsilon)) {
     return false;
   }
   return (Math.abs((x - y) / x) <= epsilon) || (Math.abs((x - y) / y) <= epsilon);
 }