コード例 #1
0
ファイル: CellSim.java プロジェクト: yehbrian/Assignments-
 /**
  * Given a tissue sample, move all unsatisfied agents to a vacant cell
  *
  * @param tissue a 2-D character array that has been initialized
  * @param threshold the percentage of like agents that must surround the agent to be satisfied
  */
 public static int moveAllUnsatisfied(char[][] tissue, int threshold) {
   ArrayList<Integer> list2 = new ArrayList<Integer>();
   int counter = 0;
   ArrayList<Integer> list1 = new ArrayList<Integer>();
   for (int i = 0; i < tissue.length; i++) {
     for (int x = 0; x < tissue[0].length; x++) {
       if (isSatisfied(tissue, i, x, threshold) == false) {
         list1.add(i);
         list2.add(x);
       }
     }
   }
   int num = list1.size();
   char temp;
   int count = 0;
   do {
     int rand = (int) (Math.random() * tissue.length);
     int random = (int) (Math.random() * tissue.length);
     if (tissue[rand][random] == ' ') {
       temp = tissue[rand][random];
       tissue[rand][random] = tissue[list1.get(counter)][list2.get(counter)];
       tissue[list1.get(counter)][list2.get(counter)] = temp;
       counter++;
       count++;
     }
   } while (counter != num);
   return count;
 }
コード例 #2
0
ファイル: Solution.java プロジェクト: Faktorealchik/faktor
 public static Date getRandomDate(int startYear) {
   int year = startYear + (int) (Math.random() * 30);
   int month = (int) (Math.random() * 12);
   int day = (int) (Math.random() * 28);
   GregorianCalendar calendar = new GregorianCalendar(year, month, day);
   return calendar.getTime();
 }
コード例 #3
0
  public AngleLocalization(
      List<PolygonObstacle> cSpaceObstacles,
      Rectangle2D.Double cSpaceWorld,
      Point2D.Double robotStart,
      Fiducial[] fiducialPairs) {

    this.cSpaceObstacles = cSpaceObstacles;
    this.cSpaceWorld = cSpaceWorld;
    this.robotStart = robotStart;
    this.fiducialPairs = fiducialPairs;

    particles = new ArrayList<OdoPoint>();
    probabilities = new ArrayList<Double>();

    double delta_x = 0;
    double delta_y = 0;
    double delta_theta = 0;
    for (int i = 0; i < NUM_PARTICLES; i++) {
      delta_x = cSpaceWorld.getWidth() * INITIAL_NOISE * (1 - 2 * Math.random());
      delta_y = cSpaceWorld.getHeight() * INITIAL_NOISE * (1 - 2 * Math.random());
      delta_theta = 2 * Math.PI * INITIAL_NOISE * (1 - 2 * Math.random());
      particles.add(new OdoPoint(robotStart.x + delta_x, robotStart.y + delta_y, delta_theta));
      probabilities.add(1.0 / NUM_PARTICLES);
    }

    prev_odo_x = robotStart.x;
    prev_odo_y = robotStart.y;
    prev_odo_theta = 0;
    localPoint = new OdoPoint(robotStart.x, robotStart.y, 0);
  }
コード例 #4
0
  /**
   * Spawn a character on the map
   *
   * @param MiX Minimum X value
   * @param MiY Minimum Y value
   * @param MaX Maximum X value
   * @param MaY Maximum Y value
   */
  public void Spawn(int MiX, int MiY, int MaX, int MaY) {
    double Nx = 0, Ny = 0;

    // Random coordinate
    Nx = Math.random() * MaX + MiX;
    Ny = Math.random() * MaY + MiY;

    // Store block number
    int BNum = MAP.elementAt(0).getBlockNum(Nx + W / 2, Ny + H / 2);

    // if invalid block number
    if (BNum == -1) {
      Spawn(MiX, MiY, MaX, MaY);
    }

    // if invalid surface
    else if (!isValidSurface(MAP.elementAt(0).Fill[BNum])) {
      Spawn(MiX, MiY, MaX, MaY);
    }

    // if colliding with something
    else if (this.Collision(Nx + W / 2, Ny + H / 2)) {
      Spawn(MiX, MiY, MaX, MaY);
    } else {
      X = Nx;
      Y = Ny;
    }
  }
コード例 #5
0
ファイル: Ex2.java プロジェクト: KulArtyom/Java-Courses
  public static void main(String[] args) {

    ArrayList<Human> man = new ArrayList<>();
    man.add(new Human("Gena", "Suvorov"));
    man.add(new Human("Artyom", "Andropov"));
    man.add(new Human("Petro", "Popov"));
    man.add(new Human("Vasil", "Suhadol"));
    man.add(new Human("Egor", "Perkakov"));
    man.add(new Human("Kirill", "Slovrentsiy"));
    man.add(new Human("Anton", "Antipov"));
    man.add(new Human("Petya", "Kurnosov"));
    man.add(new Human("Antonio", "Zapashnyi"));
    man.add(new Human("Gena", "Debalcev"));

    ArrayList<Human> woman = new ArrayList<>();
    woman.add(new Human("Larisa", "Strezanova"));
    woman.add(new Human("Lubov", "Popova"));
    woman.add(new Human("Julia", "Golovach"));
    woman.add(new Human("Marina", "Vasilkova"));
    woman.add(new Human("Vika", "Disman"));
    woman.add(new Human("Zoya", "Piterskaya"));
    woman.add(new Human("Elena", "Gorbacevich"));
    woman.add(new Human("Tatyana", "Jerdetskaya"));
    woman.add(new Human("Larisa", "Strezanovskaya"));

    HashMap<String, ArrayList<Human>> humanHashMap = new HashMap<>();
    humanHashMap.put("man", man);
    humanHashMap.put("woman", woman);

    Scanner scanner = new Scanner(System.in);

    do {
      System.out.println(Constans.ENTER_NAME);

      String s = scanner.nextLine();
      s = s.toUpperCase();
      s = s.trim();

      switch (s) {
        case "MAN":
          {
            System.out.println(
                humanHashMap
                    .get("man")
                    .get((int) ((humanHashMap.get("man").size()) * Math.random())));
            break;
          }
        case "WOMAN":
          {
            System.out.println(
                humanHashMap
                    .get("woman")
                    .get((int) ((humanHashMap.get("woman").size()) * Math.random())));
            break;
          }
        default:
          System.exit(0);
      }
    } while (true);
  }
コード例 #6
0
 // -------------------------------------------------------------------------------------------------------------------------------------------------------
 // Decorations
 public void newDecos() {
   int prob = (int) (Math.random() * 100); // randomly spawnst he decoration
   if (prob == 1) {
     if (decoList.size() < 1) {
       int prob2 = (int) (Math.random() * 2);
       if (prob2 == 1) { // right side or left side
         decoList.add(new Decorations(-700, (int) (backy * 0.1) % 23080, false));
       } else {
         decoList.add(new Decorations(-700, (int) (backy * 0.1) % 23080, true));
       }
     }
   }
   Boolean check = true;
   for (Decorations i : decoList) {
     if (i.getYTop() >= 2000) {
       check = false;
       break;
     }
   }
   if (check == false
       && decoList.size()
           > 0) { // theres only on in the lsit but for consitency we kept it as a list
     decoList.remove(0);
   }
 }
コード例 #7
0
ファイル: Unit.java プロジェクト: jacarandang/CS140
 public Unit() {
   trm = (Math.random() * 10) - 5;
   prm = (Math.random() * 10) - 5;
   wtm = (Math.random() * 10) - 5;
   tkm = (Math.random() * 10) - 5;
   ped = (Math.random() * 5) + 5;
 }
コード例 #8
0
  public Tour createRandomTour() {
    Tour tour = new Tour();
    List<City> newPath = new ArrayList<>();

    int tourSize = allCities.size();
    int index;
    Set<Integer> seen = new HashSet<>();
    City city;

    newPath.add(allCities.get(0));
    // System.out.println("** " + allCities.get(0).getName());
    for (int i = 1; i < tourSize; i++) {
      index = (int) (Math.random() * tourSize);
      while (index == 0 || seen.contains(index)) {
        // System.out.println("in " + index);
        index = (int) (Math.random() * tourSize);
      }

      seen.add(index);
      city = allCities.get(index);
      // System.out.println("** " + index + " " + allCities.get(index).getName());
      newPath.add(city);
    }
    // System.out.println("");

    if (allCities.size() > 1) {
      // System.out.println("** last :" + allCities.get(0).getName());
      newPath.add(allCities.get(0));
    }

    tour.setPath(newPath);
    return tour;
  }
コード例 #9
0
ファイル: Tableroa.java プロジェクト: ikerzalla/ClickyBoom
 private void bonbakKokatu() {
   int b = 0;
   int alt;
   int zab;
   while (b < this.bonbaKop) {
     alt = (int) (Math.random() * this.altuera - 1);
     zab = (int) (Math.random() * this.zabalera - 1);
     if (!(alt + 1 == this.hasAlt || alt - 1 == this.hasAlt)
         && !(zab + 1 == this.hasZab
             || zab - 1 == this.hasZab)) { // If honen baldintza luzea da, hasieran click
       // egin dugun posizioaren alboan bonbak ez kokatzeko
       if (laukiak[alt][zab] == null) {
         laukiak[alt][zab] = new Bonba();
         bonbenKoor.add(alt);
         bonbenKoor.add(zab);
         b++;
       } else if (laukiak[alt][zab].banderaDu()) {
         laukiak[alt][zab].eskuinClickEgin(alt, zab);
         laukiak[alt][zab] = new Bonba();
         laukiak[alt][zab].eskuinClickEgin(alt, zab);
         bonbenKoor.add(alt);
         bonbenKoor.add(zab);
         b++;
       }
     }
   }
   System.out.println("Bonbak kokatu dira");
 }
コード例 #10
0
  private void createOperations(Date startDate, int numberOfDays, Context context) {
    for (int i = 0; i < numberOfDays; i++) {
      Date date = DateUtils.addDays(startDate, i);

      if (i % 7 == 0) {
        income(date, context.accounts.get(0), context.salaryCategory, new BigDecimal("16000"));
      }
      if (i % 5 == 0) {
        income(
            date,
            context.accounts.get(1),
            context.otherIncomeCategory,
            new BigDecimal(1000 + Math.round(Math.random() * 5000)));
      }

      for (int j = 0; j < Math.random() * 7; j++) {
        expense(date, context.accounts.get(1), context);
        if (j % 2 == 0) expense(date, context.accounts.get(0), context);
      }

      if (i % 2 == 0) {
        Account account2 =
            context.accounts.get((int) (1 + Math.random() * (context.accounts.size() - 1)));
        transfer(date, context.accounts.get(0), account2);
      }
    }
  }
コード例 #11
0
  public static void main(String[] args) {
    SplayTree myNameIsSonyAndICantProgram =
        new SplayTree(); // We won't be using this, I just felt it was necessary.
    SplayTree splay = new SplayTree();

    // Randomly creates a SplayTree, printing out the Tree after each insert
    int rand = (int) (Math.random() * 25 + .5);
    for (int i = 0; i < rand; i++) {
      int temp = (int) (Math.random() * 100 + .5);
      System.out.println("Attempting to add " + temp + " to the SplayTree:\nNew SplayTree:");
      splay.insert(temp);
      print(splay.getRoot());
    }

    // Removes all of the data by the root
    while (splay.getSize() > 0) {
      if (splay.getRoot() != null) {
        System.out.println(
            "Attempting to remove "
                + splay.getRoot().getValue()
                + " from the tree.\nNew SplayTree:");
        splay.remove(splay.getRoot().getValue());
        print(splay.getRoot());
      } else break;
    }
  }
コード例 #12
0
ファイル: Game2048.java プロジェクト: Proger666/Neuro2048
 private void addTile() {
   List<Tile> list = availableSpace();
   if (!availableSpace().isEmpty()) {
     int index = (int) (Math.random() * list.size()) % list.size();
     Tile emptyTime = list.get(index);
     emptyTime.value = Math.random() < 0.9 ? 2 : 4;
   }
 }
コード例 #13
0
  /**
   * The {@code shuffle()} method is responsible for shuffling the race id's and ability id's before
   * creating the stack.
   */
  public void shuffle() {

    Random r1 = new Random(Double.doubleToLongBits(Math.random()));
    Random r2 = new Random(Double.doubleToLongBits(Math.random()));

    Collections.shuffle(raceStack, r1);
    Collections.shuffle(abilityStack, r2);
  }
コード例 #14
0
ファイル: Shootme.java プロジェクト: jiafu1115/jain-sip-1
  /** Process the invite request. */
  public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      logger.info("shootme: got an Invite sending Trying");
      // logger.info("shootme: " + request);

      ServerTransaction st = requestEvent.getServerTransaction();

      if (st == null) {
        logger.info("null server tx -- getting a new one");
        st = sipProvider.getNewServerTransaction(request);
      }

      logger.info("getNewServerTransaction : " + st);

      String txId = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getBranch();
      this.serverTxTable.put(txId, st);

      // Create the 100 Trying response.
      Response response = protocolObjects.messageFactory.createResponse(Response.TRYING, request);
      ListeningPoint lp = sipProvider.getListeningPoint(protocolObjects.transport);
      int myPort = lp.getPort();

      Address address =
          protocolObjects.addressFactory.createAddress(
              "Shootme <sip:" + myAddress + ":" + myPort + ">");

      // Add a random sleep to stagger the two OK's for the benifit of implementations
      // that may not be too good about handling re-entrancy.
      int timeToSleep = (int) (Math.random() * 1000);

      Thread.sleep(timeToSleep);

      st.sendResponse(response);

      Response ringingResponse =
          protocolObjects.messageFactory.createResponse(Response.RINGING, request);
      ContactHeader contactHeader = protocolObjects.headerFactory.createContactHeader(address);
      response.addHeader(contactHeader);
      ToHeader toHeader = (ToHeader) ringingResponse.getHeader(ToHeader.NAME);
      String toTag =
          actAsNonRFC3261UAS ? null : new Integer((int) (Math.random() * 10000)).toString();
      if (!actAsNonRFC3261UAS) toHeader.setTag(toTag); // Application is supposed to set.
      ringingResponse.addHeader(contactHeader);
      st.sendResponse(ringingResponse);
      Dialog dialog = st.getDialog();
      dialog.setApplicationData(st);

      this.inviteSeen = true;

      new Timer().schedule(new MyTimerTask(requestEvent, st /*,toTag*/), 1000);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
コード例 #15
0
 private Point convertRelativePositionToPoint(RelativePoint rp) {
   int x = (int) (Math.random() * (gwtBitsCanvas.width - 150));
   int y = (int) (Math.random() * (gwtBitsCanvas.height - 50));
   if (rp != null) {
     if (rp.x != -1) x = (int) (rp.x * (gwtBitsCanvas.width - 150));
     if (rp.y != -1) y = (int) (rp.y * (gwtBitsCanvas.height - 50));
   }
   return new Point(x, y);
 }
コード例 #16
0
  public static void createFileOfRandomIntegers(String outputFileName) throws IOException {

    PrintStream printstream;
    printstream = new PrintStream(outputFileName);
    int numberOfIntegers = (int) (Math.random() * 100) % 10 + 1;
    printstream.println(numberOfIntegers);
    for (int i = 0; i < numberOfIntegers; i++)
      printstream.println((int) (Math.random() * 1000) % 100 + 1);
    printstream.close();
  }
コード例 #17
0
ファイル: ShortRoute.java プロジェクト: IT-Kakan/TDA416
  // experimental
  // ====================================================================
  // ====================================================================
  // ====================================================================
  private void readAndDrawBIGGraph(String file) {
    // behövs inte än
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); //
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        // this is a fix: fixa att Kålltorp och Torp är samma hållplats
        if (hpl.equals("Torp")) {
          xco += 11;
          hpl = "   / Torp";
        }
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      Color color =
          new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); //
      String lineNo = "1"; //
      while (indata.hasNext()) { // assume lines are correct
        int from = noderna.find(indata.next()).getNodeNo();
        int to = noderna.find(indata.next()).getNodeNo();
        grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
        indata.nextLine(); // skip rest of line
        // Draw
        BusStop busFrom = noderna.find(from);
        BusStop busTo = noderna.find(to);
        karta.drawLine(
            busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE);
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawBIGGraph
コード例 #18
0
ファイル: troll.java プロジェクト: padawin/troll-game
 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);
 }
コード例 #19
0
ファイル: AHGB.java プロジェクト: angrymidiao/AProject
  public static void autoTest(int k, int cals) {
    int settingCnt = 0;
    R = 20;
    K = k;
    for (L = 200; L <= 800; L += 200) {
      for (double rate = 1.25; rate <= 2; rate += 0.25) {
        settingCnt++;
        LogInfo.begin_track("Testing data setting %d", settingCnt);
        n = (int) (rate * L * K / (2 * R)) + 1;
        LogInfo.logs("n = %d, L = %d, K = %d, R = %d, redundancy rate: %.2f", n, L, K, R, rate);
        long stTime = System.currentTimeMillis();
        for (int numCnt = 1; numCnt <= cals; numCnt++) {
          x = new double[n + 2];
          xs = new double[n + 2];
          y = new double[n + 2];
          ys = new double[n + 2];

          // Generate x positions
          Set<Integer> set = new HashSet<>();
          while (set.size() < n) {
            int num = (int) (Math.random() * (L - 1)) + 1;
            set.add(num);
          }
          List<Integer> list = new ArrayList<>(set);
          Collections.sort(list);
          for (int i = 0; i < n; i++) xs[i + 1] = x[i + 1] = list.get(i);

          // Generate y positions
          set = new HashSet<>();
          while (set.size() < n) {
            int num = (int) (Math.random() * (L - 1)) + 1;
            set.add(num);
          }
          list = new ArrayList<>(set);
          for (int i = 0; i < n; i++) ys[i + 1] = y[i + 1] = list.get(i);

          if (verbose) {
            LogInfo.begin_track("Data #%d:", numCnt);
            printXY();
          }
          strongDetect();
          if (verbose) LogInfo.end_track();
        }
        long edTime = System.currentTimeMillis();
        long time = edTime - stTime;
        LogInfo.logs(
            "Time: %dms, [n = %d, L = %d, K = %d, R = %d, redundancy rate: %.2f]",
            time, n, L, K, R, rate);
        LogInfo.end_track();
      }
    }
  }
コード例 #20
0
ファイル: Field.java プロジェクト: kevinychen/catch22-game
 private void createTurn(int index) {
   double dist = 100;
   double newTurn = (index == NUM_TURNS - 1 && Math.random() < .1 ? Math.random() * 2 - 1 : 0);
   Turn prev = centerHinges[index - 1];
   double newX = prev.x + dist * Math.sin(prev.angle);
   double newZ = prev.z + dist * Math.cos(prev.angle);
   int barrierY =
       (index == NUM_TURNS - 1 && barrierBuffer == 0 && Math.random() < BARRIER_PROB
           ? (int) (Math.random() * (HEIGHT - BARRIER_HEIGHT)) + START_Y
           : -1);
   if (barrierY != -1) barrierBuffer = BARRIER_BUFFER;
   centerHinges[index] = new Turn(newX, newZ, prev.angle + newTurn, prev.angle, barrierY);
 }
コード例 #21
0
  public static int Rand(int n1) { // rand num generator

    double num = Math.random();
    double upone = Math.random();
    num = num * 10;
    upone = upone * 10;
    if (upone < 1) {
      num = 10;
    }
    int numrand = (int) num;

    return numrand;
  }
コード例 #22
0
ファイル: Title.java プロジェクト: dledlow/HighschoolGame
  @Override
  public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    width = frame.getWidth();
    height = frame.getHeight();
    sizeControl.width = width;
    sizeControl.height = height;

    if (info.pressed == true && !showGuide) {
      showGuide = true;
    }

    if (back.pressed == true && showGuide) {
      showGuide = false;
    }

    go.x = width / 2;
    go.y = height / 2;
    info.x = width / 2;
    info.y = height / 2 + 150;
    back.x = 3 * width / 4;
    back.y = height / 2 + 150;

    for (int i = 0; i < boomList.size(); i++) {
      boomList.get(i).updatePosition();
      if (Integer.parseInt(boomList.get(i).toString()) <= 0) {
        boomList.remove(i);
      } else {
        for (int ii = 0; ii < gravList.size(); ii++) {
          gravList.get(ii).pull(boomList.get(i));
          if (boomList.get(i).collide(gravList.get(ii))) {
            boomList.remove(i);
          }
        }
      }
    }

    count--;
    if (count <= 0) {

      double rand1 = Math.random();
      double rand2 = Math.random();
      for (int ii = 0; ii < num; ii++) {
        boomList.add(new boom(rand1 * width, rand2 * height));
      }
      count = delay;
    }

    repaint();
  }
コード例 #23
0
ファイル: Game.java プロジェクト: worldofanguis/VelociRUPtors
  /**
   * Az úthoz kapcsolódó elemek (autó, épület) elhelyezése rá - inicalizáláskor.
   *
   * @param road Az út amelyet módosítunk.
   */
  public void populateRoad(Road road) {
    try {
      if (road.hasCar() != null) return;
      if (cars.size() < maxCarsOnMap) {
        if (Math.random() < 0.1) {
          Civil c =
              new Civil((int) (Math.random() % (MinCivilSpeed - MaxCivilSpeed)) + MaxCivilSpeed);
          road.setCar(c);
        }
      }
    } catch (Exception ex) {

    }
  }
コード例 #24
0
  private String getCommentMoreURL(String sns_sys_id) {
    String jsonp1 = "141249668" + (int) (9999 * Math.random());
    String jsonp2 = "141249670" + (int) (9999 * Math.random());

    return "http://interface3.i.178.com/~cite.embed.ViewAll?callback=jsonp"
        + jsonp1
        + "&_="
        + jsonp2
        + "&res_id="
        + res_id
        + "&sys_res_id="
        + sns_sys_id
        + "&sys_name=manhua178";
  }
コード例 #25
0
ファイル: XieAnA4Q1.java プロジェクト: hapyboy/Practice
  /** ***************************** Creat Road ************************************ */
  public static int[] creatRoad(int length, int limV, double density) {

    int[] road = new int[length];

    for (int i = 0; i < road.length; i++) {
      if (Math.random() <= density) {
        road[i] = (int) (Math.random() * (limV + 1));
      } else {
        road[i] = -1;
      }
    }

    return road;
  }
コード例 #26
0
  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;
  }
コード例 #27
0
  /**
   * Currently we will arbitrarily choose the first node that is not a destination i.e. it's a
   * starting point\ if none such exists we will choose a random node.
   *
   * @param entitiesList
   * @param relationshipsList
   */
  private InternalNode getFirstEntity(
      List<InternalNode> entitiesList, List<InternalRelationship> relationshipsList) {
    List<InternalNode> entitiesLeft = new ArrayList<InternalNode>(entitiesList);

    // go through all the relationships and remove destination nodes
    for (InternalRelationship rel : relationshipsList) {
      entitiesLeft.remove(rel.getDestination());
    }
    if (!entitiesLeft.isEmpty()) {
      // TODO throw in random for fun of it
      return entitiesLeft.get((int) (Math.round(Math.random() * (entitiesLeft.size() - 1))));
    }
    // if all the nodes were destination nodes then return a random node.
    return entitiesList.get((int) (Math.round(Math.random() * (entitiesList.size() - 1))));
  }
コード例 #28
0
ファイル: Picture.java プロジェクト: AlexHuntsman/PhotoLab
  public void randomColor() {
    Pixel[][] pixels = this.getPixels2D();
    for (Pixel[] row : pixels) {
      for (Pixel currentPixel : row) {
        int randomRed, randomBlue, randomGreen;
        randomRed = (int) (Math.random() * 256);
        randomBlue = (int) (Math.random() * 256);
        randomGreen = (int) (Math.random() * 256);

        currentPixel.setBlue(randomBlue);
        currentPixel.setRed(randomRed);
        currentPixel.setGreen(randomGreen);
      }
    }
  }
コード例 #29
0
  protected void initUI() {
    File f = new File("Top100");
    String Str;
    String WORDS[] = new String[100];
    int FREQ[] = new int[100];
    String shuffle[] = new String[100];
    ArrayList<String> shuffling = new ArrayList<String>();
    int count = 0, i, temp = 1000000;
    try {
      Scanner br = new Scanner(f);

      while (br.hasNextLine()) {
        Str = br.nextLine();
        shuffling.add(Str);
      }
      br.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    Collections.shuffle(shuffling);
    for (String str : shuffling) {

      WORDS[count] = str.substring(0, str.indexOf(' '));
      FREQ[count] = Integer.parseInt(str.substring(str.indexOf(' ') + 1, str.length()));
      if (FREQ[count] < temp) temp = FREQ[count];
      count++;
    }
    JFrame frame = new JFrame(TestOpenCloud.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    // Cloud cloud = new Cloud();
    Random random = new Random();
    for (i = 0; i < 100; i++) {

      final int red = (int) (Math.random() * 150);
      final int green = (int) (Math.random() * 150);
      final int blue = (int) (Math.random() * 150);
      final JLabel label = new JLabel(WORDS[i]);
      label.setOpaque(false);
      label.setFont(new Font("Andalus", Font.PLAIN, ((FREQ[i] * 11) / temp)));
      Color color = new Color(red, green, blue);
      label.setForeground(color);
      panel.add(label);
    }
    frame.add(panel);
    frame.setSize(1366, 768);
    frame.setVisible(true);
  }
コード例 #30
0
ファイル: CoffeeUtensils.java プロジェクト: bbailey/ewok
 public Trap makeADeprecatedTrap(Environmental unlockThis) {
   Trap theTrap = null;
   int roll = (int) Math.round(Math.random() * 100.0);
   if (unlockThis instanceof Exit) {
     if (((Exit) unlockThis).hasADoor()) {
       if (((Exit) unlockThis).hasALock()) {
         if (roll < 20) theTrap = (Trap) CMClass.getAbility("Trap_Open");
         else if (roll < 80) theTrap = (Trap) CMClass.getAbility("Trap_Unlock");
         else theTrap = (Trap) CMClass.getAbility("Trap_Enter");
       } else {
         if (roll < 50) theTrap = (Trap) CMClass.getAbility("Trap_Open");
         else theTrap = (Trap) CMClass.getAbility("Trap_Enter");
       }
     } else theTrap = (Trap) CMClass.getAbility("Trap_Enter");
   } else if (unlockThis instanceof Container) {
     if (((Container) unlockThis).hasALid()) {
       if (((Container) unlockThis).hasALock()) {
         if (roll < 20) theTrap = (Trap) CMClass.getAbility("Trap_Open");
         else if (roll < 80) theTrap = (Trap) CMClass.getAbility("Trap_Unlock");
         else theTrap = (Trap) CMClass.getAbility("Trap_Get");
       } else {
         if (roll < 50) theTrap = (Trap) CMClass.getAbility("Trap_Open");
         else theTrap = (Trap) CMClass.getAbility("Trap_Get");
       }
     } else theTrap = (Trap) CMClass.getAbility("Trap_Get");
   } else if (unlockThis instanceof Item) theTrap = (Trap) CMClass.getAbility("Trap_Get");
   return theTrap;
 }