Ejemplo n.º 1
0
Archivo: Gen.java Proyecto: hrnn/olymp
 static void genRandom(int cnt, int value) throws IOException {
   ArrayList<Integer> ch = new ArrayList<Integer>();
   ch.add(rand.nextInt(value / cnt));
   for (int i = 1; i < cnt; i++) ch.add(rand.nextInt(value / cnt) + 1 + ch.get(i - 1));
   crypto(ch);
   print();
 }
Ejemplo n.º 2
0
 private Card genNewCard() {
   Random rand = new Random();
   Card card = new Card(rand.nextInt(52) + 1);
   while (cardUsed.contains(card)) card = new Card(rand.nextInt(52) + 1);
   cardUsed.add(card);
   return card;
 }
Ejemplo n.º 3
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;
  }
Ejemplo n.º 4
0
 public void attack(Character other) {
   Random r = new Random();
   Scanner sc = new Scanner(System.in);
   int dex = dexterity;
   int mult = 1;
   int x = r.nextInt(6) + 1, y = r.nextInt(6) + 1, z = r.nextInt(6) + 1;
   System.out.println("\nChoose your weapon:\n1 - Dagger\n2 - Short sword");
   System.out.print(">");
   int weapon = sc.nextInt();
   if (weapon == 1) {
     dex = dexterity + 3;
     mult = 2;
   } else if (weapon == 2) {
     dex = dexterity + 1;
     mult = 3;
   }
   System.out.println("\n" + this + " attacked!");
   pause();
   if (x + y + z <= dex) {
     int dmg = damageDone(other, mult);
     other.loseHealth(dmg);
     System.out.println("\n" + name + " did " + dmg + " damage to " + other + "!");
   } else {
     System.out.println("\n" + name + " missed!");
   }
 }
Ejemplo n.º 5
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();
  }
Ejemplo n.º 6
0
  /**
   * Base tick method for the level. Updates all entities, tiles, and player. Has slow repopulation
   * algorithm
   */
  public void tick() {
    player.tick();
    List<Entity> toTick = new ArrayList<Entity>();
    int lr = 7;
    for (int x = -lr; x < lr; x++) {
      for (int y = -lr; y < lr; y++) {
        Tile tile = getTile(player.x + x, player.z + y);
        tile.addToTick(toTick);
        tile.tick();
      }
    }

    for (int i = 0; i < toTick.size(); i++) {
      Entity e = toTick.get(i);
      e.tick(this);
    }
    tickcount++;
    if (tickcount % 1800 == 0) {
      System.out.println("Adding entity to world");
      if (r != null) {
        int rx = r.nextInt(w);
        int ry = r.nextInt(h);

        if (skillNoise.noise(rx / 80d, ry / 80d) > 0.0) {
          SmallMob mob = new SmallMob();
          if (!tiles[rx + ry * w].blocks(mob)) {
            tiles[rx + ry * w].addEntity(r.nextInt(4), mob);
          }
        }
      }
    }
  }
 public static void main(String[] args) {
   Random r = new Random();
   int n;
   if (args.length == 1) {
     n = Integer.parseInt(args[0]);
   } else {
     n = r.nextInt(10000) + 1;
   }
   try {
     OutputStream ofs = new FileOutputStream("scores.txt");
     ObjectOutputStream oos = new ObjectOutputStream(ofs);
     for (int i = 0; i < n; ++i) {
       int testNum = r.nextInt(21);
       String name = randString(r.nextInt(6) + 5);
       while (testNum-- > 0) {
         oos.writeUTF(name);
         oos.writeInt(r.nextInt(101));
       }
     }
     ofs.close();
   } catch (Exception e) {
     System.out.println("Error creating scores.txt: " + e.getMessage());
   }
   try {
     InputStream ifs = new FileInputStream("scores.txt");
     String name = findStudentWithTopThreeAverageScores(ifs);
     System.out.println("top student is " + name);
     ifs.close();
   } catch (Exception e) {
     System.out.println("Error reading scores.txt: " + e.getMessage());
   }
 }
Ejemplo n.º 8
0
  public static void golf(String file_name) {
    Random rand = new Random();
    ArrayList<Person> players = new ArrayList();
    try {
      Scanner in = new Scanner(new FileReader(file_name));
      while (in.hasNextLine()) {
        String name = in.nextLine();
        Person person = new Person(name);
        players.add(person);
      }
    } catch (Exception e) {
      System.out.println("Could not find file");
    }

    while (!players.isEmpty()) {
      int first, second;
      do {
        first = rand.nextInt(players.size());
        second = rand.nextInt(players.size());
      } while (first == second);
      System.out.println("Team:");
      System.out.println(players.get(first).name);
      System.out.println(players.get(second).name);
      System.out.print("\n");
      players.remove(second);
      if (second < first) {
        players.remove(first - 1);
      } else {
        players.remove(first);
      }
    }
  }
Ejemplo n.º 9
0
 public Object call() throws Exception {
   _barrier.await(); // barrier, to force racing start
   for (long j = 0; j < _count; j++)
     _map.put(
         j + _offset,
         new TestKey(_rand.nextLong(), _rand.nextInt(), (short) _rand.nextInt(Short.MAX_VALUE)));
   return null;
 }
Ejemplo n.º 10
0
 public static void shuffleArray(long[] a) {
   int n = a.length;
   Random random = new Random();
   random.nextInt();
   for (int i = 0; i < n; i++) {
     int change = i + random.nextInt(n - i);
     swap(a, i, change);
   }
 }
Ejemplo n.º 11
0
Archivo: Gen.java Proyecto: hrnn/olymp
  static void genNo(int cnt, int value) throws IOException {
    ArrayList<Integer> ch = new ArrayList<Integer>();

    for (int i = 0; i < cnt - 1; i++) ch.add(rand.nextInt(value) + 1);
    ch.add(ch.get(rand.nextInt(cnt - 1)));
    Collections.sort(ch);
    crypto(ch);
    print();
  }
Ejemplo n.º 12
0
Archivo: Gen.java Proyecto: hrnn/olymp
 static void genRandom3(int cnt, int len) throws IOException {
   for (int i = 0; i < cnt; i++) {
     String t = "";
     int sz = 1 + rand.nextInt(len);
     for (int j = 0; j < sz; j++) t += (char) ('a' + rand.nextInt(10));
     data.add(t);
   }
   print();
 }
Ejemplo n.º 13
0
  public void npcDied(Player p, int npcID, int abSX, int abSY) {
    Random rand = new Random();
    try {

      BufferedReader in = new BufferedReader(new FileReader("./data/npcs/npcdrops.cfg"));
      String input;
      int on = 0;
      String[] splitEQL;
      String[] splitCOM;
      String[] splitDSH;
      String[] splitCLN;
      String[] splitSCL;
      while ((input = in.readLine()) != null) {
        splitEQL = null;
        splitEQL = null;
        splitDSH = null;
        splitCLN = null;
        splitSCL = null;
        if (!input.startsWith("/")
            && input.contains("=")
            && input.contains(",")
            && input.contains("-")
            && input.contains(":")) {
          try {
            splitEQL = input.split("=");
            if (Integer.parseInt(splitEQL[0]) == npcID) {
              splitSCL = splitEQL[1].split(";");
              int Wealth = 0;

              for (int i = Wealth; i < splitSCL.length; i++) {
                splitCOM = splitSCL[i].split(",");
                splitDSH = splitCOM[1].split("-");
                splitCLN = splitCOM[2].split(":");
                int item = Integer.parseInt(splitCOM[0]);
                int min = Integer.parseInt(splitDSH[0]);
                int max = Integer.parseInt(splitDSH[1]);
                int chance = Integer.parseInt(splitCLN[0]);
                int outOf = Integer.parseInt(splitCLN[1]);
                int amount = rand.nextInt((max - min) + 1) + min;
                int ifDrop = rand.nextInt(outOf) + 1;
                if (ifDrop <= chance && npccanloot == true) {
                  Engine.items.createGroundItem(item, amount, abSX, abSY, heightLevel, p.username);
                  npccanloot = false;
                }
              }
            }
          } catch (Exception e) {
            System.out.println("Exception dropping item:\n" + e);
          }
          ++on;
        }
      }
      in.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
Ejemplo n.º 14
0
 private int getRandomGame(int num) {
   int ranGame;
   Random randomNum = new Random();
   ranGame = randomNum.nextInt(num) + 1;
   while (!gameRecord.containsKey(ranGame)) {
     ranGame = randomNum.nextInt(num) + 1;
   }
   return ranGame;
 }
Ejemplo n.º 15
0
 public void testWritingRandomValue() throws ClassNotFoundException, IOException {
   testWriteAndRead(
       new ComplexClass(
           rand.nextInt(),
           rand.nextLong(),
           Integer.toString(rand.nextInt()),
           rand.nextBoolean(),
           rand.nextDouble(),
           rand.nextFloat()));
 }
Ejemplo n.º 16
0
 int selectCycle() {
   if (t < N) {
     return generator.nextInt(5);
   } else {
     if (Rtmp > alpha) {
       currentPath = previousPath;
     } else currentPath = generator.nextInt(5);
   }
   return currentPath;
 }
Ejemplo n.º 17
0
  /**
   * Produces an index for a tournament selection candidate.
   *
   * @param inIndex The index which is to be replaced by the current reproduction event (used only
   *     if trivial-geography is enabled).
   * @param inPopsize The size of the population.
   * @return the index for the tournament selection.
   */
  protected int TournamentSelectionIndex(int inIndex, int inPopsize) {
    if (_trivialGeographyRadius > 0) {
      int index = (_RNG.nextInt(_trivialGeographyRadius * 2) - _trivialGeographyRadius) + inIndex;
      if (index < 0) index += inPopsize;

      return (index % inPopsize);
    } else {
      return _RNG.nextInt(inPopsize);
    }
  }
Ejemplo n.º 18
0
 public static int randomColor(Random om) {
   return pack(
       om.nextInt(256),
       om.nextInt(256),
       om.nextInt(256),
       // 255);
       // 253 + Rand.om.nextInt(3));
       // 200 + Rand.om.nextInt(53));
       randAlpha(om));
 }
Ejemplo n.º 19
0
 public void chooseDeal(Player self) {
   int numOfDeck = Dealer.deck.size();
   int numOfHand = self.hand.size(); // 表示第幾張牌
   Random ran = new Random(); // 之後再加入一點人工智慧
   int cardNo = 0; // 假設一開始想要牌組裡的第0張牌
   if (numOfHand % 2 == 0) cardNo = ran.nextInt(numOfDeck / 2) + numOfDeck / 2;
   else cardNo = ran.nextInt(numOfDeck / 2) + numOfDeck / 2;
   int cardId = Dealer.deck.get(cardNo);
   self.hand.add(cardId);
   Dealer.deck.remove(cardNo);
 }
Ejemplo n.º 20
0
 public static boolean addWord(String w) {
   Random r = new Random();
   int randomc = r.nextInt(board[0].length);
   int randomr = r.nextInt(board.length);
   int deltaRow = -1 + r.nextInt(3);
   int deltaCol = -1 + r.nextInt(3);
   if (deltaRow == deltaCol && deltaCol == 0) {
     return false;
   }
   w = w.toUpperCase();
   return addWordHelper(w, randomr, randomc, deltaRow, deltaCol);
 }
Ejemplo n.º 21
0
 // create file of random size in given directory
 static Path createSourceFile(Path dir) throws IOException {
   String name = "source" + Integer.toString(rand.nextInt());
   Path file = dir.resolve(name);
   createFile(file);
   byte[] bytes = new byte[rand.nextInt(128 * 1024)];
   rand.nextBytes(bytes);
   try (OutputStream out = newOutputStream(file)) {
     out.write(bytes);
   }
   randomizeAttributes(file);
   return file;
 }
  public static void construct_processes() {

    for (int i = 0; i < rando; i++) {
      processes[i] = new Process(i, random.nextInt(10), random.nextInt(10), random.nextInt(10));
      System.out.print(
          processes[i].getProcessNumber()
              + " "
              + processes[i].getStartTime()
              + " "
              + processes[i].getRunTime()
              + "\n");
    }
  }
Ejemplo n.º 23
0
Archivo: Gen.java Proyecto: hrnn/olymp
 static void genRandomSame(int cnt, int len) throws IOException {
   for (int i = 0; i < cnt; i++) {
     String t = "";
     for (int j = 0; j < len; j++) t += (char) ('a' + rand.nextInt(10));
     data.add(t);
     if (rand.nextInt(100) < 30 && i < cnt - 1) {
       data.add(t);
       i++;
     }
   }
   Collections.sort(data);
   print();
 }
Ejemplo n.º 24
0
  private InputStream generateData() {
    final String LINE_SEPARATOR = System.getProperty("line.separator");

    StringWriter writer = new StringWriter();

    int maxMale = numGuests / 2;
    int maxFemale = numGuests / 2;

    int maleCount = 0;
    int femaleCount = 0;

    // init hobbies
    List hobbyList = new ArrayList();
    for (int i = 1; i <= maxHobbies; i++) {
      hobbyList.add("h" + i);
    }

    Random rnd = new Random();
    for (int i = 1; i <= numGuests; i++) {
      char sex = rnd.nextBoolean() ? 'm' : 'f';
      if (sex == 'm' && maleCount == maxMale) {
        sex = 'f';
      }
      if (sex == 'f' && femaleCount == maxFemale) {
        sex = 'm';
      }
      if (sex == 'm') {
        maleCount++;
      }
      if (sex == 'f') {
        femaleCount++;
      }

      List guestHobbies = new ArrayList(hobbyList);

      int numHobbies = minHobbies + rnd.nextInt(maxHobbies - minHobbies + 1);
      for (int j = 0; j < numHobbies; j++) {
        int hobbyIndex = rnd.nextInt(guestHobbies.size());
        String hobby = (String) guestHobbies.get(hobbyIndex);
        writer.write(
            "(guest (name n" + i + ") (sex " + sex + ") (hobby " + hobby + "))" + LINE_SEPARATOR);
        guestHobbies.remove(hobbyIndex);
      }
    }
    writer.write("(last_seat (seat " + numSeats + "))" + LINE_SEPARATOR);

    writer.write(LINE_SEPARATOR);
    writer.write("(context (state start))" + LINE_SEPARATOR);

    return new ByteArrayInputStream(writer.getBuffer().toString().getBytes());
  }
Ejemplo n.º 25
0
 public void makeRandomSchedule() {
   amountOfRooms = rooms.size();
   for (Activity activity : activities) {
     int i = numberGenerator.nextInt(amountOfRooms);
     int amountOfTimeslots = rooms.get(i).timetable.size();
     int j = numberGenerator.nextInt(amountOfTimeslots);
     while (rooms.get(i).timetable.get(j) != null) {
       i = numberGenerator.nextInt(amountOfRooms);
       amountOfTimeslots = rooms.get(i).timetable.size();
       j = numberGenerator.nextInt(amountOfTimeslots);
     }
     rooms.get(i).timetable.set(j, activity);
   }
 }
Ejemplo n.º 26
0
  private JSONObject specialMove(int gameCount) {
    Random randomNum = new Random();
    GameInfo gameInfo;
    JSONObject jObj = new JSONObject();
    JSONObject action = new JSONObject();
    int game;
    int addPoints;
    int special;
    // Gets random number to denote which game to use action on
    game = getRandomGame(gameCount);
    gameInfo = gameRecord.get(game);
    // Checks if all specials are used
    if (gameInfo.checkSpecial()) {
      return moveUser(gameCount);
    }
    // Gets random number to denote which special move to use
    special = randomNum.nextInt(4);
    while (gameInfo.checkSpecialMove(special)) {
      special = randomNum.nextInt(4);
    }
    gameInfo.useSpecialMove(special);

    addPoints = randomNum.nextInt(41) - 20;
    gameInfo.addPoints(addPoints);
    gameInfo.incrementCount();

    try {
      jObj.put("game", game);

      action.put("actionType", "specialMove");
      action.put("actionNumber", gameInfo.getCount());
      action.put("pointsAdded", addPoints);
      if (special == SHUFFLE) {
        action.put("move", "Shuffle");
      } else if (special == CLEAR) {
        action.put("move", "Clear");
      } else if (special == INVERT) {
        action.put("move", "Invert");
      } else {
        action.put("move", "Rotate");
      }
      action.put("points", gameInfo.getPoints());

      jObj.put("action", action);
      jObj.put("user", gameInfo.getUser());
    } catch (JSONException e) {
      System.out.println("could not put");
    }
    return jObj;
  }
Ejemplo n.º 27
0
  // "randomize" the file attributes of the given file.
  static void randomizeAttributes(Path file) throws IOException {
    String os = System.getProperty("os.name");
    boolean isWindows = os.startsWith("Windows");
    boolean isUnix = os.equals("SunOS") || os.equals("Linux");
    boolean isDirectory = isDirectory(file, NOFOLLOW_LINKS);

    if (isUnix) {
      Set<PosixFilePermission> perms = getPosixFilePermissions(file, NOFOLLOW_LINKS);
      PosixFilePermission[] toChange = {
        PosixFilePermission.GROUP_READ,
        PosixFilePermission.GROUP_WRITE,
        PosixFilePermission.GROUP_EXECUTE,
        PosixFilePermission.OTHERS_READ,
        PosixFilePermission.OTHERS_WRITE,
        PosixFilePermission.OTHERS_EXECUTE
      };
      for (PosixFilePermission perm : toChange) {
        if (heads()) {
          perms.add(perm);
        } else {
          perms.remove(perm);
        }
      }
      setPosixFilePermissions(file, perms);
    }

    if (isWindows) {
      DosFileAttributeView view =
          getFileAttributeView(file, DosFileAttributeView.class, NOFOLLOW_LINKS);
      // only set or unset the hidden attribute
      view.setHidden(heads());
    }

    boolean addUserDefinedFileAttributes =
        heads() && getFileStore(file).supportsFileAttributeView("xattr");

    // remove this when copying a direcory copies its named streams
    if (isWindows && isDirectory) addUserDefinedFileAttributes = false;

    if (addUserDefinedFileAttributes) {
      UserDefinedFileAttributeView view =
          getFileAttributeView(file, UserDefinedFileAttributeView.class);
      int n = rand.nextInt(16);
      while (n > 0) {
        byte[] value = new byte[1 + rand.nextInt(100)];
        view.write("user." + Integer.toString(n), ByteBuffer.wrap(value));
        n--;
      }
    }
  }
Ejemplo n.º 28
0
 public static int rules(
     String top, Vector<String> first, Vector<String> second, Vector<String> afia) {
   while (!first.isEmpty() && !second.isEmpty()) {
     if (count % 2 == 0) {
       boolean check = false;
       for (int i = 0; i < first.size(); i++) {
         check =
             matcher(
                 top,
                 first.elementAt(
                     i)); // performs a linear search on player1's whot to see if any matches the
         // top card
         if (check == true) {
           place.addElement(first.elementAt(i));
           first.removeElementAt(i);
           break;
         }
       }
       if (check == false) {
         Random rd = new Random();
         int pick = Math.abs(rd.nextInt(afia.size() - 1)) % (afia.size() - 1);
         first.addElement(afia.elementAt(pick));
         afia.removeElementAt(pick);
       }
     } else {
       boolean check = false;
       for (int i = 0; i < second.size(); i++) {
         check =
             matcher(
                 top,
                 second.elementAt(
                     i)); // performs a linear search on player1's whot to see if any matches the
         // top card
         if (check == true) {
           place.addElement(second.elementAt(i));
           second.removeElementAt(i);
           break;
         }
       }
       if (check == false) {
         Random rd = new Random();
         int pick = Math.abs(rd.nextInt(afia.size() - 1)) % (afia.size() - 1);
         second.addElement(afia.elementAt(pick));
         afia.removeElementAt(pick);
       }
     }
   }
   return 1;
 }
Ejemplo n.º 29
0
 /*
    n - size of the array
    m - max value for each entry
 */
 public Mode(int n, int m) {
   r = new Random();
   a = new int[n];
   for (int i = 0; i < n; i++) {
     a[i] = r.nextInt(m);
   }
 }
Ejemplo n.º 30
0
  /** run once each game tick */
  public void networkTick() {
    field_72584_h = false;
    currentTicks++;
    mcServer.theProfiler.startSection("packetflow");
    theNetworkManager.processReadPackets();
    mcServer.theProfiler.endStartSection("keepAlive");

    if ((long) currentTicks - ticksOfLastKeepAlive > 20L) {
      ticksOfLastKeepAlive = currentTicks;
      keepAliveTimeSent = System.nanoTime() / 0xf4240L;
      keepAliveRandomID = randomGenerator.nextInt();
      sendPacketToPlayer(new Packet0KeepAlive(keepAliveRandomID));
    }

    if (chatSpamThresholdCount > 0) {
      chatSpamThresholdCount--;
    }

    if (creativeItemCreationSpamThresholdTally > 0) {
      creativeItemCreationSpamThresholdTally--;
    }

    mcServer.theProfiler.endStartSection("playerTick");

    if (!field_72584_h && !playerEntity.playerHasConqueredTheEnd) {
      playerEntity.onUpdateEntity();
    }

    mcServer.theProfiler.endSection();
  }