Example usage for java.util Collections shuffle

List of usage examples for java.util Collections shuffle

Introduction

In this page you can find the example usage for java.util Collections shuffle.

Prototype

public static void shuffle(List<?> list) 

Source Link

Document

Randomly permutes the specified list using a default source of randomness.

Usage

From source file:net.sf.asap.PlayerService.java

private void setPlaylist(final Uri uri, boolean shuffle) {
    playlist.clear();//from  w ww  .  j a va  2 s  .com
    FileContainer container = new FileContainer() {
        @Override
        protected void onSongFile(String name, InputStream is) {
            playlist.add(Util.buildUri(uri, name));
        }
    };
    try {
        container.list(uri, false, true);
        if (shuffle)
            Collections.shuffle(playlist);
        else if (!Util.isM3u(uri))
            Collections.sort(playlist);
    } catch (IOException ex) {
        // playlist is not essential
    }
}

From source file:edu.ucuenca.authorsrelatedness.Distance.java

public List<String> TopT(List<String> m, int n) throws IOException, SQLException {
    n = (n <= 0) ? 1 : n;//from  w w  w  . ja v  a  2s.c om
    if (m.size() == 1) {
        m.add(m.get(0));
    }
    if (Cache.getInstance().config.get("stochastic").getAsBoolean().value()) {
        Collections.shuffle(m);
        if (2 * n < m.size()) {
            m = m.subList(0, 2 * n);
        }
    }
    Map<String, Double> Mapa = new HashMap();
    for (int i = 0; i < m.size(); i++) {
        for (int j = i + 1; j < m.size(); j++) {
            double v = NGD(m.get(i), m.get(j));
            System.out.println(m.get(i) + "," + m.get(j) + "=" + v);

            if (Mapa.containsKey(m.get(i))) {
                Mapa.put(m.get(i), Mapa.get(m.get(i)) + v);
            } else {
                Mapa.put(m.get(i), v);
            }

            if (Mapa.containsKey(m.get(j))) {
                Mapa.put(m.get(j), Mapa.get(m.get(j)) + v);
            } else {
                Mapa.put(m.get(j), v);
            }
        }
    }
    Map<String, Double> sortByValue = sortByValue(Mapa);
    List<String> ls = new ArrayList<>();
    ArrayList<String> arrayList = new ArrayList(sortByValue.keySet());
    ArrayList<Double> arrayList2 = new ArrayList(sortByValue.values());
    for (int i = 0; i < n; i++) {
        if (i < sortByValue.size()) {
            ls.add(arrayList.get(i));
        }
    }
    return ls;
}

From source file:fr.exanpe.t5.lib.components.SecurePassword.java

@SetupRender
void init() {// ww w  . j a  va2s  . c om
    uniqueId = javaScriptSupport.allocateClientId(resources);

    // Build the positionning list, to position items on the grid
    positionning = new LinkedList<String>(Arrays.asList(characters.split("")));
    positionning.remove(0);

    int gridNumber = gridWidth * gridHeight;

    for (int i = characters.length(); i < gridNumber; i++)
        positionning.add("");

    Collections.shuffle(positionning);

    // Build a dummy list to iterate over
    dummyRowList = new ArrayList<String>(gridHeight);
    for (int i = 0; i < gridHeight; ++i)
        dummyRowList.add("");

    dummyColumnList = new ArrayList<String>(gridWidth);
    for (int i = 0; i < gridWidth; ++i)
        dummyColumnList.add("");

    positionningMap = new HashMap<String, String>();
}

From source file:com.tealcube.minecraft.bukkit.mythicdrops.utils.TierUtil.java

public static Tier randomTierWithChance(Map<Tier, Double> chanceMap) {
    Validate.notNull(chanceMap, "Map<Tier, Double> cannot be null");
    double totalWeight = 0;
    List<Tier> keys = new ArrayList<>(chanceMap.keySet());
    Collections.shuffle(keys);
    for (Tier t : keys) {
        totalWeight += chanceMap.get(t);
    }/*w ww .  ja  v a  2s.c  om*/

    double chosenWeight = MythicDropsPlugin.getInstance().getRandom().nextDouble() * totalWeight;

    double currentWeight = 0;

    for (Tier t : keys) {
        currentWeight += chanceMap.get(t);

        if (currentWeight >= chosenWeight) {
            return t;
        }
    }
    return null;
}

From source file:com.ibm.bluej.commonutil.PrecisionRecallThreshold.java

private static String stringPRCurve(ArrayList<Pair<Double, Boolean>> pr, double total, int buckets) {
    StringBuffer buf = new StringBuffer();
    Collections.shuffle(pr);
    Collections.sort(pr, new FirstPairComparator(null));
    Collections.reverse(pr);//  w w w  .  j av  a2  s .  c o m
    double[] correct = new double[buckets];
    double[] answered = new double[buckets];
    double[] thresholds = new double[buckets];
    int bucketNdx = 0;
    double cummulativeCorrect = 0;
    double auc = 0;
    double allPositive = 0;
    for (Pair<Double, Boolean> p : pr) {
        if (p.second)
            allPositive += 1;
    }

    double maxF = 0;
    for (int i = 0; i < pr.size(); ++i) {
        if (i >= (1 + bucketNdx) * pr.size() / buckets && bucketNdx < buckets - 1) {
            thresholds[bucketNdx] = pr.get(i).first;
            ++bucketNdx;
        }
        for (int j = bucketNdx; j < buckets; ++j) {
            ++answered[j];
            if (pr.get(i).second) {
                ++correct[j];
            }
        }
        if (pr.get(i).second) {
            ++cummulativeCorrect;
            auc += cummulativeCorrect / ((i + 1) * allPositive);
        }

        double tp = cummulativeCorrect;
        double fp = (i + 1) - cummulativeCorrect;
        double fn = allPositive - cummulativeCorrect;
        double precision = (double) (tp) / (tp + fp);
        double recall = (double) (tp) / (tp + fn);
        double f1 = 2 * precision * recall / (precision + recall);
        if (f1 > maxF)
            maxF = f1;
    }

    for (int i = 0; i < buckets; ++i) {
        double precision = correct[i] / answered[i];
        double recall = correct[i] / total;
        double FScore = 2 * precision * recall / (precision + recall);
        buf.append(
                "P = " + Lang.dblStr(precision) + " R = " + Lang.dblStr(recall) + " F = " + Lang.dblStr(FScore)
                        + " (C = " + (int) answered[i] + " T = " + Lang.dblStr(thresholds[i]) + ")" + "\n");
    }
    buf.append("AUC = " + auc + "\n"); //not sure if computed correctly
    buf.append("Max F-Score = " + maxF + "\n");
    return buf.toString();
}

From source file:br.com.autonomiccs.autonomic.plugin.common.services.AutonomiccsSystemVmDeploymentService.java

/**
 * This method looks for a host in the whole cloud environment to deploy an Autonomiccs system VM.
 * It loads all zones of the environment, and then it randomizes the list and tries to look for suitable hosts using {@link #searchForRandomHostInZoneToDeployAutonomiccsSystemVm(DataCenterVO)}
 *
 * @return {@link HostVO} to deploy the system VM, it can also return null if no suitable hosts were found.
 *///from www  .j a  va  2s  . c  om
public HostVO searchForRandomHostInCloudToDeployAutonomiccsSystemVm() {
    List<DataCenterVO> allZonesEnabled = zoneService.listAllZonesEnabled();
    Collections.shuffle(allZonesEnabled);
    for (DataCenterVO dataCenterVO : allZonesEnabled) {
        HostVO host = searchForRandomHostInZoneToDeployAutonomiccsSystemVm(dataCenterVO);
        if (host != null) {
            return host;
        }
    }
    logger.info("Could not find any suitable hosts to deploy the system VM into Cloud environment");
    return null;
}

From source file:fr.ritaly.dungeonmaster.champion.body.Body.java

/**
 * Tries to wound this body and returns whether the operation succeeded.
 *
 * @return whether at least one body part was wounded.
 *///from w  ww. jav  a2s . co m
public boolean wound() {
    if (log.isDebugEnabled()) {
        log.debug("Wounding " + getChampion().getName() + "'s body ...");
    }

    // TODO Strength of wounds ? Number of wounds ?
    final List<BodyPart> bodyParts = getNonWoundedParts();

    if (!bodyParts.isEmpty()) {
        // Randomly wound one of the non-wounded body parts
        Collections.shuffle(bodyParts);

        boolean wounded = false;

        while (!bodyParts.isEmpty() && !wounded) {
            wounded = bodyParts.remove(0).wound();
        }

        return wounded;
    }

    return false;
}

From source file:com.wso2telco.dep.mediator.impl.smsmessaging.northbound.RetrieveSMSNorthboundHandler.java

@Override
public boolean handle(MessageContext context) throws CustomException, AxisFault, Exception {

    SOAPBody body = context.getEnvelope().getBody();
    Gson gson = new GsonBuilder().serializeNulls().create();

    String reqType = "retrive_sms";
    String requestid = UID.getUniqueID(Type.SMSRETRIVE.getCode(), context, executor.getApplicationid());

    int batchSize = 100;

    JSONObject jsonBody = executor.getJsonBody();
    NorthboundRetrieveRequest nbRetrieveRequest = gson.fromJson(jsonBody.toString(),
            NorthboundRetrieveRequest.class);
    log.info(// ww w .j  av a  2 s  .  c  o  m
            "-------------------------------------- Retrieve messages sent to your Web application --------------------------------------"
                    + " Request ID: " + UID.getRequestID(context));
    log.info("Retrieve northbound request body : " + gson.toJson(nbRetrieveRequest) + " Request ID: "
            + UID.getRequestID(context));

    List<OperatorEndpoint> endpoints = occi.getAPIEndpointsByApp(API_TYPE, executor.getSubResourcePath(),
            executor.getValidoperators());

    List<OperatorEndpoint> validEndpoints = new ArrayList<OperatorEndpoint>();
    Registrations[] registrations = nbRetrieveRequest.getInboundSMSMessages().getRegistrations();

    if (nbRetrieveRequest.getInboundSMSMessages().getMaxBatchSize() != null) {
        String requestBodyBatchSize = nbRetrieveRequest.getInboundSMSMessages().getMaxBatchSize();

        if (!requestBodyBatchSize.equals("")) {
            if (Integer.parseInt(requestBodyBatchSize) < 100) {
                batchSize = Integer.parseInt(requestBodyBatchSize);
            }
        }
    }

    for (OperatorEndpoint operatorEndpoint : endpoints) {

        for (int i = 0; i < registrations.length; i++) {
            if (registrations[i].getOperatorCode().equalsIgnoreCase(operatorEndpoint.getOperator())) {
                validEndpoints.add(operatorEndpoint);
                break;
            }
        }
    }

    log.info("Endpoints size: " + validEndpoints.size());

    Collections.shuffle(validEndpoints);
    int perOpCoLimit = batchSize / (validEndpoints.size());

    log.info("Per OpCo limit :" + perOpCoLimit);

    List<InboundSMSMessage> inboundSMSMessageList = new ArrayList<InboundSMSMessage>();

    int execCount = 0;
    int forLoopCount = 0;
    boolean retryFlag = true;
    FileReader fileReader = new FileReader();
    String file = CarbonUtils.getCarbonConfigDirPath() + File.separator
            + FileNames.MEDIATOR_CONF_FILE.getFileName();
    Map<String, String> mediatorConfMap = fileReader.readPropertyFile(file);
    Boolean retry = false;
    retry = Boolean.valueOf(mediatorConfMap.get("retry_on_fail"));
    Integer retryCount = Integer.valueOf(mediatorConfMap.get("retry_count"));

    ArrayList<String> responses = new ArrayList<String>();
    while ((inboundSMSMessageList.size() < batchSize) && (retryFlag == true)) {
        execCount++;
        log.info("NB aEndpoint : " + endpoints.size());

        for (int i = 0; i < validEndpoints.size(); i++) {
            forLoopCount++;
            log.info("NB forLoopCount : " + forLoopCount);
            OperatorEndpoint aEndpoint = validEndpoints.remove(0);
            log.info("NB aEndpoint : " + aEndpoint.getEndpointref().getAddress());
            validEndpoints.add(aEndpoint);
            String url = aEndpoint.getEndpointref().getAddress();
            String getRequestURL = null;
            String criteria = null;
            String operatorCode = null;

            for (int r = 0; r < registrations.length; r++) {
                if (registrations[r].getOperatorCode().equalsIgnoreCase(aEndpoint.getOperator())) {
                    /* create request url for southbound operators */
                    if (registrations[r].getCriteria() != null) {
                        criteria = registrations[r].getCriteria();
                    }

                    if (criteria == null || criteria.equals("")) {
                        operatorCode = registrations[r].getOperatorCode();
                        log.info("Operator RetrieveSMSHandler" + operatorCode);
                        getRequestURL = "/" + registrations[r].getRegistrationID() + "/messages?maxBatchSize="
                                + batchSize;
                        url = url.replace("/messages", getRequestURL);
                        log.info("Invoke RetrieveSMSHandler of plugin");
                    } else {
                        operatorCode = registrations[r].getOperatorCode();
                        log.info("Operator RetrieveSMSHandler" + operatorCode);
                        getRequestURL = "/" + registrations[r].getRegistrationID() + "/" + criteria
                                + "/messages?maxBatchSize=" + batchSize;
                        url = url.replace("/messages", getRequestURL);
                        log.info("Invoke SBRetrieveSMSHandler of plugin");
                    }

                    break;
                }

            }

            APICall ac = apiUtil.setBatchSize(url, body.toString(), reqType, perOpCoLimit);//check if request json body incorrect
            JSONObject obj = ac.getBody();
            String retStr = null;
            log.info("Retrieving messages of operator: " + aEndpoint.getOperator());

            context.setDoingGET(true);
            if (context.isDoingGET()) {
                log.info("Doing makeGetRequest");
                retStr = executor.makeRetrieveSMSGetRequest(aEndpoint, ac.getUri(), null, true, context, false);
            } else {
                log.info("Doing makeRequest");
                retStr = executor.makeRequest(aEndpoint, ac.getUri(), obj.toString(), true, context, false);
            }

            log.info("Retrieved messages of " + aEndpoint.getOperator() + " operator: " + retStr
                    + " Request ID: " + UID.getRequestID(context));

            /* add criteria and operatorCode to the southbound response */
            NorthboundRetrieveResponse sbRetrieveResponse = gson.fromJson(retStr,
                    NorthboundRetrieveResponse.class);

            if (sbRetrieveResponse != null && sbRetrieveResponse.getInboundSMSMessageList() != null) {
                if (sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage() != null
                        && sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage().length != 0) {
                    InboundSMSMessage[] inboundSMSMessageResponses = sbRetrieveResponse
                            .getInboundSMSMessageList().getInboundSMSMessage();
                    log.info("001 SECTION");
                    for (int t = 0; t < inboundSMSMessageResponses.length; t++) {
                        inboundSMSMessageResponses[t].setCriteria(criteria);
                        inboundSMSMessageResponses[t].setOperatorCode(operatorCode);
                        inboundSMSMessageList.add(inboundSMSMessageResponses[t]);
                    }
                    sbRetrieveResponse.getInboundSMSMessageList()
                            .setInboundSMSMessage(inboundSMSMessageResponses);
                    responses.add(gson.toJson(sbRetrieveResponse));

                } else {
                    log.info("002 SECTION");
                    InboundSMSMessage[] inboundSMSMessageResponses = new InboundSMSMessage[0];
                    InboundSMSMessageList inboundSMSMessageListN = new InboundSMSMessageList();
                    inboundSMSMessageListN.setInboundSMSMessage(inboundSMSMessageResponses);
                    inboundSMSMessageListN.setNumberOfMessagesInThisBatch("0");
                    inboundSMSMessageListN.setResourceURL("Not Available");
                    inboundSMSMessageListN.setTotalNumberOfPendingMessages("0");
                    sbRetrieveResponse.setInboundSMSMessageList(inboundSMSMessageListN);

                    for (int k = 0; k < inboundSMSMessageResponses.length; k++) {
                        inboundSMSMessageResponses[k].setCriteria(criteria);
                        inboundSMSMessageResponses[k].setOperatorCode(operatorCode);
                        inboundSMSMessageList.add(inboundSMSMessageResponses[k]);
                    }
                    sbRetrieveResponse.getInboundSMSMessageList()
                            .setInboundSMSMessage(inboundSMSMessageResponses);
                    responses.add(gson.toJson(sbRetrieveResponse));
                }
            }

            if (inboundSMSMessageList.size() >= batchSize) {
                break;
            }
        }

        log.info("Final value of count :" + execCount);
        log.info("Results length of retrieve messages: " + inboundSMSMessageList.size());

        if (retry == false) {
            retryFlag = false;
            log.info("11 Final value of retryFlag :" + retryFlag);
        }

        if (execCount >= retryCount) {
            retryFlag = false;
            log.info("22 Final value of retryFlag :" + retryFlag);
        }
    }

    JSONObject paylodObject = apiUtil.generateResponse(context, reqType, inboundSMSMessageList, responses,
            requestid);
    String strjsonBody = paylodObject.toString();

    /* create northbound response. add clientCorrelator and resourceURL */
    NorthboundRetrieveResponse nbRetrieveResponse = gson.fromJson(strjsonBody,
            NorthboundRetrieveResponse.class);
    nbRetrieveResponse.getInboundSMSMessageList()
            .setClientCorrelator(nbRetrieveRequest.getInboundSMSMessages().getClientCorrelator());
    String resourceURL = nbRetrieveResponse.getInboundSMSMessageList().getResourceURL();
    InboundSMSMessage[] inboundSMSMessageResponses = nbRetrieveResponse.getInboundSMSMessageList()
            .getInboundSMSMessage();
    for (int q = 0; q < inboundSMSMessageResponses.length; q++) {
        String operatorCode = inboundSMSMessageResponses[q].getOperatorCode();
        String sestinationAddress = inboundSMSMessageResponses[q].getDestinationAddress();
        String messageId = inboundSMSMessageResponses[q].getMessageId();
        String inResourceURL = resourceURL.replace("registrations/",
                "registrations/" + operatorCode + "/" + sestinationAddress + "/") + "/" + messageId;
        inboundSMSMessageResponses[q].setResourceURL(inResourceURL);
    }
    nbRetrieveResponse.getInboundSMSMessageList().setInboundSMSMessage(inboundSMSMessageResponses);

    executor.removeHeaders(context);
    executor.setResponse(context, gson.toJson(nbRetrieveResponse));
    ((Axis2MessageContext) context).getAxis2MessageContext().setProperty("messageType", "application/json");

    return true;
}

From source file:com.intuit.tank.harness.functions.JexlStringFunctions.java

/**
 * @param minId/*from ww w.j  a v  a 2  s.c  om*/
 * @param maxId
 * @return
 */
private synchronized Stack<Integer> getStack(Integer minId, Integer maxId) {
    String key = getStackKey(minId, maxId);
    Stack<Integer> stack = stackMap.get(key);
    if (stack == null) {
        int blockSize = (maxId - minId) / APITestHarness.getInstance().getAgentRunData().getTotalAgents();
        int offset = APITestHarness.getInstance().getAgentRunData().getAgentInstanceNum() * blockSize;
        LOG.info(LogUtil.getLogMessage(
                "Creating userId Block starting at " + offset + " and containing  " + blockSize + " entries.",
                LogEventType.System));
        List<Integer> list = new ArrayList<Integer>();

        for (int i = 0; i < blockSize; i++) {
            int nextNum = i + minId + offset;
            list.add(nextNum);
        }
        Collections.shuffle(list);
        // Collections.reverse(list);
        stack = new Stack<Integer>();
        stack.addAll(list);
        stackMap.put(key, stack);
    }
    return stack;
}

From source file:fi.hsl.parkandride.core.service.PredictionService.java

private List<Long> findPredictorsNeedingUpdate() {
    List<Long> predictorIds = predictorRepository.findPredictorsNeedingUpdate();
    Collections.shuffle(predictorIds); // distribute the load over all servers
    return predictorIds;
}