Esempio n. 1
0
  // ************************************
  public static void initWeights() {

    for (int j = 0; j < numHidden; j++) {
      weightsHO[j] = (Math.random() - 0.5) / 2;
      for (int i = 0; i < numInputs; i++) weightsIH[i][j] = (Math.random() - 0.5) / 5;
    }
  }
  public int getWrongTwo() {
    int wrongTwo = (int) (Math.random() * (Math.pow(2, bits)));
    while (wrongTwo == answer || wrongTwo == wrongOne)
      wrongOne = (int) (Math.random() * (Math.pow(2, bits)));

    return wrongTwo;
  }
Esempio n. 3
0
 private static double nextRandom() {
   int pos = (int) (java.lang.Math.random() * BUFFER_SIZE);
   if (pos == BUFFER_SIZE) pos = BUFFER_SIZE - 1;
   double r = buffer[pos];
   buffer[pos] = java.lang.Math.random();
   return r;
 }
Esempio n. 4
0
 private void setType(Paddle paddle) {
   if (Math.random() < 0.1 && paddle.getType() != 2) { // %10 chance
     if (Math.random() < 0.5 && paddle.padType != 1) {
       Sound.play("\\sound\\pwrup.wav");
       paddle.padType = 1;
     } else if (paddle.padType != 2) {
       Sound.play("\\sound\\pwrup.wav");
       paddle.padType = 2;
     }
   } else if (paddle.getType() != 1) {
     paddle.padType = 0;
   }
 }
Esempio n. 5
0
  private static void meth() throws Exception {
    double r1 =
        10
            * java.lang.Math
                .random(); // random() returns a double value with a positive sign, greater than or
                           // equal to 0.0 and less than 1.0
    double r2 = 10 * java.lang.Math.random();

    // if the difference of the 2 numbers is higher than 3, throw an exception you�ll specially
    // define for this case
    if (java.lang.Math.abs(r1 - r2) > 3) {
      throw new Exception("Difference of the 2 random numbers is higher than 3");
    }
  }
Esempio n. 6
0
  public void test(Date currentDate) {
    // is it a new day
    if (currentDate == oldDate) {
      counter = counter + 1;
      if (counter == 1) {
        isnewDay = true;
      } else {
        isnewDay = false;
      }
    }
    if (currentDate != oldDate) {
      oldDate = currentDate;
      isnewDay = true;
      counter = 1;
    }

    // Snooze functionality
    double x = Math.random();
    if (x < .5) {
      isSnooze = true;
    }
    if (x >= .5) {
      isSnooze = false;
    }

    if (isSnooze == false && isnewDay == true) {
      totalpoints = totalpoints + points;
    }
  }
Esempio n. 7
0
  public static void main(String[] args) {

    // initiate the weights
    initWeights();

    // load in the data
    initData();

    // train the network
    for (int j = 0; j <= numEpochs; j++) {

      for (int i = 0; i < numPatterns; i++) {

        // select a pattern at random
        patNum = (int) ((Math.random() * numPatterns) - 0.001);

        // calculate the current network output
        // and error for this pattern
        calcNet();

        // change network weights
        WeightChangesHO();
        WeightChangesIH();
      }

      // display the overall network error
      // after each epoch
      calcOverallError();
      System.out.println("epoch = " + j + "  RMS Error = " + RMSerror);
    }

    // training has finished
    // display the results
    displayResults();
  }
Esempio n. 8
0
  public static void main(String[] args) throws IOException {
    int aKey;
    Link dataItem;
    int size, initSize, keysPerCell = 100;
    size = 100;
    initSize = 10;
    HashChain hashTable = new HashChain(size);

    for (int i = 0; i < initSize; i++) {
      aKey = (int) (java.lang.Math.random() * keysPerCell * size);
      dataItem = new Link(aKey);
      hashTable.insert(dataItem);
    }
    hashTable.displayTable();
    aKey = 100;
    dataItem = new Link(aKey);
    hashTable.insert(dataItem);
    aKey = 100;
    hashTable.delete(aKey);

    aKey = 50;
    dataItem = hashTable.find(aKey);
    if (dataItem != null) System.out.println("Found " + aKey);
    else System.out.println("Could not find " + aKey);
  }
Esempio n. 9
0
 /**
  * Apply an "efficient selection shuffle" to the argument. The selection shuffle algorithm
  * conceptually maintains two sequences of cards: the selected cards (initially empty) and the
  * not-yet-selected cards (initially the entire deck). It repeatedly does the following until all
  * cards have been selected: randomly remove a card from those not yet selected and add it to the
  * selected cards. An efficient version of this algorithm makes use of arrays to avoid searching
  * for an as-yet-unselected card.
  *
  * @param values is an array of integers simulating cards to be shuffled.
  */
 public static void selectionShuffle(int[] values) {
   for (int i = SHUFFLE_COUNT - 1; i >= 0; i--) {
     int r = (int) (Math.random() * i);
     int tmp = values[r];
     values[r] = values[i];
     values[i] = tmp;
   }
 }
Esempio n. 10
0
 private void addDish() {
   foodTimerDiff = (System.nanoTime() - foodTimer) / 1000000;
   if (foodTimerDiff > foodDelay) { // there will be a 88% chance the next dish will be food
     double chance = Math.random();
     int rail = (int) Math.round(Math.random() * 2);
     if (chance < foodprobability) {
       String food = foodList.get((int) (Math.random() * foodList.size()) % foodList.size());
       Food f = new Food(food, rail, foodValues.get(food));
       f.setPositionInRail(player.getx() + GamePanel.WIDTH + f.getWidth() / 2, rail);
       f.setCamera(camera);
       dishes.add(f);
     } else {
       String power = powerList.get((int) (Math.random() * powerList.size()) % powerList.size());
       Power p = new Power(power, rail);
       p.setPositionInRail(player.getx() + GamePanel.WIDTH + p.getWidth() / 2, rail);
       p.setCamera(camera);
       dishes.add(p);
     }
     foodTimer = System.nanoTime();
     if (difficulty == OptionsState.EASY)
       foodDelay = (long) (Math.random() * fooddelays[0]) + fooddelays[1];
     if (difficulty == OptionsState.NORMAL)
       foodDelay = (long) (Math.random() * fooddelays[2]) + fooddelays[3];
     if (difficulty == OptionsState.HARD)
       foodDelay = (long) (Math.random() * fooddelays[4]) + fooddelays[5];
   }
 }
Esempio n. 11
0
  /** Turns the robot left or right depending on a random number. */
  private void turnLeftOrRight() {
    randomNum = (int) (Math.random() * 2);

    if (randomNum == 0) {
      rotation(TURN_90_DEGREES, TURN_RIGHT);
    } else if (randomNum == 1) {
      rotation(TURN_90_DEGREES, TURN_LEFT);
    }
  }
Esempio n. 12
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      String[] values = map.get("vector");
      if (values != null) param = values[0];
    }

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    double value = java.lang.Math.random();
    String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front.

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
      javax.servlet.http.Cookie cookie = cookies[i];
      if (cookieName.equals(cookie.getName())) {
        if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
          foundUser = true;
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }
    response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
  }
Esempio n. 13
0
  /** Calls all other methods creates 120 vehicles and populates proper queues to specification */
  public void Simulate() {

    write("---Start of simulation, time set to 0\n");
    int num = (int) (Math.random() * (13 - 7)) + 7;
    changeLight();
    populate(num);
    do {
      move(2);
      num = (int) (Math.random() * (16 - 8)) + 8;
      if (!(counter > 120)) populate(num);
      changeLight();
      move(3);
      num = (int) (Math.random() * (16 - 3)) + 3;
      if (!(counter > 120)) populate(num);
      changeLight();
    } while (!queuesEmpty());

    output();
  }
Esempio n. 14
0
  public static void main(String args[]) {
    CCalculator obj1 = new CCalculator();
    CTriFunc obj2 = new CTriFunc();
    double a, b;
    a = Math.random() * 20;
    b = Math.random() * 10;

    System.out.println(a + " Add " + b + " = " + obj1.Add(a, b));
    System.out.println(a + " Sub " + b + " = " + obj1.Sub(a, b));
    System.out.println(a + " Mul " + b + " = " + obj1.Mul(a, b));
    System.out.println(a + " Div " + b + " = " + obj1.Div(a, b));
    System.out.println("log(" + a + ") = " + obj1.LOG(a));
    System.out.println("ln(" + a + ") = " + obj1.LN(a));
    System.out.println("sin(" + b + ") = " + obj1.SIN(b * 10));
    System.out.println("cos(" + b + ") = " + obj1.COS(b * 10));
    System.out.println("tan(" + b + ") = " + obj1.TAN(b * 10));
    System.out.println("sin(" + b + ") = " + obj2.SIN(b * 10) + "by run CTriFunc method");
    System.out.println("cos(" + b + ") = " + obj2.COS(b * 10) + "by run CTriFunc method");
    System.out.println("tan(" + b + ") = " + obj2.TAN(b * 10) + "by run CTriFunc method");
  }
Esempio n. 15
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getParameter("foo");

    String bar = doSomething(param);

    java.lang.Math.random();

    response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
  } // end doPost
Esempio n. 16
0
  public void init() {

    // setBackground (Color.blue);
    try {
      // load map
      dbImage =
          ImageIO.read(
              new File("C:\\Users\\acer\\Documents\\JavaProjects\\ProjectZ\\src\\usamap.png"));
      background =
          ImageIO.read(
              new File("C:\\Users\\acer\\Documents\\JavaProjects\\ProjectZ\\src\\usamap.png"));
      // load building
      //			building = ImageIO.read(new
      // File("C:\\Users\\acer\\Documents\\JavaProjects\\ProjectZ\\src\\building.jpg"));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    setSize(1200, 600);
    width = getSize().width;
    height = getSize().height;
    mx = width / 2;
    my = height / 2;

    points = new Point[N];
    for (int i = 0; i < N; ++i) {
      int x = (int) ((Math.random() - 0.5) * width / 1.5);
      int y = (int) ((Math.random() - 0.5) * height / 1.5);
      points[i] = new Point(x, y);
    }

    building = getImage(getDocumentBase(), "building.jpg");

    //	    backbuffer = createImage( width, height );
    dbg = dbImage.getGraphics();

    addMouseMotionListener(this);
  }
  public boolean match() {
    if (robot.getOthers() > 5 || targetManager.getAliveTargetCount() == 0) {
      return false;
    }
    Map<Target, Double> dists = new HashMap<Target, Double>();
    final java.util.List<Target> aliveTargets = targetManager.getAliveTargets();
    for (Target t : aliveTargets) {
      final Target closest = targetManager.getClosestTergetToT(t);
      if (closest == null) {
        return false;
      }
      dists.put(t, closest.aDistance(t) + 80);
    }

    LXXPoint candidate = dest;
    Target closest = targetManager.getClosestTarget();
    for (int i = 0; i < 20; i++) {
      double angle =
          Utils.angle(closest.getPosition(), robot.getPosition())
              + Math.random() * LXXConstants.RADIANS_20
              - LXXConstants.RADIANS_10;
      double dist = dists.get(closest);

      if (candidate == null) {
        candidate =
            new LXXPoint(closest.getX() + sin(angle) * dist, closest.getY() + cos(angle) * dist);
      }

      for (Target t : aliveTargets) {
        final double d = t.aDistance(candidate);
        if (d < dists.get(t)) {
          candidate = null;
          break;
        }
      }
      if (candidate != null && robot.getBattleField().contains(candidate)) {
        break;
      }

      candidate =
          new LXXPoint(closest.getX() + sin(angle) * dist, closest.getY() + cos(angle) * dist);
    }

    dest = candidate;

    return candidate != null
        && robot.getBattleField().contains(candidate)
        && StaticData.robot.getDestination().aDistance(dest) > 20;
  }
Esempio n. 18
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    java.lang.Math.random();

    response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
  } // end doPost
Esempio n. 19
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      param = map.get("foo")[0];
    }

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    java.lang.Math.random();

    response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
  }
Esempio n. 20
0
 public static double handleRandom(Process pro) {
   System.out.println("RAMBUDGET = " + pro.B);
   double value = 0;
   double bud = 0;
   for (int t = 1; t < pro.T; t++) {
     for (int i = 0; i < pro.N.list.size(); i++) {
       if (pro.N.list.get(i).arrival_time == t) {
         if (Math.random() > 0.5) {
           if (bud + pro.N.list.get(i).cost < pro.B) {
             bud += pro.N.list.get(i).cost;
             value += pro.N.list.get(i).value * disc(pro.beta, t);
           }
         }
       }
     }
   }
   return value;
 }
Esempio n. 21
0
  private Object interpretFunctionRand(Object right, Object left) {
    Double minimum = java.lang.Math.min((Double) left, (Double) right);
    Double maximum = java.lang.Math.max((Double) left, (Double) right);

    Double randomDouble = minimum + (java.lang.Math.random() * (maximum - minimum));

    if (isInteger(minimum)
        && isInteger(maximum)
        && !(rightChild.type == ElementType.NUMBER && rightChild.value.contains("."))
        && !(leftChild.type == ElementType.NUMBER && leftChild.value.contains("."))) {
      if ((Math.abs(randomDouble) - (int) Math.abs(randomDouble)) >= 0.5) {
        return (double) randomDouble.intValue() + 1;
      } else {
        return (double) randomDouble.intValue();
      }
    } else {
      return randomDouble;
    }
  }
Esempio n. 22
0
  private void createZambie(float x, float y, float dist, float speed) {
    Entity entity = new Entity();

    float theta = (float) (random() * PI * 2);

    float cos = (float) cos(theta);
    float sin = (float) sin(theta);

    float scale = (float) (4 + Math.random() * 2);
    entity.add(new Position(x + cos * dist, y + sin * dist, theta + (float) PI, scale, scale));
    entity.add(new Velocity(0, 0, 0));
    entity.add(new ZambieAI(speed + (float) Utils.random.nextGaussian() * (speed * 0.1f)));
    entity.add(new Health(30));
    entity.add(new Lifetime(300)); // 5 minute liftime (to stop too many zambies on screen)
    entity.add(new ZambieClaws(10, 1)); // damge, APS
    entity.add(new Renderable(Color.GREEN));

    engine.addEntity(entity);
  }
Esempio n. 23
0
 /**
  * Executes the fall.
  *
  * @param e An action event called upon by a timer
  */
 public void actionPerformed(ActionEvent e) {
   // If we don't have a currently falling pentomino we set up a new one
   if (activePentomino == null) {
     pentominoLocation = new Point(gameBoard.getWidth() / 2, 0);
     predictedLocation = new Point(gameBoard.getWidth() / 2, 0);
     activePentomino = nextPentomino1;
     nextPentomino1 = new Pentomino((int) (Math.random() * 12));
     predictDrop();
   }
   // If the next drop is legal we move the piece and make a tmpBoard, which contains the
   // changes.
   // This way the original board remains unchanged and we can change the UI without changing
   // the gameBoard.
   if (nextDropLegal(activePentomino, gameBoard.getBoard(), pentominoLocation)) {
     // Move pentomino
     pentominoLocation.setLocation(pentominoLocation.getX(), pentominoLocation.getY() + 1);
     updateMatrix();
   }
   // If not, lock the piece to gameBoard, erase the full rows and add score accordingly.
   else {
     // Locking each block of the pentomino to the board
     for (Point p : activePentomino.getLocation()) {
       int newX = (int) (pentominoLocation.getX() + p.getX());
       int newY = (int) (pentominoLocation.getY() + p.getY());
       if (newY >= 0 && newY < gameBoard.getBoard()[0].length)
         gameBoard.getBoard()[newX][newY] = activePentomino.getID();
     }
     // Removing rows and pentomino and adding score
     addScore(gameBoard.removeFullRows());
     matrix = gameBoard.getBoard();
     activePentomino = null;
     scoreText = Integer.toString(score);
     // And set storageable to true
     storageable = true;
     // Adjust the timer speed
     if (t.getDelay() > 10) t.setDelay((int) (Math.max(1000 - Math.sqrt(12 * score), 10)));
     else t.setDelay(10);
   }
 }
Esempio n. 24
0
 // ---------------------------------------------------------------------------
 private String Calculate0(String oper) throws Exception {
   double val = 0;
   if (oper.equalsIgnoreCase("ALEATORIO")) val = java.lang.Math.random();
   else throw new Exception("ERRO fun��o Desconhecida 2 [" + oper + "]");
   return Values.DoubleToString(val);
 }
Esempio n. 25
0
  /**
   * Constructor for a new game
   *
   * @param width The width of the gameboard
   * @param height The height of the gameboard
   * @param randomBlocks The random blocks in the starting grid
   */
  public Game(int width, int height, int randomBlocks) {
    // Setup for the board, UI and the first pentomino.
    gameBoard = new Board(width, height, 0, randomBlocks);
    pentominoLocation = new Point(width / 2, 0);
    predictedLocation = new Point(width / 2, 0);
    activePentomino = new Pentomino((int) (Math.random() * 12));
    nextPentomino1 = new Pentomino((int) (Math.random() * 12));
    storagedPentomino = new Pentomino((int) (Math.random() * 12));
    storageable = true;
    scoreText = Integer.toString(0);
    predictDrop();

    /** Makes the active pentomino fall one step each time it's called. */
    /*START-OF-BLOCKFALL-CLASS*/
    class BlockFall implements ActionListener {
      /**
       * Executes the fall.
       *
       * @param e An action event called upon by a timer
       */
      public void actionPerformed(ActionEvent e) {
        // If we don't have a currently falling pentomino we set up a new one
        if (activePentomino == null) {
          pentominoLocation = new Point(gameBoard.getWidth() / 2, 0);
          predictedLocation = new Point(gameBoard.getWidth() / 2, 0);
          activePentomino = nextPentomino1;
          nextPentomino1 = new Pentomino((int) (Math.random() * 12));
          predictDrop();
        }
        // If the next drop is legal we move the piece and make a tmpBoard, which contains the
        // changes.
        // This way the original board remains unchanged and we can change the UI without changing
        // the gameBoard.
        if (nextDropLegal(activePentomino, gameBoard.getBoard(), pentominoLocation)) {
          // Move pentomino
          pentominoLocation.setLocation(pentominoLocation.getX(), pentominoLocation.getY() + 1);
          updateMatrix();
        }
        // If not, lock the piece to gameBoard, erase the full rows and add score accordingly.
        else {
          // Locking each block of the pentomino to the board
          for (Point p : activePentomino.getLocation()) {
            int newX = (int) (pentominoLocation.getX() + p.getX());
            int newY = (int) (pentominoLocation.getY() + p.getY());
            if (newY >= 0 && newY < gameBoard.getBoard()[0].length)
              gameBoard.getBoard()[newX][newY] = activePentomino.getID();
          }
          // Removing rows and pentomino and adding score
          addScore(gameBoard.removeFullRows());
          matrix = gameBoard.getBoard();
          activePentomino = null;
          scoreText = Integer.toString(score);
          // And set storageable to true
          storageable = true;
          // Adjust the timer speed
          if (t.getDelay() > 10) t.setDelay((int) (Math.max(1000 - Math.sqrt(12 * score), 10)));
          else t.setDelay(10);
        }
      }
    }
    /*END-OF-BLOCKFALL-CLASS*/
    // Setup for the method to make the pentomino fall and the timer which controls it. I.E. this
    // makes the game run.
    BlockFall blockFall = new BlockFall();

    // Set up the timer for the fall
    t = new Timer((800), blockFall);
    t.start();
    updateMatrix();
  }
Esempio n. 26
0
 static {
   int i;
   for (i = 0; i < BUFFER_SIZE; i++) buffer[i] = java.lang.Math.random();
 }
Esempio n. 27
0
 private static int r(int num) {
   return (int) (Math.random() * num);
 }
Esempio n. 28
0
 /**
  * @param prob the probability of success for the geometric distribution.
  * @return a random number generated from the geometric distribution.
  */
 private static long randomGeometricDist(double prob) {
   assert (prob > 0.0 && prob < 1.0);
   return (long) (Math.log(Math.random()) / Math.log(1.0 - prob));
 }
Esempio n. 29
0
 public static int randOneZero() { // GENERATE RANDOM LEFT OR RIGHT
   // method that generates random number either 1 or 0
   double random_number = Math.random();
   int rand_int = (random_number >= .50) ? 1 : 0;
   return rand_int;
 }
Esempio n. 30
0
 public void run() {
   int j = 0;
   while (true) {
     j++;
     if (supply) {
       controller.depositFuel(supplyAmount, supplyKind);
       System.out.println(
           System.currentTimeMillis()
               - startTime
               + "--> SpaceVehicle "
               + getName()
               + " has supplied "
               + supplyAmount
               + " liters of "
               + FuelSpaceStation.KIND[supplyKind]
               + " in its "
               + j
               + "-th trip");
     }
     amount[0] = rand.nextInt(10);
     amount[1] = rand.nextInt(10);
     if (amount[0] == 0 && amount[1] == 0) continue;
     System.out.println(
         System.currentTimeMillis()
             - startTime
             + " -- SpaceVehicle "
             + getName()
             + " requests "
             + amount[0]
             + " liters of "
             + FuelSpaceStation.KIND[0]
             + " and "
             + amount[1]
             + " liters of "
             + FuelSpaceStation.KIND[1]
             + " in its "
             + j
             + "-th trip");
     if (amount[0] == 0 || amount[1] == 0) {
       controller.requestFuel(amount);
       Sleep((int) (1000 * java.lang.Math.random())); // gets the fuel of the kind
     } else {
       kind = controller.requestFuel(amount);
       Sleep((int) (1000 * java.lang.Math.random())); // get the fuel of the kind
       if (kind != FuelSpaceStation.BOTH) {
         amount[kind] = 0;
         controller.releasePlace();
         controller.requestFuel(amount); // request another fuel
         Sleep((int) (1000 * java.lang.Math.random())); // get another fluid;
       }
     }
     controller.releasePlace();
     System.out.println(
         System.currentTimeMillis()
             - startTime
             + "<-- SpaceVehicle "
             + getName()
             + " has got the fuel requested in its "
             + j
             + "-th trip");
   }
 }