public void prepare(ColumnFamilyStore cfs) {
      if (tree.partitioner() instanceof RandomPartitioner) {
        // You can't beat an even tree distribution for md5
        tree.init();
      } else {
        List<DecoratedKey> keys = new ArrayList<DecoratedKey>();
        for (DecoratedKey sample : cfs.keySamples(request.range)) {
          assert request.range.contains(sample.token)
              : "Token " + sample.token + " is not within range " + request.range;
          keys.add(sample);
        }

        if (keys.isEmpty()) {
          // use an even tree distribution
          tree.init();
        } else {
          int numkeys = keys.size();
          Random random = new Random();
          // sample the column family using random keys from the index
          while (true) {
            DecoratedKey dk = keys.get(random.nextInt(numkeys));
            if (!tree.split(dk.token)) break;
          }
        }
      }
      logger.debug("Prepared AEService tree of size " + tree.size() + " for " + request);
      ranges = tree.invalids();
    }
Example #2
0
  public static void main(String[] args) throws FileNotFoundException {

    /* Loads the word list and stores its length */
    String ext = "/afs/cats/courses/cmps109-db/cmps012a-pa1/wordList.txt";
    Scanner in = new Scanner(new FileInputStream(ext));
    int listSize = in.nextInt(); // length of the word list

    /* Randomly selects word from the word list */
    Random rand = new Random();
    int n = rand.nextInt(listSize) + 1;
    for (int i = 1; i < n; i++) in.next();
    String word = in.next();

    /* Displays to the user the number of letters in the word */
    System.out.println("Your word is " + word.length() + " letters long.");

    /* Recursive method that plays the game. TRUE return indicates win */
    if (play(word)) {

      System.out.println("You win! The word was " + word + ".");

    } else { // Display for if the user loses

      System.out.println("You lose. The word was " + word + ".");
    }
  }
Example #3
0
 public int choiceOneCard(Player self) { // 幫我看一下self用法是不是錯了
   Random ran = new Random();
   int cardNo = ran.nextInt(self.hand.size()); // 表示第幾張牌
   int cardId = self.hand.get(cardNo); // 表示值
   self.hand.remove(cardNo);
   return cardId;
 }
  /**
   * 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 void testFormat() throws Exception {
    localFs = FileSystem.getLocal(defaultConf);
    localFs.delete(workDir, true);

    Job job = new Job(new Configuration(defaultConf));
    Path file = new Path(workDir, "test.txt");

    int seed = new Random().nextInt();
    Random random = new Random(seed);

    // for a variety of lengths
    for (int length = 0; length < MAX_LENGTH; length += random.nextInt(MAX_LENGTH / 10) + 1) {
      // create a file with length entries
      Writer writer = new OutputStreamWriter(localFs.create(file));
      try {
        MyClass mc = new MyClass();
        for (int i = 0; i < length; i++) {
          mc.s = Integer.toString(i);
          mc.v = i;
          byte[] raw = MessagePack.pack(mc);
          byte[] b64e = base64_.encodeBase64(raw);
          byte[] b64d = base64_.decode(b64e);
          MyClass mc2 = MessagePack.unpack(b64d, mc.getClass());
          assertEquals(mc.s, mc2.s);
          assertEquals(mc.v, mc2.v);

          writer.write(base64_.encodeToString(raw));
        }
      } finally {
        writer.close();
      }
      checkFormat(job);
    }
  }
  /**
   * Tests offset and limit clauses for query.
   *
   * @throws Exception If failed.
   */
  public void testOffsetLimit() throws Exception {
    IgniteCache<Integer, Integer> c =
        ignite(0).getOrCreateCache(cacheConfig("ints", true, Integer.class, Integer.class));

    try {
      List<Integer> res = new ArrayList<>();

      Random rnd = new GridRandom();

      for (int i = 0; i < 10; i++) {
        int val = rnd.nextInt(100);

        c.put(i, val);
        res.add(val);
      }

      Collections.sort(res);

      String qry = "select _val from Integer order by _val ";

      assertEqualsCollections(res, columnQuery(c, qry));
      assertEqualsCollections(res.subList(0, 0), columnQuery(c, qry + "limit ?", 0));
      assertEqualsCollections(res.subList(0, 3), columnQuery(c, qry + "limit ?", 3));
      assertEqualsCollections(res.subList(0, 9), columnQuery(c, qry + "limit ? offset ?", 9, 0));
      assertEqualsCollections(res.subList(3, 7), columnQuery(c, qry + "limit ? offset ?", 4, 3));
      assertEqualsCollections(res.subList(7, 9), columnQuery(c, qry + "limit ? offset ?", 2, 7));
      assertEqualsCollections(res.subList(8, 10), columnQuery(c, qry + "limit ? offset ?", 2, 8));
      assertEqualsCollections(res.subList(9, 10), columnQuery(c, qry + "limit ? offset ?", 1, 9));
      assertEqualsCollections(res.subList(10, 10), columnQuery(c, qry + "limit ? offset ?", 1, 10));
      assertEqualsCollections(
          res.subList(9, 10), columnQuery(c, qry + "limit ? offset abs(-(4 + ?))", 1, 5));
    } finally {
      c.destroy();
    }
  }
Example #7
0
File: Gen.java Project: 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();
 }
Example #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);
      }
    }
  }
  /**
   * Returns the index of the piece that could be downloaded by the peer in parameter
   *
   * @param id The id of the peer that wants to download
   * @return int The index of the piece to request
   */
  private synchronized int choosePiece2Download(String id) {
    synchronized (this.isComplete) {
      int index = 0;
      ArrayList<Integer> possible = new ArrayList<Integer>(this.nbPieces);
      for (int i = 0; i < this.nbPieces; i++) {
        if ((!this.isPieceRequested(i) || (this.isComplete.cardinality() > this.nbPieces - 3))
            &&
            // (this.isRequested.cardinality() == this.nbPieces)) &&
            (!this.isPieceComplete(i))
            && this.peerAvailabilies.get(id) != null) {

          if (this.peerAvailabilies.get(id).get(i)) possible.add(i);
        }
      }
      // System.out.println(this.isRequested.cardinality()+" "+this.isComplete.cardinality()+" " +
      // possible.size());
      if (possible.size() > 0) {
        Random r = new Random(System.currentTimeMillis());
        index = possible.get(r.nextInt(possible.size()));
        this.setRequested(index, true);
        return (index);
      }
      return -1;
    }
  }
  static StringDoubleMap test(int n, int range) {
    // Generate random data
    Random rand = new Random();
    Set<Integer> set = new HashSet<Integer>();
    for (int i = 0; i < n; i++) set.add(rand.nextInt(range));

    // Make the map
    StringDoubleMap map = new StringDoubleMap(0);
    // map.switchToSortedList();
    for (int x : set) {
      map.put("" + x, 1.0 * x);
    }

    // System.out.println("here");
    check(set, map);
    map.switchToSortedList();
    check(set, map);
    map.switchToHashTable();
    check(set, map);

    map.lock();
    for (int x : set) map.put("" + x, 1.0 * x);

    assert set.size() == map.size();
    return map;
  }
 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());
   }
 }
Example #12
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();
  }
Example #13
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;
 }
Example #14
0
  /**
   * Gera uma partícula aleatória de dimensões fixas.
   *
   * <p>Define os valores para size, maxValue, dimensions, lBest e inertia.
   *
   * @param pagesArray array com as páginas do banco de dados
   * @param size quantidade de dimensões da partícula
   */
  public Particle(int[] pagesArray, int size, int inertia, Random r) throws IOException {

    maxValue = pagesArray.length;
    dimensions = new int[size];
    velocity = new int[size];
    lBest = new int[size];
    this.inertia = inertia;
    this.rnd = r;

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

      dimensions[i] = (int) (rnd.nextFloat() * pagesArray.length);
      lBest[i] = (int) (rnd.nextFloat() * pagesArray.length);
      // System.out.println("dimensions["+i+"] : "+dimensions[i]);
    }

    File f = new File("dimensions");

    FileWriter fw = new FileWriter(f, true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw);

    pw.println("pagesArray.length " + pagesArray.length);
    for (int i = 0; i < dimensions.length; i++) {
      pw.print(dimensions[i] + " ");
    }
    pw.println();

    pw.close();
    bw.close();
    fw.close();
  }
Example #15
0
  public static void createTestFiles() {
    try {
      System.out.println("Creating test files ... ");
      Random rand = new Random();
      String rootname = "f-";

      long[] sizes = {0, 1, 50000000};

      File testdir = new File(dirname);
      FileUtil.mkdirs(testdir);

      for (int i = 0; i < sizes.length; i++) {
        long size = sizes[i];
        File file = new File(testdir, rootname + String.valueOf(size));
        System.out.println(file.getName() + "...");
        FileChannel fc = new RandomAccessFile(file, "rw").getChannel();

        long position = 0;
        while (position < size) {
          long remaining = size - position;
          if (remaining > 1024000) remaining = 1024000;
          byte[] buffer = new byte[new Long(remaining).intValue()];
          rand.nextBytes(buffer);
          ByteBuffer bb = ByteBuffer.wrap(buffer);
          position += fc.write(bb);
        }

        fc.close();
      }
      System.out.println("DONE\n");
    } catch (Exception e) {
      Debug.printStackTrace(e);
    }
  }
Example #16
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!");
   }
 }
Example #17
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;
  }
    /**
     * Get a path from the local FS. If size is known, we go round-robin over the set of disks (via
     * the configured dirs) and return the first complete path which has enough space.
     *
     * <p>If size is not known, use roulette selection -- pick directories with probability
     * proportional to their available space.
     */
    public synchronized Path getLocalPathForWrite(
        String pathStr, long size, Configuration conf, boolean checkWrite) throws IOException {
      confChanged(conf);
      int numDirs = localDirsPath.length;
      int numDirsSearched = 0;
      // remove the leading slash from the path (to make sure that the uri
      // resolution results in a valid path on the dir being checked)
      if (pathStr.startsWith("/")) {
        pathStr = pathStr.substring(1);
      }
      Path returnPath = null;
      Path path = new Path(pathStr);

      if (size == SIZE_UNKNOWN) { // do roulette selection: pick dir with probability
        // proportional to available size
        long[] availableOnDisk = new long[dirDF.length];
        long totalAvailable = 0;

        // build the "roulette wheel"
        for (int i = 0; i < dirDF.length; ++i) {
          availableOnDisk[i] = dirDF[i].getAvailable();
          totalAvailable += availableOnDisk[i];
        }

        // Keep rolling the wheel till we get a valid path
        Random r = new java.util.Random();
        while (numDirsSearched < numDirs && returnPath == null) {
          long randomPosition = Math.abs(r.nextLong()) % totalAvailable;
          int dir = 0;
          while (randomPosition > availableOnDisk[dir]) {
            randomPosition -= availableOnDisk[dir];
            dir++;
          }
          dirNumLastAccessed = dir;
          returnPath = createPath(path, checkWrite);
          if (returnPath == null) {
            totalAvailable -= availableOnDisk[dir];
            availableOnDisk[dir] = 0; // skip this disk
            numDirsSearched++;
          }
        }
      } else {
        while (numDirsSearched < numDirs && returnPath == null) {
          long capacity = dirDF[dirNumLastAccessed].getAvailable();
          if (capacity > size) {
            returnPath = createPath(path, checkWrite);
          }
          dirNumLastAccessed++;
          dirNumLastAccessed = dirNumLastAccessed % numDirs;
          numDirsSearched++;
        }
      }
      if (returnPath != null) {
        return returnPath;
      }

      // no path found
      throw new DiskErrorException("Could not find any valid local " + "directory for " + pathStr);
    }
Example #19
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;
 }
 private static String randString(int len) {
   Random r = new Random();
   StringBuilder ret = new StringBuilder(len);
   while (len-- > 0) {
     ret.append((char) (r.nextInt(26) + 'A'));
   }
   return ret.toString();
 }
Example #21
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);
   }
 }
Example #22
0
 public static String createRandomHexNumber(int length) {
   Random random = new Random(System.currentTimeMillis());
   char[] result = new char[length];
   for (int i = 0; i < length; i++) {
     int r = random.nextInt(16);
     result[i] = Integer.toHexString(r).charAt(0);
   }
   return new String(result);
 }
Example #23
0
File: Gen.java Project: 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();
  }
Example #24
0
File: Gen.java Project: 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();
 }
Example #25
0
 private int getRand(int min, int max) {
   Date now = new Date();
   long seed = now.getTime();
   Random randomizer = new Random(seed);
   int n = max - min + 1;
   int i = randomizer.nextInt(n);
   if (i < 0) i = -i;
   return min + i;
 }
Example #26
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);
    }
  }
Example #27
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;
 }
  public static void main(String[] args) throws Exception {
    String graphName = args[0];
    int nShards = Integer.parseInt(args[1]);

    CircleOfTrustSalsa csalsa = new CircleOfTrustSalsa(new VertexQuery(graphName, nShards), 10000);

    VertexIdTranslate vertexTrans =
        VertexIdTranslate.fromFile(
            new File(ChiFilenames.getVertexTranslateDefFile(graphName, nShards)));

    BufferedReader cmdIn = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
      System.out.print("Enter vertex id to query >> :: ");
      String ln = cmdIn.readLine();
      int vertex = Integer.parseInt(ln);

      // Circle of trust is just the vertex's followers for now
      HashSet<Integer> circle = csalsa.queryService.queryOutNeighbors(vertexTrans.forward(vertex));

      int maxCircleSize = 300;
      // max 500
      if (circle.size() > maxCircleSize) {
        int[] all = new int[circle.size()];
        int i = 0;
        for (Integer v : circle) all[i++] = v;
        HashSet<Integer> filteredCircle = new HashSet<Integer>();
        Random r = new Random(260379);
        for (i = 0; i < maxCircleSize; i++)
          filteredCircle.add(all[Math.abs(r.nextInt()) % all.length]);
        circle = filteredCircle;
      }

      csalsa.initializeGraph(circle);

      long t = System.currentTimeMillis();
      csalsa.computeSALSA(3);
      logger.info("SALSA computation took " + (System.currentTimeMillis() - t) + "ms");

      circle.add(vertexTrans.forward(vertex));
      ArrayList<SalsaVertex> top = csalsa.topAuthorities(20, circle);
      int j = 1;
      for (SalsaVertex sv : top) {
        int originalId = vertexTrans.backward(sv.id);
        logger.info(
            "Top "
                + (j++)
                + " = "
                + originalId
                + " "
                + csalsa.namify(originalId)
                + " ("
                + sv.value
                + ")");
      }
    }
  }
Example #29
0
 public void testNaNValues() throws ClassNotFoundException, IOException {
   testWriteAndRead(
       new ComplexClass(
           rand.nextInt(),
           rand.nextLong(),
           "hello",
           rand.nextBoolean(),
           Double.NaN,
           rand.nextFloat()));
 }
Example #30
0
 int selectCycle() {
   if (t < N) {
     return generator.nextInt(5);
   } else {
     if (Rtmp > alpha) {
       currentPath = previousPath;
     } else currentPath = generator.nextInt(5);
   }
   return currentPath;
 }