Пример #1
1
 protected Iterator<CachedAccount> getRuleAwareIterator() {
   if (rules == null) {
     return cache.iterator();
   }
   ArrayList<CachedAccount> orderedCache = new ArrayList<AccountCache.CachedAccount>(cache);
   int startRandom = -1;
   for (int index = 0; index < orderedCache.size(); index++) {
     Rules rule = rules.get(index);
     if (rule == null) {
       if (startRandom >= 0) {
         Collections.shuffle(orderedCache.subList(startRandom, index));
         startRandom = -1;
       }
       continue;
     }
     switch (rule) {
       case RANDOM:
         if (startRandom < 0) {
           startRandom = index;
         }
         break;
       default:
         if (startRandom >= 0 && index - startRandom > 1) {
           Collections.shuffle(orderedCache.subList(startRandom, index));
         }
         startRandom = -1;
         break;
     }
   }
   if (startRandom >= 0) {
     Collections.shuffle(orderedCache.subList(startRandom, orderedCache.size()));
   }
   return orderedCache.iterator();
 }
Пример #2
0
  private static List<FoodSchedule> schedule(
      List<String> breakfastParticipants,
      List<String> snackParticipants,
      List<DateTime> fridaysAvailable) {
    // shuffle both lists
    Collections.shuffle(breakfastParticipants);
    List<String> modifiableBreakfast = new ArrayList<String>(breakfastParticipants);
    Collections.shuffle(snackParticipants);
    List<String> modifiableSnack = new ArrayList<String>(snackParticipants);

    // while not empty, schedule
    int participantCount = breakfastParticipants.size();

    List<FoodSchedule> schedule = new ArrayList<FoodSchedule>();
    for (int i = 0; i < participantCount; i += 2) {
      String bp1 = modifiableBreakfast.remove(0);
      String bp2 = modifiableBreakfast.remove(0);
      String sp1 = modifiableSnack.remove(0);
      String sp2 = modifiableSnack.remove(0);
      DateTime friday = fridaysAvailable.remove(0);
      FoodSchedule fs = new FoodSchedule();
      fs.setDateTime(friday);
      fs.setBreakfastParticipantIds(Arrays.asList(bp1, bp2));
      fs.setSnackParticipantIds(Arrays.asList(sp1, sp2));
      schedule.add(fs);
    }
    return schedule;
  }
  /** Give it many different graphs and see if it can reconstruct the order correctly */
  @Test
  public void exhaustiveValid() {
    for (int numRows = 2; numRows <= 10; numRows++) {
      for (int numCols = 2; numCols <= 10; numCols++) {
        List<QuadBlob> expected = createBlobs(numCols, numRows);

        // randomize the order
        List<QuadBlob> input = new ArrayList<QuadBlob>();
        input.addAll(expected);
        Collections.shuffle(input, rand);

        for (QuadBlob b : input) {
          Collections.shuffle(b.conn, rand);
        }

        OrderChessboardQuadBlobs alg = new OrderChessboardQuadBlobs(numCols, numRows);
        assertTrue(numCols + " " + numRows, alg.order(input));

        // check the node order to see if it's as expected
        List<QuadBlob> found = alg.getResults();
        assertEquals(expected.size(), found.size());
        for (int i = 0; i < input.size(); i++) {
          assertTrue(expected.get(i) == found.get(i));
        }
      }
    }
  }
Пример #4
0
  /**
   * Factory method for a list of engines and processes.
   *
   * @param engines a list of engines to be included in the test suite
   * @param processes a list of processes to be included in the test suite
   * @param testFolderName
   * @return a test suite where each engine tests all passed processes
   */
  public static BPMNTestSuite createTests(
      List<AbstractBPMNEngine> engines, final List<BPMNProcess> processes, String testFolderName) {

    BPMNTestSuite test = new BPMNTestSuite();
    test.setPath(Paths.get(testFolderName));

    for (AbstractBPMNEngine engine : engines) {
      List<BPMNProcess> clonedProcesses =
          processes.stream().map(BPMNProcess::createCopyWithoutEngine).collect(Collectors.toList());

      // link them
      for (BPMNProcess process : clonedProcesses) {
        process.setEngine(engine);
        engine.getProcesses().add(process);
      }

      // set parentFolder
      engine.setParentFolder(test.getPath());
    }

    test.setEngines(engines);
    test.setProcessesCount(getProcessesCount(engines));

    Collections.shuffle(engines);
    for (AbstractBPMNEngine engine : engines) {
      Collections.shuffle(engine.getProcesses());
    }

    return test;
  }
Пример #5
0
  // make 2-letter options with 'vokal' as second letter
  private String generateAutoOptionsVokal(int nOptions, String answer, String avoid) {

    String vokaler = "A,E,I,O,U,Y,Æ,Ø,Å";
    ArrayList<String> vokalerList = new ArrayList<String>(Arrays.asList(vokaler.split(",")));

    String c0 = answer.substring(0, 1);
    String c1 = answer.substring(1, 2);
    Collections.shuffle(vokalerList);

    ArrayList<String> options = new ArrayList<String>();
    options.add(answer);

    if (nOptions > vokalerList.size()) nOptions = vokalerList.size();

    int i = 0;
    while (options.size() < nOptions) {

      // add if different from answer
      if (!c1.equals(vokalerList.get(i))) options.add(c0 + vokalerList.get(i));

      i++;
    }

    Collections.shuffle(options);
    return joinArray(options);
  }
Пример #6
0
 private void placeTheoryLecture(Lecture lecture, ArrayList<ClassRoom> rooms2) {
   // TODO Auto-generated method stub
   int size = lecture.getStudentGroup().getSize();
   String dept = lecture.getStudentGroup().getDepartment();
   boolean invalid = true;
   ClassRoom room = null;
   Collections.shuffle(rooms2);
   while (invalid) {
     room = getBestRoom(size, rooms2);
     if (room.getDepartment().equalsIgnoreCase(dept)) {
       invalid = false;
       Collections.shuffle(rooms2);
     } else {
       Collections.shuffle(rooms2);
     }
   }
   ArrayList<Day> weekdays = room.getWeek().getWeekDays();
   Iterator<Day> daysIterator = weekdays.iterator();
   while (daysIterator.hasNext()) {
     Day day = daysIterator.next();
     ArrayList<TimeSlot> timeslots = day.getTimeSlot();
     Iterator<TimeSlot> timeslotIterator = timeslots.iterator();
     while (timeslotIterator.hasNext()) {
       TimeSlot lecture2 = timeslotIterator.next();
       if (lecture2.getLecture() == null) {
         lecture2.setLecture(lecture);
         return;
       }
     }
   }
 }
Пример #7
0
  /** @param args */
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<String>();
    names.add("Н┼и╔");
    names.add("═шик");
    names.add("┴шмЯик");
    for (int i = 0; i < names.size(); i++) {
      System.out.println(names.get(i));
    }
    for (String name : names) {
      System.out.println(name);
    }
    System.out.println("*****************");
    System.out.println(names);
    System.out.println("*****************");
    names.remove(0);
    System.out.println(names);
    names.add(1, "Н┼и╔");
    System.out.println("*****************");
    System.out.println(names);

    Collections.shuffle(names, new Random());
    System.out.println(names);
    System.out.println("******");
    Collections.shuffle(names);
    System.out.println(names);
  }
Пример #8
0
  /**
   * add 20 shuffled rows
   *
   * @throws InterruptedException
   */
  private void load(Client client)
      throws NoConnectionsException, ProcCallException, IOException, InterruptedException {
    int pkey = 0;
    a_int.clear();
    a_inline_str.clear();
    a_pool_str.clear();

    boolean async = true;

    for (int i = 0; i < 20; i++) {
      a_int.add(i);
      a_inline_str.add("a_" + i);
      a_pool_str.add(simpleString + i);
    }

    Collections.shuffle(a_int);
    Collections.shuffle(a_inline_str);
    Collections.shuffle(a_pool_str);

    for (int i = 0; i < 20; i++) {
      SyncCallback cb = new SyncCallback();
      client.callProcedure(
          cb, "InsertO1", pkey, a_int.get(i), a_inline_str.get(i), a_pool_str.get(i));

      if (!async) {
        cb.waitForResponse();
        VoltTable vt = cb.getResponse().getResults()[0];
        assertTrue(vt.getRowCount() == 1);
      }
      pkey = pkey + 1;
    }

    client.drain();
  }
  /** Merges a fixed number of tasks into a job */
  private void collapseClustering() {
    for (Map.Entry<Integer, List> pairs : mDepth2Task.entrySet()) {
      List list = pairs.getValue();

      long seed = System.nanoTime();
      Collections.shuffle(list, new Random(seed));
      seed = System.nanoTime();
      Collections.shuffle(list, new Random(seed));

      int num = list.size();
      int avg = this.clusterSize;

      int start = 0;
      int end = 0;
      int i = 0;
      do {
        start = i * avg;
        end = start + avg - 1;
        i++;
        if (end >= num) {
          end = num - 1;
        }
        Job job = addTasks2Job(list.subList(start, end + 1));
      } while (end < num - 1);
    }
  }
Пример #10
0
  public static void reset(boolean useMoreBuildings, boolean useEvenMoreBuildings) {
    GeneralSupply.useMoreBuildings = useMoreBuildings;
    GeneralSupply.useEvenMoreBuildings = useEvenMoreBuildings;
    stallsLeft.clear();
    stallsLeft.addAll(Arrays.asList(STALLS));
    if (!useEvenMoreBuildings) {
      stallsLeft.remove(stallsLeft.size() - 1);
    }
    if (!useMoreBuildings) {
      stallsLeft.remove(stallsLeft.size() - 1);
    }
    if (Main.DEBUG) {
      stallsLeft.clear();
      stallsLeft.add(STALLS[0]);
      stallsLeft.add(STALLS[1]);
    }
    Collections.shuffle(stallsLeft);

    troughsLeft = MAX_TROUGHS;

    extsLeft.clear();
    extsLeft.addAll(Arrays.asList(EXTS));
    if (!useEvenMoreBuildings) {
      extsLeft.remove(extsLeft.size() - 1);
    }
    if (!useMoreBuildings) {
      extsLeft.remove(extsLeft.size() - 1);
    }
    Collections.shuffle(extsLeft);
    extsUsed.clear();

    SPECIAL_BUILDINGS.clear(); // clear building instances
    randomizeBuildings(INITIAL_BUILDING_COUNTS);
  }
Пример #11
0
  public double runSimulatedAnnealing(int iterations) {
    if (!locked) lock();
    double temp = 1;
    double coolingFactor = Math.pow(0.001, 1d / iterations);
    double currentEnergy = getEnergy();
    if (nodes.isEmpty()) return currentEnergy;
    Collections.shuffle(nodesWithSeveralChildrenScaled, random);
    Collections.shuffle(sourceFakeEdges, random);

    while (temp > 0.001) {
      double action = random.nextDouble();
      if (action < 0.19) { // add fake edge
        currentEnergy = tryAddFakeEdge(temp, currentEnergy);
        assert currentEnergy == getEnergy();
      } else if (action
          < 0.36) { // remove fake edge (slightly higher probability - we don't want too many fake
        // edges) - update: apparently, that hypothesis is wrong
        currentEnergy = tryRemoveFakeEdge(temp, currentEnergy);
        assert currentEnergy == getEnergy();
      } else if (action < 0.7) { // swap two children of some node
        currentEnergy = trySwapChildren(temp, currentEnergy);
        assert currentEnergy == getEnergy();
      } else { // change where one of the sources is attached to
        currentEnergy = tryChangeSource(temp, currentEnergy);
        assert currentEnergy == getEnergy();
      }
      temp *= coolingFactor;
    }
    return currentEnergy;
  }
Пример #12
0
  @Override
  public List<URI> selectHttpService() {
    List<ServiceDescriptor> serviceDescriptors =
        Lists.newArrayList(serviceSelector.selectAllServices());
    if (serviceDescriptors.isEmpty()) {
      return ImmutableList.of();
    }

    // favor https over http
    List<URI> httpsUri = Lists.newArrayList();
    for (ServiceDescriptor serviceDescriptor : serviceDescriptors) {
      String https = serviceDescriptor.getProperties().get("https");
      if (https != null) {
        try {
          httpsUri.add(new URI(https));
        } catch (URISyntaxException ignored) {
        }
      }
    }
    List<URI> httpUri = Lists.newArrayList();
    for (ServiceDescriptor serviceDescriptor : serviceDescriptors) {
      String http = serviceDescriptor.getProperties().get("http");
      if (http != null) {
        try {
          httpUri.add(new URI(http));
        } catch (URISyntaxException ignored) {
        }
      }
    }

    // return random(https) + random(http)
    Collections.shuffle(httpsUri);
    Collections.shuffle(httpUri);
    return ImmutableList.<URI>builder().addAll(httpsUri).addAll(httpUri).build();
  }
Пример #13
0
 public void setTimeTable(
     ArrayList<StudentGroups> studentGroups2, ArrayList<ClassRoom> rooms2, String string) {
   // TODO Auto-generated method stub
   Collections.shuffle(studentGroups2);
   Stack<Lecture> lecturesStack = new Stack<Lecture>();
   for (Iterator<StudentGroups> sdtGrpIterator = studentGroups2.iterator();
       sdtGrpIterator.hasNext(); ) {
     StudentGroups studentGrp = sdtGrpIterator.next();
     String subject = studentGrp.getSubjectName();
     int noOfLectures = studentGrp.getNoOfLecturePerWeek();
     for (int i = 0; i < noOfLectures; i++) {
       Collections.shuffle(classes);
       Iterator<Lecture> classIterator = classes.iterator();
       while (classIterator.hasNext()) {
         Lecture lecture = classIterator.next();
         if (lecture.getSubject().equalsIgnoreCase(subject)) {
           Lecture mainLecture = new Lecture(lecture.getProfessor(), lecture.getSubject());
           mainLecture.setStudentGroup(studentGrp);
           lecturesStack.push(mainLecture);
           break;
         }
       }
     }
   }
   while (!(lecturesStack.empty())) {
     Collections.shuffle(lecturesStack);
     Lecture lecture2 = lecturesStack.pop();
     if (string.equalsIgnoreCase("theory")) {
       placeTheoryLecture(lecture2, rooms2);
     }
     if (string.equalsIgnoreCase("practical")) {
       placePracticalLecture(lecture2, rooms2);
     }
   }
 }
Пример #14
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);
  }
Пример #15
0
  public void createBaits() // creates the baits and fills the list with them
      {
    // Creating x locations of the baits
    ArrayList<Integer> xLocations = new ArrayList<Integer>();
    for (int i = 1; i < sizeOfArena - 2; i++) {
      xLocations.add(new Integer(i));
    }
    Collections.shuffle(xLocations);

    // Creating y locations of the baits
    ArrayList<Integer> yLocations = new ArrayList<Integer>();
    for (int i = 1; i < sizeOfArena - 2; i++) {
      yLocations.add(new Integer(i));
    }
    Collections.shuffle(yLocations);

    // creating pieces for baits
    Piece[] baitPieces = new Piece[BAIT_NUM];

    for (int i = 0; i < BAIT_NUM; i++) {
      baitPieces[i] = new Piece(xLocations.get(i), yLocations.get(i), 2);
    }

    // create one special bait and fill other with regularBaits
    baitPieces[0].setType(3);
    baitPieces[0].setImage(3);
    Bait tmp = new BonusPointBait(baitPieces[0]);
    baits.add(tmp);
    baitPieces[1].setType(4);
    baitPieces[1].setImage(4);
    tmp = new ExtendingBait(baitPieces[1]);
    baits.add(tmp);
    baitPieces[2].setType(5);
    baitPieces[2].setImage(5);
    tmp = new PoisonousBait(baitPieces[2]);
    baits.add(tmp);
    baitPieces[3].setType(6);
    baitPieces[3].setImage(6);
    tmp = new ShorteningBait(baitPieces[3]);
    baits.add(tmp);
    baitPieces[4].setType(7);
    baitPieces[4].setImage(7);
    tmp = new SuperSnakeBait(baitPieces[4]);
    baits.add(tmp);
    baitPieces[5].setType(8);
    baitPieces[5].setImage(8);
    tmp = new UpsideDownBait(baitPieces[5]);
    baits.add(tmp);

    for (int i = 6; i < BAIT_NUM; i++) {
      tmp = new RegularBait(baitPieces[i]);
      baits.add(tmp);
    }
    // for(int i=0;i<BAIT_NUM;i++)
    //	System.out.println(baits.get(i).retrievePiece().getType());
    Collections.shuffle(baits);
  }
Пример #16
0
  // generate 2-letter options with no 'vokaler'
  private String generateAutoOptionsConsonant(int nOptions, String answer, String avoid) {

    char c0 = answer.charAt(0);
    String allOptionsStr;
    switch (c0) {
      case 'B':
        allOptionsStr = "BJ,BL,BR,BV";
        break;
      case 'D':
        allOptionsStr = "DJ,DL,DR,DV";
        break;
      case 'F':
        allOptionsStr = "FJ,FL,FR,FV";
        break;
      case 'G':
        allOptionsStr = "GJ,GL,GR,GV";
        break;
      case 'K':
        allOptionsStr = "KJ,KL,KR,KV";
        break;
      case 'P':
        allOptionsStr = "PJ,PL,PR,PV";
        break;
      case 'S':
        allOptionsStr = "SJ,SK,SL,SM,SN,SP,ST,SV";
        break;
      case 'T':
        allOptionsStr = "TJ,TR,TN,TV";
        break;
      default:
        allOptionsStr = "XX,YY,ZZ";
        break;
    }

    ArrayList<String> allOptions = new ArrayList<String>(Arrays.asList(allOptionsStr.split(",")));
    Collections.shuffle(allOptions);

    ArrayList<String> options = new ArrayList<String>();
    options.add(answer);

    if (nOptions > allOptions.size()) nOptions = allOptions.size();

    int i = 0;
    while (options.size() < nOptions) {

      // add if different from answer
      if (!answer.equals(allOptions.get(i))) options.add(allOptions.get(i));

      i++;
    }

    Collections.shuffle(options);
    return joinArray(options);
  }
 /**
  * Return the given set of students in a random order, however, all real students before last-like
  * ({@link Student#isDummy()} is true) students.
  */
 @Override
 public List<Student> order(List<Student> students) {
   List<Student> real = new ArrayList<Student>(students.size());
   List<Student> dummy = new ArrayList<Student>(students.size());
   for (Student student : students) {
     if (student.isDummy()) dummy.add(student);
     else real.add(student);
   }
   Collections.shuffle(dummy);
   Collections.shuffle(real);
   dummy.addAll(real);
   return dummy;
 }
Пример #18
0
 /**
  * Shuffle the uninstalled and installed list (separately) and select a random number of them
  * and install or uninstall them respectively.
  */
 private void randomize() {
   List<HostPair> hostList = new LinkedList<>(uninstalledOrWithdrawn);
   Collections.shuffle(hostList);
   List<HostPair> toInstall = hostList.subList(0, random.nextInt(hostList.size() - 1));
   List<HostPair> toRemove;
   if (!installed.isEmpty()) {
     hostList = new LinkedList<>(installed);
     Collections.shuffle(hostList);
     toRemove = hostList.subList(0, random.nextInt(hostList.size() - 1));
     uninstallIntents(toRemove);
   }
   installIntents(toInstall);
 }
Пример #19
0
  public static void main(String[] args) {
    Random rand = new Random(47);
    Integer[] ia = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
    System.out.println("Before shuffling: " + list1);
    Collections.shuffle(list1, rand);
    System.out.println("After shuffling: " + list1);
    System.out.println("array: " + Arrays.toString(ia));

    List<Integer> list2 = Arrays.asList(ia);
    System.out.println("Before shuffling: " + list2);
    Collections.shuffle(list2, rand);
    System.out.println("After shuffling: " + list2);
    System.out.println("array: " + Arrays.toString(ia));
  }
Пример #20
0
  /**
   * Grab random holiday from the equivalence class that falls between the two dates
   *
   * @param earliest the earliest date parameter as defined in the model
   * @param latest the latest date parameter as defined in the model
   * @return a holiday that falls between the dates
   */
  public String getRandomHoliday(String earliest, String latest) {
    String dateString = "";
    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);
    List<Holiday> holidays = new LinkedList<>();

    int min = Integer.parseInt(earlyDate.toString().substring(0, 4));
    int max = Integer.parseInt(lateDate.toString().substring(0, 4));
    int range = max - min + 1;
    int randomYear = (int) (Math.random() * range) + min;

    for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {
      holidays.add(s);
    }
    Collections.shuffle(holidays);

    for (Holiday holiday : holidays) {
      dateString = convertToReadableDate(holiday.forYear(randomYear));
      if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {
        break;
      }
    }
    return dateString;
  }
Пример #21
0
  /**
   * On créé la paquet de carte Troupes
   *
   * @return
   */
  public LinkedList<CarteTroupe> initialisationPaquetTroupe() {
    LinkedList<CarteTroupe> llct = new LinkedList<CarteTroupe>();
    int i = 1;

    for (Troupes t : hashTroupes) {
      CarteTroupe ct = new CarteTroupe(t);
      // On met 6 fois la même carte dans la liste
      for (int k = 0; k < 6; k++) {
        llct.add(ct);
      }
      // il faut également mettre un carte avec deux troupes (en tout 6 cartes)
      int j = 1;
      for (Troupes t2 : hashTroupes) {
        // On ne reprend pas les cartes précédentes (elles ont déjà ét traitées)
        if (i == j || i < j) {
          CarteTroupe ct2 = new CarteTroupe(t, t2);
          llct.add(ct2);
        }
        j++;
      }
      i++;
    }
    // On mélange le paquet
    Collections.shuffle(llct);

    return llct;
  }
  /**
   * Randomizes the entries of the node list if needed.
   *
   * @param list the list to potentially randomize.
   */
  private void potentiallyRandomizeNodeList(List<URI> list) {
    if (getStreamingNodeOrder().equals(CouchbaseNodeOrder.ORDERED)) {
      return;
    }

    Collections.shuffle(list);
  }
  /** Create a block that contains the indicated stimuli. */
  private static Block createBlock(List<Stimulus> stimuli, boolean training) {
    List<TrialGroup> trialGroups = new ArrayList<TrialGroup>();
    ;
    List<Trial> trialsInCurrentTrialGroup = new ArrayList<Trial>();

    Collections.shuffle(
        stimuli); // randomize stimulusorder to the order in which they will be displayed in this
                  // block

    // go through all stimuli
    for (Stimulus s : stimuli) {
      if (trialsInCurrentTrialGroup.size()
          < Options.trialsPerTrialGroup) { // still working on the current trialGroup
        trialsInCurrentTrialGroup.add(new Trial(s));
      }

      if (trialsInCurrentTrialGroup.size()
          == Options
              .trialsPerTrialGroup) { // current trialGroup is complete, create it and start a new
                                      // one
        trialGroups.add(new TrialGroup(trialsInCurrentTrialGroup, training));
        trialsInCurrentTrialGroup.clear();
      }
    }

    return new Block(trialGroups);
  }
 @Override
 public List<Square> apply(
     Integer nrOfGoldItems2,
     Integer nrOfWalls2,
     Integer maxLatitude2,
     Integer maxLongitude2) {
   ArrayList<Square> available = new ArrayList<Square>();
   int oneForTheBank = 1;
   int goldLeft = nrOfGoldItems2;
   int nrOfGoldSquares = 0;
   while (goldLeft > 0) {
     int gold = (int) Math.min((Math.random() * 9) + 1, goldLeft);
     goldLeft = goldLeft - gold;
     nrOfGoldSquares++;
     available.add(new GoldSquare(gold));
   }
   for (int i = 0;
       i < (maxLatitude2 * maxLongitude2) - nrOfGoldSquares - nrOfWalls2 - oneForTheBank;
       i++) {
     available.add(Square.empty());
   }
   for (int i = 0; i < nrOfWalls2; i++) {
     available.add(new WallSquare());
   }
   Collections.shuffle(available);
   return available;
 }
Пример #25
0
  private void pickSmart() {
    this.buildingFound = false;
    synchronized (ContextManager.randomLock) {
      Collections.shuffle(GlobalVars.burgleMap); // Shuffle the map
      for (Building b : GlobalVars.burgleMap) {
        // TODO: Tune this logic for Objective #2 of the project. Consider game theory or some other
        // type
        //      of SoS decision making process to decide if it is best to travel to burgle location
        // or
        //      prevent other burgles by traveling to less-burgled parts of the map (e.g. replace
        // the 25%
        //      value with "game theory" idea where the cost/benefits are adjusted (trade study) to
        //      analyze behavior on crime
        Uniform uniform = RandomHelper.createUniform(0, 1);
        if (uniform.nextDouble()
            < GlobalVars.probTraveltoRecentCrime) { // 25% chance of traveling near recent crime
          if ((b.jurisdiction == this.jurisdiction) && !(this.burgleMapSave.contains(b))) {
            this.b_pick = b;
            this.route = new Route(this, b.getCoords(), b_pick); // Initialize route to target;
            this.buildingFound = true;
            this.burgleMapSave.add(b);
            break; // stop searching
          }
        }
      }

      if (this.buildingFound == false) {
        pickRandom(); // no previously burgled building exists in memory map for given jurisdiction
      }
    }
  }
Пример #26
0
 public static void trainModel(ActionBarActivity obj) throws IOException, ClassNotFoundException {
   ArrayList<Feature> features = Globals.getAllFeatures(obj);
   ArrayList<ArrayList<Double>> train = new ArrayList<ArrayList<Double>>();
   ArrayList<Double> temp;
   for (Feature f : features) {
     temp = new ArrayList<>();
     temp.add((double) f._classLabel);
     temp.addAll(f._features);
     train.add(temp);
   }
   for (Feature f : features) {
     temp = new ArrayList<>();
     temp.add((double) f._classLabel);
     temp.addAll(f._features);
     train.add(temp);
   }
   for (Feature f : features) {
     temp = new ArrayList<>();
     temp.add((double) f._classLabel);
     temp.addAll(f._features);
     train.add(temp);
   }
   for (Feature f : features) {
     temp = new ArrayList<>();
     temp.add((double) f._classLabel);
     temp.addAll(f._features);
     train.add(temp);
   }
   long seed = System.nanoTime();
   Collections.shuffle(train, new Random(seed));
   svmTrain(train);
   // Printing labels to check
   printModelLabels();
   writeModeltoFile(obj);
 }
Пример #27
0
 public void fillChest(Chest chest, int level) {
   ArrayList<ItemStack> unused = new ArrayList<ItemStack>();
   System.out.println("Unused is null: " + (unused == null));
   System.out.println("inventory is null: " + (inventory.get(level) == null));
   System.out.println("contents is null: " + (inventory.get(level).getContents() == null));
   Collections.addAll(unused, inventory.get(level).getContents());
   Collections.shuffle(unused);
   int min = minMap.get(level)[0],
       max = minMap.get(level)[1],
       itemsToGive = new Random().nextInt((max - min) + 1) + min;
   Inventory inventory = chest.getBlockInventory();
   inventory.clear();
   for (int i = 1; i <= itemsToGive; i++) {
     int nextSlot = -1;
     if (unused.isEmpty()) {
       chest.update(true);
       return;
     }
     while (nextSlot == -1) {
       nextSlot = new Random().nextInt(inventory.getSize());
       if (inventory.getItem(nextSlot) != null
           && inventory.getItem(nextSlot).getType() != Material.AIR) nextSlot = -1;
     }
     int item = new Random().nextInt(unused.size());
     inventory.setItem(nextSlot, unused.get(item));
     unused.remove(item);
   }
   chest.update(true);
 }
  private void spawnMob() {
    // TODO Check how many mobs are in the local area and don't spawn if > configurable amount

    @SuppressWarnings("unchecked")
    Iterator<EntityEggInfo> iterator = EntityList.entityEggs.values().iterator();
    List<Integer> ids = new ArrayList<Integer>();
    while (iterator.hasNext()) {
      EntityEggInfo entityegginfo = iterator.next();
      ids.add(entityegginfo.spawnedID);
    }
    // shuffle and pick from IDs
    Collections.shuffle(ids);
    int id = ids.get(0);
    Entity entity = null;
    entity = EntityList.createEntityByID(id, worldObj);

    if (entity != null && entity instanceof EntityLivingBase) {
      EntityLiving entityliving = (EntityLiving) entity;
      entity.setLocationAndAngles(
          xCoord + 2 + MathHelper.randomDoubleInRange(0, xLength - 3),
          yCoord + 1.0,
          zCoord + 2 + MathHelper.randomDoubleInRange(0, zLength - 3),
          net.minecraft.util.MathHelper.wrapAngleTo180_float(worldObj.rand.nextFloat() * 360.0f),
          0.0f);
      worldObj.spawnEntityInWorld(entity);
      entityliving.playLivingSound();
    }
  }
Пример #29
0
  @Test
  public void testCreateAndDropManyDatabases() throws Exception {
    List<String> createdDatabases = new ArrayList<>();
    InfoSchemaMetadataDictionary dictionary = new InfoSchemaMetadataDictionary();
    String namePrefix = "database_";
    final int NUM = 10;
    for (int i = 0; i < NUM; i++) {
      String databaseName = namePrefix + i;
      assertFalse(catalog.existDatabase(databaseName));
      catalog.createDatabase(databaseName, TajoConstants.DEFAULT_TABLESPACE_NAME);
      assertTrue(catalog.existDatabase(databaseName));
      createdDatabases.add(databaseName);
    }

    Collection<String> allDatabaseNames = catalog.getAllDatabaseNames();
    for (String databaseName : allDatabaseNames) {
      assertTrue(
          databaseName.equals(DEFAULT_DATABASE_NAME)
              || createdDatabases.contains(databaseName)
              || dictionary.isSystemDatabase(databaseName));
    }
    // additional ones are 'default' and 'system' databases.
    assertEquals(NUM + 2, allDatabaseNames.size());

    Collections.shuffle(createdDatabases);
    for (String tobeDropped : createdDatabases) {
      assertTrue(catalog.existDatabase(tobeDropped));
      catalog.dropDatabase(tobeDropped);
      assertFalse(catalog.existDatabase(tobeDropped));
    }
  }
Пример #30
0
  /**
   * On créé le paquet de cartes Kokus
   *
   * @return
   */
  public LinkedList<Kokus> initialisationPaquetKokus() {
    LinkedList<Kokus> llk = new LinkedList<Kokus>();

    for (Kokus k : this.hashKokus) {
      // 12 cartes kokus de 1 unité
      if (k.getNbkoku() == 1) {
        for (int i = 0; i < 12; i++) {
          llk.add(k);
        }
      }

      // 8 cartes kokus de 2 unités
      if (k.getNbkoku() == 2) {
        for (int i = 0; i < 8; i++) {
          llk.add(k);
        }
      }

      // 4 cartes kokus de 3 unités
      if (k.getNbkoku() == 3) {
        for (int i = 0; i < 4; i++) {
          llk.add(k);
        }
      }
    }
    Collections.shuffle(llk);

    return llk;
  }