public void reset() { // init the location of the rocket to the center. rocketXPos = getWidth2() / 2; rocketYPos = getHeight2() / 2; // rocket direction rocketRight = true; // rocket speed. rocketXSpeed = 0; rocketYSpeed = 0; rocketMaxSpeed = 10; // rocket lives rocketLife = 3; // star position. starXPos = new int[numStars]; starYPos = new int[numStars]; starActive = new boolean[numStars]; for (int index = 0; index < numStars; index++) { starXPos[index] = (int) (Math.random() * getWidth2()); starYPos[index] = (int) (Math.random() * getHeight2()); starActive[index] = true; } // score stuff score = 0; // missile stuff missile = new Missile[Missile.numMissile]; for (int index = 0; index < missile.length; index++) { missile[index] = new Missile(); } Missile.currentIndex = 0; starHit = -1; gameOver = false; }
public static String generateID() { String s = ""; int j; for (int i = 0; i < 8; i++) { j = (int) (Math.random() * 100); if (j < 16) { i--; continue; } s += String.format("%x", (int) j); } s += "ff"; for (int i = 0; i < 6; i++) { j = (int) (Math.random() * 100); if (j < 16) { i--; continue; } s += String.format("%x", (int) j); } s += "00"; return s; }
// ------------------------------------------------------------------------------------------------------------------------------------------------------- // 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); } }
public static void main(String[] args) { final int iloscLiczbWLosowaniu = 25; int[] aryNums; aryNums = new int[iloscLiczbWLosowaniu]; boolean powtarza = false; // for losuje 6 liczb do tablicy aryNums[] aryNums[0] = (int) ((47 * Math.random()) + 1); for (int i = 1; i < iloscLiczbWLosowaniu; i++) { int wylosowanaLiczba = (int) ((47 * Math.random()) + 1); for (int j = 1; j <= i; j++) { if (aryNums[j] == wylosowanaLiczba) { powtarza = true; } } // for sprawdza czy liczby sie nie powtarzają // for (int j = i; j < i; j--) { // if (wylosowanaLiczba != aryNums[j]) { // aryNums[i] = wylosowanaLiczba; // } else { // System.out.println("wylosowanaLiczba: " + wylosowanaLiczba + " aryNums[" + i + "]" // + aryNums[i]); // } // } } Arrays.sort(aryNums); // wyswietlenie for (int i = 0; i < iloscLiczbWLosowaniu; i++) { System.out.print(" " + aryNums[i]); } System.out.print("\n"); }
private void spawnRandomers() { for (int i = 0; i < randomN; i++) { float x = (float) Math.random() * width; float y = (float) Math.random() * height; float r = (float) Math.sqrt( Math.pow(((Player) players.get(0)).getX() - x, 2) + Math.pow(((Player) players.get(0)).getY() - x, 2)); while (r < distanceLimit) { x = (float) Math.random() * width; y = (float) Math.random() * height; r = (float) Math.sqrt( Math.pow(((Player) players.get(0)).getX() - x, 2) + Math.pow(((Player) players.get(0)).getY() - y, 2)); } enemies.add(new EnemyTypes.Random(x, y, 0.5f, borders)); } spawnRandomersB = false; }
/** * metoda zajistujici rozmisteni lodi - ve skutecnosti zatim rozmistuje jen nahodne ctverecky, ne * cele lode */ public void rozmistiLode(int i) { for (; i > 0; i--) { x = (int) (Math.random() * (size - 1)); y = (int) (Math.random() * (size - 1)); pole[x][y] = lod; total_impacts++; } }
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(); }
// 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
private void spawnBomb() { float x, y; for (int i = 0; i < bombN; i++) { if (Math.random() > .5) { // top/bottom y = (Math.random() > .5) ? borders[1] : borders[3]; x = (float) Math.random() * borders[2] - borders[0]; // width } else { x = (Math.random() > .5) ? borders[0] : borders[2]; y = (float) Math.random() * borders[3] - borders[1]; // height } enemies.add(new EnemyTypes.Bomb(x, y, 1f, borders, scbInstance)); } }
private String generarPassWord() { String password = ""; for (int x = 0; x < 8; x++) { int y = (int) (2 * Math.random()); switch (y) { case 0: password += (int) (10 * Math.random()); break; default: password += (char) ((122 - 97 + 1)) * Math.random() + 97; } } return password; }
public void setNeighbours(Message message) { String msg = message.message; String[] msg_data = msg.split(" "); int neigh_count = Integer.parseInt(msg_data[2]); if (neigh_count == 9999 || neigh_count == 9998 || neigh_count == 9997 || neigh_count == 9996) { System.out.println("Registration failed..!!!"); } if (neigh_count == 1) { Configuration.setNeighbor(msg_data[3], Integer.parseInt(msg_data[4])); joinWithNeighbor(msg_data[3], Integer.parseInt(msg_data[4])); } else if (neigh_count == 2) { Configuration.setNeighbor(msg_data[3], Integer.parseInt(msg_data[4])); Configuration.setNeighbor(msg_data[6], Integer.parseInt(msg_data[7])); joinWithNeighbor(msg_data[3], Integer.parseInt(msg_data[4])); joinWithNeighbor(msg_data[6], Integer.parseInt(msg_data[7])); } else if (neigh_count > 2) { int rand = (int) Math.floor(Math.random() * neigh_count); Configuration.setNeighbor(msg_data[3 * rand + 3], Integer.parseInt(msg_data[3 * rand + 4])); int neigh_port_1 = Integer.parseInt(msg_data[3 * rand + 4]), neigh_port_2; String neigh_ip_1 = msg_data[3 * rand + 3], neigh_ip_2; joinWithNeighbor(neigh_ip_1, neigh_port_1); while (true) { rand = (int) Math.floor(Math.random() * neigh_count); neigh_ip_2 = msg_data[3 * rand + 3]; neigh_port_2 = Integer.parseInt(msg_data[3 * rand + 4]); if (neigh_ip_1.equals(neigh_ip_2) && neigh_port_1 == neigh_port_2) continue; else { Configuration.setNeighbor(neigh_ip_2, neigh_port_2); joinWithNeighbor(neigh_ip_2, neigh_port_2); break; } } for (int x = 0; x < neigh_count; x++) { Configuration.setBackUpNeighbor(msg_data[3 * x + 3], Integer.parseInt(msg_data[3 * x + 4])); } } }
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); }
private void levelSetup() { reset(); switch (level) { case 1: distance = 600; monsterN = 0; randomN = 0; rainN = 30; defaultDistance = 600; timeLast = 10000; spawnCircleB = true; break; case 2: distance = 600; monsterN = 0; randomN = 30; rainN = 30; defaultDistance = 600; timeLast += 10000; spawnCircleB = true; break; case 3: distance = 600; monsterN = 30; randomN = 0; rainN = 0; defaultDistance = 600; timeLast += 10000; spawnCircleB = true; break; default: distance = (float) (Math.random() * 200 + 400 - level * 5); monsterN = (int) (Math.random() * 25 + 10 + level); randomN = (int) (Math.random() * 25 + 10 + level); rainN = (int) (Math.random() * 10 + 10 + level); defaultDistance = distance; timeLast += 5000 + level * 1000; spawnCircleB = true; } monsterN *= monsterMultiplier; randomN *= monsterMultiplier; spawnMonsterB = true; spawnRandomersB = true; spawnIncrease = true; spawnRainB = true; }
// ------------------------------------------------------------------------------------------------------------------------------------------------------- // Patterns public void newPattern() { int prob = (int) (Math.random() * probs.get(level - 1) + 1); Pattern p = new Pattern(0, -300, prob, (int) (backy * 0.1)); if (checkSpawn(new Rectangle(p.getX(), p.getY(), p.getWidth(), p.getHeight())) == true) { for (Coin i : p.getCoins()) { coinList.add(i); } for (Star i : p.getStars()) { starList.add(i); } for (Box i : p.getBoxes()) { boxList.add(i); } for (Jumper i : p.getJumpers()) { jumperList.add(i); } for (Enemy i : p.getEnemies()) { enemyList.add(i); } for (Spikes i : p.getSpikes()) { spikeList.add(i); } for (Powerup i : p.getPowerUps()) { pupList.add(i); } for (Rectangle i : p.getRects()) { rectList.add(i); } } }
public int[] solve() { // (0,1 or -1 for dont care) int rounds = 0, num_lits = cnf.num_lits; long starttime = System.currentTimeMillis(); long endtime = starttime + maxtime; boolean[] minterm = new boolean[num_lits]; int flips = Math.min(1000, 3 * num_lits); if (stack == null) { stack = new int[num_lits]; } randomize(minterm); while (endtime > System.currentTimeMillis()) { rounds++; if (cnf.satisfies(minterm)) { JDDConsole.out.println("SAT/" + (System.currentTimeMillis() - starttime) + "ms"); return toIntVector(minterm); } if ((rounds % flips) == 0) { randomize(minterm); } else { int choice = (Math.random() < p) ? choice = random(num_lits) : findLiteral(minterm); minterm[choice] = !minterm[choice]; } } JDDConsole.out.println( "UNKNOWN(" + rounds + " rounds)/" + (System.currentTimeMillis() - starttime) + "ms"); return null; }
public static double[] RandomArray(int n) { double[] A = new double[n]; for (int i = 0; i < n; i++) { A[i] = Math.random(); } return A; }
/** @param args the command line arguments */ public static void main(String[] args) { try { int randomNum = (int) ((Math.random() * 100) + 1); Socket server = new Socket("127.0.0.1", 8888); BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter output = new PrintWriter(server.getOutputStream(), true); String leggi; int total = 0; output.println(randomNum); while ((leggi = input.readLine()) != null) { System.out.println("Valore letto: " + leggi); total += Integer.parseInt(leggi); } System.out.println("Somma dei valori ricevuti dal Server: " + total); if (total % 2 == 0) { System.out.println("PARI"); } else { System.out.println("DISPARI"); } } catch (UnknownHostException ex) { System.out.println("Errore indirizzo sconosciuto:" + ex.getMessage()); } catch (IOException ex) { System.out.println(ex); } }
public static void doRandomCommand() throws Exception { int commandCount = 6; // remember to count 0 int command = (int) (Math.random() * commandCount); switch (command) { case 0: createFile(); break; case 1: readFile(); break; case 2: deleteFile(); break; case 3: createClient(); break; case 4: createServer(); break; case 5: exit(); break; default: System.out.println("Bad command number: " + command); break; } }
// Add a random tetris shape to the arraylist // Add the shape to the tool bar // Also find the ai command when ai is enabled public void addShape() { shapeTrack = new ArrayList<Integer>(); int n = (int) (Math.random() * 7); switch (n) { case (0): shapes.add(new Block(THA.WIDTH / 2 - 40, -80, new Color(0, 0, 128))); break; case (1): shapes.add(new Line(THA.WIDTH / 2 - 40, -80, new Color(75, 0, 130))); break; case (2): shapes.add(new LeftZ(THA.WIDTH / 2 - 40, -80, new Color(255, 215, 0))); break; case (3): shapes.add(new RightZ(THA.WIDTH / 2 - 40, -80, new Color(255, 20, 147))); break; case (4): shapes.add(new T(THA.WIDTH / 2 - 40, -80, new Color(205, 0, 0))); break; case (5): shapes.add(new LeftL(THA.WIDTH / 2 - 40, -80, new Color(255, 165, 0))); break; case (6): shapes.add(new RightL(THA.WIDTH / 2 - 40, -80, new Color(0, 128, 0))); break; default: System.out.println("Impossible Error!!!"); break; } ns.clear(); ns.addShape(shapes); if (shapeAI.getAI()) { aiCommand = shapeAI.initAI(map, shapes.get(0)); } }
public void testRerankFilters() throws IOException { int queryDocID = (int) (Math.random() * 10000); IndexReader reader = DirectoryReader.open(FSDirectory.open(new File("index-large"))); // select one feature for the large index: int featureIndex = 4; int count = 0; long ms = System.currentTimeMillis(); ImageSearchHits hits = searchers[featureIndex].search(reader.document(queryDocID), reader); RerankFilter rerank = new RerankFilter(featureClasses[0], DocumentBuilder.FIELD_NAME_CEDD); LsaFilter lsa = new LsaFilter(featureClasses[0], DocumentBuilder.FIELD_NAME_CEDD); FileUtils.saveImageResultsToPng( "GeneralTest_rerank_0_old", hits, reader.document(queryDocID).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]); hits = rerank.filter(hits, reader.document(queryDocID)); FileUtils.saveImageResultsToPng( "GeneralTest_rerank_1_new", hits, reader.document(queryDocID).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]); hits = lsa.filter(hits, reader.document(queryDocID)); FileUtils.saveImageResultsToPng( "GeneralTest_rerank_2_lsa", hits, reader.document(queryDocID).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]); }
public void run() { pr.println("Reader " + id + " trying to get into CR"); mutex.semWait(); // semWait on mutex, only one reader can adjust count readCount++; if (readCount == 1) S.semWait(); // semWait on S mutex.semSignal(); // semSignal on mutex pr.println("Reader " + id + " is reading"); try { sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { } ; pr.println("Reader " + id + " is done reading"); mutex.semWait(); readCount--; if (readCount == 0) S.semSignal(); // semSignal on S mutex.semSignal(); // semSignal on mutex }
public static void main(String[] s) throws IOException { char moves[] = new char[9], player = (int) Math.round(Math.random() * 1) == 1 ? 'X' : 'O'; int move = 0; boolean winner = false, draw = false, init = false; for (int i = 0; i < moves.length; i++) moves[i] = '*'; drawScreen(moves, player, move, init); init = true; while (!winner && !draw) { player = (player == 'X') ? 'O' : 'X'; move = checkMove(moves, getInput()); drawScreen(moves, player, move, init); winner = checkForWinner(moves, player); draw = checkForDraw(moves); } if (winner) { newLine(3); System.out.println("Winner!"); System.out.println("Player " + player + " wins!"); } else { newLine(3); System.out.println("Draw!"); System.out.println("Nobody wins."); } }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
public void LevelContinue() { short i; int dx = 1; int random; try { int blocksize = game.getBlocksize(); int[] ghosty = game.getGhosty(); int[] ghostx = game.getGhostx(); int nrofghosts = game.getNrofghosts(); for (i = 0; i < nrofghosts; i++) { ghosty[i] = 4 * blocksize; ghostx[i] = 4 * blocksize; ghostdy[i] = 0; ghostdx[i] = dx; dx = -dx; random = (int) (Math.random() * (currentspeed + 1)); if (random > currentspeed) random = currentspeed; ghostspeed[i] = validspeeds[random]; } } catch (Exception e) { e.printStackTrace(); } }
public void go() { setUpGui(); try { Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); // make a sequencer and open sequencer.addControllerEventListener(m1, new int[] {127}); Sequence seq = new Sequence(Sequence.PPQ, 4); Track track = seq.createTrack(); int r = 0; for (int i = 0; i < 300; i += 4) { r = (int) ((Math.random() * 50) + 1); track.add(makeEvent(144, 1, r, 100, i)); track.add(makeEvent(176, 1, 127, 0, i)); track.add(makeEvent(128, 1, r, 100, i + 2)); } // end loop sequencer.setSequence(seq); sequencer.start(); sequencer.setTempoInBPM(120); } catch (Exception ex) { ex.printStackTrace(); } } // close method
/** * 返回想要的随机数,Nub代表随机数的位数 比如 Nub为3,则返回的字符串可能为 254 * * @param Nub * @return */ public static String getRandomNub(int Nub) { String num = ""; for (int i = 0; i < Nub; i++) { num += String.valueOf((int) (10 * Math.random())); } return num; }
public RadixSort(int a, int b) { arraylength = a; digits = b; nums = new int[arraylength]; for (int i = 0; i < arraylength; i++) { nums[i] = (int) (Math.random() * Math.pow(10, b)); } }
public void paint(Graphics g) { super.paint(g); Dimension size = getSize(); double w = size.getWidth() - 50; double h = size.getHeight() + 20; try { readFile(); } catch (IOException e) { System.err.println("IO issue"); } barWidth = ((int) (w / numBars)) - 20; pos = 5; int xPos[] = {pos, pos, pos, pos}; int yPos[] = {pos, pos, pos, pos}; maxVal = maxValue(values); double barH, ratio; for (int i = 0; i < numBars - 1; i++) { Color col[] = new Color[numBars]; for (int j = 0; j < numBars - 1; j++) { col[j] = new Color((int) (Math.random() * 0x1000000)); } ratio = (double) values[i] / (double) maxVal; barH = ((h) * ratio) - 10; xPos[0] = pos; xPos[2] = pos + barWidth; xPos[1] = xPos[0]; xPos[3] = xPos[2]; yPos[0] = (int) h; yPos[1] = (int) barH; yPos[2] = yPos[1]; yPos[3] = yPos[0]; System.out.println( "xPos:" + xPos[1] + " yPos:" + yPos[0] + " h:" + h + " barH:" + barH + " ratio:" + ratio + " pos:" + pos); int stringPtsY[] = { ((i + 1) * 20) + 180, ((i + 1) * 20) + 200, ((i + 1) * 20) + 200, ((i + 1) * 20) + 180 }; int stringPtsX[] = {600, 600, 580, 580}; g.setColor(col[i]); g.fillPolygon(xPos, yPos, xPos.length); g.fillPolygon(stringPtsX, stringPtsY, 4); g.setColor(Color.black); g.drawString(labels[i], 610, ((i + 1) * 20) + 195); pos = pos + barWidth + 10; } }
// Weight matrix= w[number inputs][number outputs] private Double[][] initializeWeights(int length, int length2, Double[][] w) { w = new Double[length][length2]; for (int i = 0; i < length; i++) { for (int j = 0; j < length2; j++) { w[i][j] = (double) Math.random() - 0.5; } } return w; }
public void actionPerformed(ActionEvent actionevent) { if (actionevent.getActionCommand().equals("ADD_DATA")) { double d = 0.90000000000000002D + 0.20000000000000001D * Math.random(); lastValue = lastValue * d; Millisecond millisecond = new Millisecond(); System.out.println("Now = " + millisecond.toString()); series.add(new Millisecond(), lastValue); } }