Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:lab.example.service.LotteryService.java

public void run(String... args) {

    try {/*from  w  ww. ja  v a 2 s.c om*/
        while (true) {
            final UUID uuid = UUID.randomUUID();

            final Integer randomPrice = 1 + (int) (Math.random() * 36);

            Lot lot = new Lot(uuid.toString(), randomPrice);

            stockSave(lot);

            Thread.sleep(10 * 1000);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:com.c123.billbuddy.client.PaymentFeeder.java

@Transactional
public void createPayment() {

    Random random = new Random();

    int userId = (int) (userCount * random.nextDouble());
    user = gigaSpace.readById(User.class, new Integer(userId));

    int merchantId = (int) (merchantCount * random.nextDouble());
    merchant = gigaSpace.readById(Merchant.class, new Integer(merchantId));

    if (user != null && merchant != null) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        Date date = calendar.getTime();

        Double paymentAmount = Double.valueOf(Math.random() * 100);
        paymentAmount = Math.round(paymentAmount * 100.0) / 100.0;

        // Check If user valid and have credit limit
        if (user.getStatus() != AccountStatus.ACTIVE) {
            log.info("User: " + user.getName() + " status is " + user.getStatus());
        } else if (user.getBalance() - paymentAmount < user.getCreditLimit()) {
            log.info("User: " + user.getName() + " doesn't have credit.");

            Double addUserBalance = Double.valueOf(Math.random() * 1000);
            addUserBalance = Math.round(addUserBalance * 100.0) / 100.0;

            log.info("Add " + addUserBalance + " to user balance");

            user.setBalance(user.getBalance() + addUserBalance);
            gigaSpace.write(user);//from w  w  w .j  a va  2  s .  co  m

        } else {

            // Withdraw payment amount from user account
            updateUserBalance(user, paymentAmount);

            // Deposit payment amount to merchant account                    
            updateMerchantReceipts(merchant, paymentAmount);

            // Create a Payment POJO and set it up.  
            Payment payment = new Payment();

            payment.setPayingAccountId(user.getUserAccountId());
            payment.setReceivingMerchantId(merchant.getMerchantAccountId());
            payment.setDescription(merchant.getCategory().name());
            payment.setCreatedDate(date);
            payment.setPaymentAmount(Double.valueOf(Math.random() * 100));
            payment.setPaymentAmount(Math.round(paymentAmount * 100.0) / 100.0);
            payment.setStatus(TransactionStatus.NEW);

            // Write the payment object
            gigaSpace.write(payment);

            log.info("TransactionWriterTask wrote new transaction between user: " + user.getName()
                    + " and merchant: " + merchant.getName());
        }
    }
}

From source file:com.ciphertool.genetics.algorithms.mutation.GroupMutationAlgorithm.java

/**
 * Performs a genetic mutation of a random Gene group of the supplied
 * Chromosome/*  w  w w .j a  v a2  s.  com*/
 * 
 * @param chromosome
 *            the Chromosome to mutate
 */
private void mutateRandomGeneGroup(Chromosome chromosome, Map<Integer, Integer> geneIndices) {
    /*
     * Choose a random number of genes constrained by the static max and the
     * total number of genes
     */
    int numGenesToMutate = (int) (Math.random() * Math.min(MAX_GENES_PER_GROUP, chromosome.getGenes().size()))
            + 1;

    int randomIndex;

    // We don't want to reuse an index, so loop until we find a new one
    int attempts = 0;
    do {
        randomIndex = (int) (Math.random() * chromosome.getGenes().size());

        attempts++;

        if (attempts >= MAX_ATTEMPTS_PER_MUTATION) {
            if (log.isTraceEnabled()) {
                log.trace("Exceeded " + MAX_ATTEMPTS_PER_MUTATION
                        + " attempts at finding a gene group to mutate.  Returning without performing mutation.");
            }

            return;
        }
    } while (exceedsChromosomeSize(chromosome, randomIndex + numGenesToMutate)
            || overlapsPreviousMutation(geneIndices, randomIndex, randomIndex + numGenesToMutate));

    mutateGeneGroup(chromosome, randomIndex, numGenesToMutate);

    geneIndices.put(randomIndex, randomIndex + numGenesToMutate - 1);
}

From source file:de.fau.amos.FileUpload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pathInfo = request.getPathInfo();
    System.out.println("called fileupload: " + pathInfo);
    boolean isImportProductionData = pathInfo != null && pathInfo.startsWith("/importProductionData");
    boolean isImportEnergyData = pathInfo != null && pathInfo.startsWith("/importEnergyData");

    if (ServletFileUpload.isMultipartContent(request)) {
        try {//ww  w  . j  a  v  a  2 s . co  m
            List<FileItem> list = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem fi : list) {
                if (!fi.isFormField()) {
                    String rand = "";
                    for (int i = 0; i < 6; i++) {
                        rand += (int) (Math.random() * 10);
                    }
                    String plantId = "";
                    if (isImportEnergyData || isImportProductionData) {
                        plantId = request.getPathInfo().replace((isImportEnergyData ? "/importEnergyData"
                                : (isImportProductionData ? "/importProductionData" : "")), "");
                    }
                    if (plantId == null || plantId.length() == 0) {
                        plantId = "";
                        //                  }else{
                        //                     plantId="_"+plantId;
                    }
                    String name = new File(rand + "_" + fi.getName()).getName()
                            + (isImportEnergyData ? "_impED" + plantId
                                    : (isImportProductionData ? "_impPD" + plantId : ""));

                    File folder = null;
                    if (isImportEnergyData || isImportProductionData) {
                        folder = new File(System.getProperty("userdir.location"), "import");
                    } else {
                        folder = new File(System.getProperty("userdir.location"), "uploads");
                    }
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    fi.write(new File(folder, name));
                }
            }

            request.setAttribute("message", "File uploaded successfully");
        } catch (Exception e) {
            request.setAttribute("errorMessage", "File upload failed!");
        }

    } else {
        request.setAttribute("errorMessage", "Something went wrong.");
    }

    if (isImportEnergyData || isImportProductionData) {
        //         request.setAttribute("plant",request.getPathInfo().replace("/import",""));
        //         request.getRequestDispatcher("/intern/import.jsp").forward(request, response);
        response.sendRedirect(request.getContextPath() + "/intern/import.jsp");
    } else {
        response.sendRedirect(request.getContextPath() + "/intern/funktion3.jsp");
    }

}

From source file:com.hortonworks.pso.data.generator.fields.StringField.java

public String getPoolValue() {
    int ran = (int) Math.round((poolSize - 1) * Math.random());
    return pool[ran];
}

From source file:nya.miku.wishmaster.http.client.DCP.java

private String getRandom() {
    return Long.toString((long) Math.floor(Math.random() * 1000000000));
}

From source file:com.btobits.automator.ant.utils.task.RandomTask.java

protected double calculateRandom2(double minD, double maxD) {
    return minD + Math.random() * (maxD - minD);
}

From source file:fr.fg.server.contract.NpcHelper.java

public static String getRandomFaction(String... factions) {
    return factions[(int) (Math.random() * factions.length)];
}

From source file:JVMRandom.java

/**
 * <p>Returns a pseudorandom, uniformly distributed long value between
 * <code>0</code> (inclusive) and the specified value (exclusive), from
 * the Math.random() sequence.</p>
 *
 * @param n  the specified exclusive max-value
 * @return the random long//from w  w w  .  j a v  a  2s  .  co m
 * @throws IllegalArgumentException when <code>n &lt;= 0</code>
 */
public static long nextLong(long n) {
    if (n <= 0) {
        throw new IllegalArgumentException("Upper bound for nextInt must be positive");
    }
    // TODO: check this cannot return 'n'
    return (long) (Math.random() * n);
}