Java Code Examples for java.util.Collections#rotate()

The following examples show how to use java.util.Collections#rotate() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cidrawing   File: ListUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Shift object in the list
 *
 * @param list   list
 * @param index  object index
 * @param offset offset value can be positive or negative.
 * @return new index of the object
 */
public static int shiftItem(List<?> list, int index, int offset) {
    if (offset == 0 || index < 0) {
        return 0;
    }
    if (offset > 0) {
        int end = index + offset + 1;
        if (end > list.size()) {
            end = list.size();
        }
        Collections.rotate(list.subList(index, end), -1);
        return end - 1;
    } else {
        int start = index + offset;
        if (start < 0) {
            start = 0;
        }
        Collections.rotate(list.subList(start, index + 1), 1);
        return start;
    }
}
 
Example 2
/**
 * Rotate the list of dimension specifiers until all dimensions with type annotations appear in
 * source order.
 * <p>
 * <p>javac reorders dimension specifiers in method declarations with mixed-array notation, which
 * means that any type annotations don't appear in source order.
 * <p>
 * <p>For example, the type of {@code int @A [] f() @B [] {}} is parsed as {@code @B [] @A []}.
 * <p>
 * <p>This doesn't handle cases with un-annotated dimension specifiers, so the formatting logic
 * checks the token stream to figure out which side of the method name they appear on.
 */
private static Iterable<List<AnnotationTree>> reorderBySourcePosition(
        Deque<List<AnnotationTree>> dims) {
    int lastAnnotation = -1;
    int lastPos = -1;
    int idx = 0;
    for (List<AnnotationTree> dim : dims) {
        if (!dim.isEmpty()) {
            int pos = ((JCTree) dim.get(0)).getStartPosition();
            if (pos < lastPos) {
                List<List<AnnotationTree>> list = new ArrayList<>(dims);
                Collections.rotate(list, -(lastAnnotation + 1));
                return list;
            }
            lastPos = pos;
            lastAnnotation = idx;
        }
        idx++;
    }
    return dims;
}
 
Example 3
/**
 * During upgrade, one server can be down, this is normal. Therefore we do a quick ping on the first server,
 * if it is not responding, we try the other servers first. False positive/negatives are not critical,
 * but will increase latency to some extent.
 */
private boolean queueFirstServerIfDown(List<URI> allServers) {
    if (allServers.size() < 2) {
        return false;
    }
    URI uri = allServers.get(0);
    HttpGet httpGet = new HttpGet(uri);

    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout((int) PING_REQUEST_TIMEOUT.toMillis())
            .setConnectionRequestTimeout((int) PING_REQUEST_TIMEOUT.toMillis())
            .setSocketTimeout((int) PING_REQUEST_TIMEOUT.toMillis()).build();
    httpGet.setConfig(config);

    try (CloseableHttpResponse response = client.execute(httpGet)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            return false;
        }

    } catch (IOException e) {
        // We ignore this, if server is restarting this might happen.
    }
    // Some error happened, move this server to the back. The other servers should be running.
    Collections.rotate(allServers, -1);
    return true;
}
 
Example 4
Source Project: OEE-Designer   File: SparkLineTileSkin.java    License: MIT License 5 votes vote down vote up
private void addData(final double VALUE) {
    if (dataList.isEmpty()) { for (int i = 0 ; i < noOfDatapoints ;i ++) { dataList.add(VALUE); } }
    if (dataList.size() <= noOfDatapoints) {
        Collections.rotate(dataList, -1);
        dataList.set((noOfDatapoints - 1), VALUE);
    } else {
        dataList.add(VALUE);
    }
    stdDeviation = Statistics.getStdDev(dataList);
}
 
Example 5
Source Project: tilesfx   File: GaugeSparkLineTileSkin.java    License: Apache License 2.0 5 votes vote down vote up
private void addData(final double VALUE) {
    if (dataList.isEmpty()) { for (int i = 0 ; i < noOfDatapoints ;i ++) { dataList.add(VALUE); } }
    if (dataList.size() <= noOfDatapoints) {
        Collections.rotate(dataList, -1);
        dataList.set((noOfDatapoints - 1), VALUE);
    } else {
        dataList.add(VALUE);
    }
    stdDeviation = Statistics.getStdDev(dataList);
}
 
Example 6
/**
 * @param sortByDate true to sort highlights by date false to sort them by position in the book
 */
public void SortAndAnimate(boolean sortByDate) {
    Highlight.sortByDate = sortByDate;
    for (int i = 1; i < highlightList.size(); i++) {
        int j = Math.abs(Collections.binarySearch(highlightList.subList(0, i), highlightList.get(i)) + 1);
        Collections.rotate(highlightList.subList(j, i + 1), j - i);
        notifyItemMoved(i, j);
    }
}
 
Example 7
Source Project: gemfirexd-oss   File: EdgeHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a round robin list of the given number of remote endpoints in the
 * specified distributed system, chosen from the given list.
 *
 * @throws HydraRuntimeException if there are not enough endpoints available.
 */
private static List getRoundRobinEndpoints(int numEndpoints, List endpoints,
                                           String distributedSystemName) {
  if (numEndpoints == PoolPrms.ALL_AVAILABLE && endpoints.size() == 0) {
    return new ArrayList(); // no endpoints available at this time
  }
  if (numEndpoints > endpoints.size()) {
    error(numEndpoints, endpoints, distributedSystemName);
  }
  // turn off product-level endpoint randomization
  CacheServerTestUtil.disableShufflingOfEndpoints();
  // stays off only through edge initialization

  // get the start index and rotate to it
  int startIndex = getRoundRobinStartIndex(endpoints.size(),
                                           distributedSystemName);
  Collections.rotate(endpoints, startIndex);
  if (Log.getLogWriter().fineEnabled()) {
    Log.getLogWriter().fine("Round robin endpoints: " + endpoints);
  }

  // select the endpoints
  List roundRobinEndpoints;
  if (numEndpoints == PoolPrms.ALL_AVAILABLE) {
    roundRobinEndpoints = endpoints;
  } else {
    roundRobinEndpoints = endpoints.subList(0, numEndpoints);
  }
  // get rid of java.util.RandomAccessSubList
  return new ArrayList(roundRobinEndpoints);
}
 
Example 8
public Boolean moveRowsUp(int from, int to) {
    if (from - 1 < 0) {
        return false;
    }
    to = to + 1;
    Collections.rotate(testSteps.subList(from - 1, to), -1);
    setSaved(false);
    return true;
}
 
Example 9
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 4 votes vote down vote up
public void next() {
  if (running) {
    // list.add(list.remove(0));
    Collections.rotate(list, 1);
  }
}
 
Example 10
private CodingMethod stressPopCoding(CodingMethod coding) {
    assert(stress != null);  // this method is only for testing
    // Don't turn it into a pop coding if it's already something special.
    if (!(coding instanceof Coding))  return coding;
    Coding valueCoding = ((Coding)coding).getValueCoding();
    Histogram hist = getValueHistogram();
    int fVlen = stressLen(hist.getTotalLength());
    if (fVlen == 0)  return coding;
    List<Integer> popvals = new ArrayList<>();
    if (stress.nextBoolean()) {
        // Build the population from the value list.
        Set<Integer> popset = new HashSet<>();
        for (int i = start; i < end; i++) {
            if (popset.add(values[i]))  popvals.add(values[i]);
        }
    } else {
        int[][] matrix = hist.getMatrix();
        for (int mrow = 0; mrow < matrix.length; mrow++) {
            int[] row = matrix[mrow];
            for (int mcol = 1; mcol < row.length; mcol++) {
                popvals.add(row[mcol]);
            }
        }
    }
    int reorder = stress.nextInt();
    if ((reorder & 7) <= 2) {
        // Lose the order.
        Collections.shuffle(popvals, stress);
    } else {
        // Keep the order, mostly.
        if (((reorder >>>= 3) & 7) <= 2)  Collections.sort(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.reverse(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.rotate(popvals, stressLen(popvals.size()));
    }
    if (popvals.size() > fVlen) {
        // Cut the list down.
        if (((reorder >>>= 3) & 7) <= 2) {
            // Cut at end.
            popvals.subList(fVlen,   popvals.size()).clear();
        } else {
            // Cut at start.
            popvals.subList(0, popvals.size()-fVlen).clear();
        }
    }
    fVlen = popvals.size();
    int[] fvals = new int[1+fVlen];
    for (int i = 0; i < fVlen; i++) {
        fvals[1+i] = (popvals.get(i)).intValue();
    }
    PopulationCoding pop = new PopulationCoding();
    pop.setFavoredValues(fvals, fVlen);
    int[] lvals = PopulationCoding.LValuesCoded;
    for (int i = 0; i < lvals.length / 2; i++) {
        int popl = lvals[stress.nextInt(lvals.length)];
        if (popl < 0)  continue;
        if (PopulationCoding.fitTokenCoding(fVlen, popl) != null) {
            pop.setL(popl);
            break;
        }
    }
    if (pop.tokenCoding == null) {
        int lmin = fvals[1], lmax = lmin;
        for (int i = 2; i <= fVlen; i++) {
            int val = fvals[i];
            if (lmin > val)  lmin = val;
            if (lmax < val)  lmax = val;
        }
        pop.tokenCoding = stressCoding(lmin, lmax);
    }

    computePopSizePrivate(pop, valueCoding, valueCoding);
    return pop;
}
 
Example 11
private CodingMethod stressPopCoding(CodingMethod coding) {
    assert(stress != null);  // this method is only for testing
    // Don't turn it into a pop coding if it's already something special.
    if (!(coding instanceof Coding))  return coding;
    Coding valueCoding = ((Coding)coding).getValueCoding();
    Histogram hist = getValueHistogram();
    int fVlen = stressLen(hist.getTotalLength());
    if (fVlen == 0)  return coding;
    List<Integer> popvals = new ArrayList<>();
    if (stress.nextBoolean()) {
        // Build the population from the value list.
        Set<Integer> popset = new HashSet<>();
        for (int i = start; i < end; i++) {
            if (popset.add(values[i]))  popvals.add(values[i]);
        }
    } else {
        int[][] matrix = hist.getMatrix();
        for (int mrow = 0; mrow < matrix.length; mrow++) {
            int[] row = matrix[mrow];
            for (int mcol = 1; mcol < row.length; mcol++) {
                popvals.add(row[mcol]);
            }
        }
    }
    int reorder = stress.nextInt();
    if ((reorder & 7) <= 2) {
        // Lose the order.
        Collections.shuffle(popvals, stress);
    } else {
        // Keep the order, mostly.
        if (((reorder >>>= 3) & 7) <= 2)  Collections.sort(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.reverse(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.rotate(popvals, stressLen(popvals.size()));
    }
    if (popvals.size() > fVlen) {
        // Cut the list down.
        if (((reorder >>>= 3) & 7) <= 2) {
            // Cut at end.
            popvals.subList(fVlen,   popvals.size()).clear();
        } else {
            // Cut at start.
            popvals.subList(0, popvals.size()-fVlen).clear();
        }
    }
    fVlen = popvals.size();
    int[] fvals = new int[1+fVlen];
    for (int i = 0; i < fVlen; i++) {
        fvals[1+i] = (popvals.get(i)).intValue();
    }
    PopulationCoding pop = new PopulationCoding();
    pop.setFavoredValues(fvals, fVlen);
    int[] lvals = PopulationCoding.LValuesCoded;
    for (int i = 0; i < lvals.length / 2; i++) {
        int popl = lvals[stress.nextInt(lvals.length)];
        if (popl < 0)  continue;
        if (PopulationCoding.fitTokenCoding(fVlen, popl) != null) {
            pop.setL(popl);
            break;
        }
    }
    if (pop.tokenCoding == null) {
        int lmin = fvals[1], lmax = lmin;
        for (int i = 2; i <= fVlen; i++) {
            int val = fvals[i];
            if (lmin > val)  lmin = val;
            if (lmax < val)  lmax = val;
        }
        pop.tokenCoding = stressCoding(lmin, lmax);
    }

    computePopSizePrivate(pop, valueCoding, valueCoding);
    return pop;
}
 
Example 12
private CodingMethod stressPopCoding(CodingMethod coding) {
    assert(stress != null);  // this method is only for testing
    // Don't turn it into a pop coding if it's already something special.
    if (!(coding instanceof Coding))  return coding;
    Coding valueCoding = ((Coding)coding).getValueCoding();
    Histogram hist = getValueHistogram();
    int fVlen = stressLen(hist.getTotalLength());
    if (fVlen == 0)  return coding;
    List<Integer> popvals = new ArrayList<>();
    if (stress.nextBoolean()) {
        // Build the population from the value list.
        Set<Integer> popset = new HashSet<>();
        for (int i = start; i < end; i++) {
            if (popset.add(values[i]))  popvals.add(values[i]);
        }
    } else {
        int[][] matrix = hist.getMatrix();
        for (int mrow = 0; mrow < matrix.length; mrow++) {
            int[] row = matrix[mrow];
            for (int mcol = 1; mcol < row.length; mcol++) {
                popvals.add(row[mcol]);
            }
        }
    }
    int reorder = stress.nextInt();
    if ((reorder & 7) <= 2) {
        // Lose the order.
        Collections.shuffle(popvals, stress);
    } else {
        // Keep the order, mostly.
        if (((reorder >>>= 3) & 7) <= 2)  Collections.sort(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.reverse(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.rotate(popvals, stressLen(popvals.size()));
    }
    if (popvals.size() > fVlen) {
        // Cut the list down.
        if (((reorder >>>= 3) & 7) <= 2) {
            // Cut at end.
            popvals.subList(fVlen,   popvals.size()).clear();
        } else {
            // Cut at start.
            popvals.subList(0, popvals.size()-fVlen).clear();
        }
    }
    fVlen = popvals.size();
    int[] fvals = new int[1+fVlen];
    for (int i = 0; i < fVlen; i++) {
        fvals[1+i] = (popvals.get(i)).intValue();
    }
    PopulationCoding pop = new PopulationCoding();
    pop.setFavoredValues(fvals, fVlen);
    int[] lvals = PopulationCoding.LValuesCoded;
    for (int i = 0; i < lvals.length / 2; i++) {
        int popl = lvals[stress.nextInt(lvals.length)];
        if (popl < 0)  continue;
        if (PopulationCoding.fitTokenCoding(fVlen, popl) != null) {
            pop.setL(popl);
            break;
        }
    }
    if (pop.tokenCoding == null) {
        int lmin = fvals[1], lmax = lmin;
        for (int i = 2; i <= fVlen; i++) {
            int val = fvals[i];
            if (lmin > val)  lmin = val;
            if (lmax < val)  lmax = val;
        }
        pop.tokenCoding = stressCoding(lmin, lmax);
    }

    computePopSizePrivate(pop, valueCoding, valueCoding);
    return pop;
}
 
Example 13
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 4 votes vote down vote up
public void next() {
  if (running) {
    // list.add(list.remove(0));
    Collections.rotate(list, 1);
  }
}
 
Example 14
private CodingMethod stressPopCoding(CodingMethod coding) {
    assert(stress != null);  // this method is only for testing
    // Don't turn it into a pop coding if it's already something special.
    if (!(coding instanceof Coding))  return coding;
    Coding valueCoding = ((Coding)coding).getValueCoding();
    Histogram hist = getValueHistogram();
    int fVlen = stressLen(hist.getTotalLength());
    if (fVlen == 0)  return coding;
    List<Integer> popvals = new ArrayList<>();
    if (stress.nextBoolean()) {
        // Build the population from the value list.
        Set<Integer> popset = new HashSet<>();
        for (int i = start; i < end; i++) {
            if (popset.add(values[i]))  popvals.add(values[i]);
        }
    } else {
        int[][] matrix = hist.getMatrix();
        for (int mrow = 0; mrow < matrix.length; mrow++) {
            int[] row = matrix[mrow];
            for (int mcol = 1; mcol < row.length; mcol++) {
                popvals.add(row[mcol]);
            }
        }
    }
    int reorder = stress.nextInt();
    if ((reorder & 7) <= 2) {
        // Lose the order.
        Collections.shuffle(popvals, stress);
    } else {
        // Keep the order, mostly.
        if (((reorder >>>= 3) & 7) <= 2)  Collections.sort(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.reverse(popvals);
        if (((reorder >>>= 3) & 7) <= 2)  Collections.rotate(popvals, stressLen(popvals.size()));
    }
    if (popvals.size() > fVlen) {
        // Cut the list down.
        if (((reorder >>>= 3) & 7) <= 2) {
            // Cut at end.
            popvals.subList(fVlen,   popvals.size()).clear();
        } else {
            // Cut at start.
            popvals.subList(0, popvals.size()-fVlen).clear();
        }
    }
    fVlen = popvals.size();
    int[] fvals = new int[1+fVlen];
    for (int i = 0; i < fVlen; i++) {
        fvals[1+i] = (popvals.get(i)).intValue();
    }
    PopulationCoding pop = new PopulationCoding();
    pop.setFavoredValues(fvals, fVlen);
    int[] lvals = PopulationCoding.LValuesCoded;
    for (int i = 0; i < lvals.length / 2; i++) {
        int popl = lvals[stress.nextInt(lvals.length)];
        if (popl < 0)  continue;
        if (PopulationCoding.fitTokenCoding(fVlen, popl) != null) {
            pop.setL(popl);
            break;
        }
    }
    if (pop.tokenCoding == null) {
        int lmin = fvals[1], lmax = lmin;
        for (int i = 2; i <= fVlen; i++) {
            int val = fvals[i];
            if (lmin > val)  lmin = val;
            if (lmax < val)  lmax = val;
        }
        pop.tokenCoding = stressCoding(lmin, lmax);
    }

    computePopSizePrivate(pop, valueCoding, valueCoding);
    return pop;
}
 
Example 15
Source Project: openjdk-systemtest   File: SolverTest.java    License: Apache License 2.0 4 votes vote down vote up
private void quietRotate() { //Doesn't return, and doesn't update the rotation counter. Use this for the pre-caching, as initial rotation is arbitrary.
	Collections.rotate(contents,1);
}
 
Example 16
Source Project: j2objc   File: CollectionsTest.java    License: Apache License 2.0 4 votes vote down vote up
private void testRotate(List list, String type) {
    // rotate with positive distance
    Collections.rotate(list, 7);
    assertEquals("Test1: rotate modified the " + type
            + " list incorrectly,", "3456789012", getString(list));

    // rotate with negative distance
    Collections.rotate(list, -2);
    assertEquals("Test2: rotate modified the " + type
            + " list incorrectly,", "5678901234", getString(list));

    // rotate sublist with negative distance
    List subList = list.subList(1, 5);
    Collections.rotate(subList, -1);
    assertEquals("Test3: rotate modified the " + type
            + " list incorrectly,", "5789601234", getString(list));

    // rotate sublist with positive distance
    Collections.rotate(subList, 2);
    assertEquals("Test4: rotate modified the " + type
            + " list incorrectly,", "5967801234", getString(list));

    // rotate with positive distance that is larger than list size
    Collections.rotate(list, 23);
    assertEquals("Test5: rotate modified the " + type
            + " list incorrectly,", "2345967801", getString(list));

    // rotate with negative distance that is larger than list size
    Collections.rotate(list, -23);
    assertEquals("Test6: rotate modified the " + type
            + " list incorrectly,", "5967801234", getString(list));

    // rotate with 0 and equivalent distances, this should make no
    // modifications to the list
    Collections.rotate(list, 0);
    assertEquals("Test7: rotate modified the " + type
            + " list incorrectly,", "5967801234", getString(list));

    Collections.rotate(list, -30);
    assertEquals("Test8: rotate modified the " + type
            + " list incorrectly,", "5967801234", getString(list));

    Collections.rotate(list, 30);
    assertEquals("Test9: rotate modified the " + type
            + " list incorrectly,", "5967801234", getString(list));
}
 
Example 17
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
    throws DimensionMismatchException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1 = new ArrayList<T>(length);
    final List<T> child2 = new ArrayList<T>(length);
    // sets of already inserted items for quick access
    final Set<T> child1Set = new HashSet<T>(length);
    final Set<T> child2Set = new HashSet<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();
    // choose random points, making sure that lb < ub.
    int a = random.nextInt(length);
    int b;
    do {
        b = random.nextInt(length);
    } while (a == b);
    // determine the lower and upper bounds
    final int lb = FastMath.min(a, b);
    final int ub = FastMath.max(a, b);

    // add the subLists that are between lb and ub
    child1.addAll(parent1Rep.subList(lb, ub + 1));
    child1Set.addAll(child1);
    child2.addAll(parent2Rep.subList(lb, ub + 1));
    child2Set.addAll(child2);

    // iterate over every item in the parents
    for (int i = 1; i <= length; i++) {
        final int idx = (ub + i) % length;

        // retrieve the current item in each parent
        final T item1 = parent1Rep.get(idx);
        final T item2 = parent2Rep.get(idx);

        // if the first child already contains the item in the second parent add it
        if (!child1Set.contains(item2)) {
            child1.add(item2);
            child1Set.add(item2);
        }

        // if the second child already contains the item in the first parent add it
        if (!child2Set.contains(item1)) {
            child2.add(item1);
            child2Set.add(item1);
        }
    }

    // rotate so that the original slice is in the same place as in the parents.
    Collections.rotate(child1, lb);
    Collections.rotate(child2, lb);

    return new ChromosomePair(first.newFixedLengthChromosome(child1),
                              second.newFixedLengthChromosome(child2));
}
 
Example 18
Source Project: gemfirexd-oss   File: EdgeHelper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a round robin list of the given number of endpoints in the
 * specified distributed system for bridge servers that are in the same
 * WAN site as the invoking VM, chosen from the servers that have registered
 * endpoints via {@link BridgeHelper}.
 * <p>
 * If the number of endpoints is {@link PoolPrms#ALL_AVAILABLE}, then all
 * matching endpoints in the distributed system are included, in round robin
 * order.  If the distributed system is null, endpoints are chosen without
 * regard to their distributed system.
 * <p>
 * The first client to ask for endpoints gets the endpoints in the order they
 * are returned from the underlying blackboard.  The second client gets the
 * endpoints in order starting from the second endpoint and wrapping around
 * if needed.  The starting endpoint continues to rotate.
 * <p>
 * This is a suitable {@link PoolPrms#contactAlgorithm} for hierarchical
 * cache tests that use <codehydraconfig/topology_wan_hct.inc</code>. 
 * 
 * @throws HydraRuntimeException if there are not enough endpoints available.
 */
public static List getRoundRobinEndpointsInWanHctSite(int numEndpoints,
                                              String distributedSystemName) {
  // get all available endpoints
  List allEndpoints = getAllEndpoints(distributedSystemName);

  // get the endpoints in this WAN site
  int wanSite = toWanSite(RemoteTestModule.getMyClientName());
  List endpoints = getAllEndpointsInWanHctSite(wanSite, numEndpoints,
                                       allEndpoints, distributedSystemName);
  if (numEndpoints == PoolPrms.ALL_AVAILABLE && endpoints.size() == 0) {
    return new ArrayList(); // no endpoints available at this time
  }
  
  // turn off product-level endpoint randomization
  CacheServerTestUtil.disableShufflingOfEndpoints();
  // stays off only through edge initialization
             
  // get the start index and rotate to it
  SharedCounters sc = EdgeBlackboard.getInstance().getSharedCounters();
  long tmp = -1;
  switch (wanSite) {
    case 1:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex1); break;
    case 2:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex2); break;
    case 3:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex3); break;
    case 4:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex4); break;
    case 5:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex5); break;
    case 6:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex6); break;
    case 7:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex7); break;
    case 8:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex8); break;
    case 9:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex9); break;
    case 10:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex10); break;
    case 11:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex11); break;
    case 12:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex12); break;
    case 13:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex13); break;
    case 14:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex14); break;
    case 15:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex15); break;
    case 16:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex16); break;
    case 17:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex17); break;
    case 18:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex18); break;
    case 19:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex19); break;
    case 20:  tmp = sc.incrementAndRead(EdgeBlackboard.startIndex20); break;
    default: String s = "Too many WAN sites: " + wanSite;
             throw new UnsupportedOperationException(s);
  } 
  int startIndex = (int)tmp % endpoints.size();
  Collections.rotate(endpoints, startIndex);
  if (Log.getLogWriter().fineEnabled()) {
    Log.getLogWriter().fine("Round robin endpoints for WAN site " + wanSite
                           + ": " + endpoints);
  }

  // select the endpoints
  List roundRobinEndpoints;
  if (numEndpoints == PoolPrms.ALL_AVAILABLE) {
    roundRobinEndpoints = endpoints;
  } else {
    roundRobinEndpoints = endpoints.subList(0, numEndpoints);
  }
  // get rid of java.util.RandomAccessSubList
  return new ArrayList(roundRobinEndpoints);
}
 
Example 19
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
    throws DimensionMismatchException {

    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1 = new ArrayList<T>(length);
    final List<T> child2 = new ArrayList<T>(length);
    // sets of already inserted items for quick access
    final Set<T> child1Set = new HashSet<T>(length);
    final Set<T> child2Set = new HashSet<T>(length);

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();
    // choose random points, making sure that lb < ub.
    int a = random.nextInt(length);
    int b;
    do {
        b = random.nextInt(length);
    } while (a == b);
    // determine the lower and upper bounds
    final int lb = FastMath.min(a, b);
    final int ub = FastMath.max(a, b);

    // add the subLists that are between lb and ub
    child1.addAll(parent1Rep.subList(lb, ub + 1));
    child1Set.addAll(child1);
    child2.addAll(parent2Rep.subList(lb, ub + 1));
    child2Set.addAll(child2);

    // iterate over every item in the parents
    for (int i = 1; i <= length; i++) {
        final int idx = (ub + i) % length;

        // retrieve the current item in each parent
        final T item1 = parent1Rep.get(idx);
        final T item2 = parent2Rep.get(idx);

        // if the first child already contains the item in the second parent add it
        if (!child1Set.contains(item2)) {
            child1.add(item2);
            child1Set.add(item2);
        }

        // if the second child already contains the item in the first parent add it
        if (!child2Set.contains(item1)) {
            child2.add(item1);
            child2Set.add(item1);
        }
    }

    // rotate so that the original slice is in the same place as in the parents.
    Collections.rotate(child1, lb);
    Collections.rotate(child2, lb);

    return new ChromosomePair(first.newFixedLengthChromosome(child1),
                              second.newFixedLengthChromosome(child2));
}
 
Example 20
Source Project: Equate   File: UnitType.java    License: GNU General Public License v3.0 2 votes vote down vote up
/**
 * Rotates the units in the display order such that the unit at toIndex - 1
 * now has position fromIndex, the unit at fromIndex has position fromIndex +
 * 1, etc.
 *
 * @param fromIndex is inclusive
 * @param toIndex   is exclusive
 */
public void rotateUnitSublist(int fromIndex, int toIndex) {
	Collections.rotate(mUnitDisplayOrder.subList(fromIndex, toIndex), 1);
}