Selecting Random Integer from int[]

Hi,
I have created an integer array. I have a for loop which will add values to the array if the condition is met. I then want to select one of the values in the array to use at random. Would anyone be able to help.
Thanks
Sohaib

you have to use an ArrayList to add objects once an array is declared its items can not be change plus ArrayList is much more useful for this problem
import the ArrayList class and the Random class with the statements
import java.util.ArrayList;
import java.util.Random;then you can create a new ArrayList and Random such as
ArrayList <int> randomNumbers = new ArrayList <int> ();
Random rnd = new Random();you can add new values at random with a method such as
public ArrayList setRandomNumbers(){
if (+condition+){
randomNumbers.add(+index+, rnd.nextInt(+highest number desired plus one here+)
}or if you want to assign a number instead of one at random use
randomNumbers.add(+index+,+number+)then you can reference them at random using:
randomNumbers.get(rnd.nextInt(number of elements -1));You can find more ArrayList methods at
[java.util.ArrayList|http://java.sun.com/j2se/1.3/docs/api/java/util/ArrayList.html]
Edited by: DJDJ on Apr 2, 2008 8:46 AM
Edited by: DJDJ on Apr 2, 2008 8:47 AM

Similar Messages

  • How to efficiently select random rows from a large table ?

    Hello,
    The following code will select 5 rows out of a random set of rows from the emp (employee) table
    select *
      from (
           select ename, job
             from emp
           order by dbms_random.value()
    where rownum <= 5my concern is that the inner select will cause a table scan in order to assign a random value to each row. This code when used against a large table can be a performance problem.
    Is there an efficient way of selecting random rows from a table without having to do a table scan ? (I am new to Oracle, therefore it is possible that I am missing a very simple way to perform this task.)
    thank you for your help,
    John.
    Edited by: 440bx on Jul 10, 2010 6:18 PM

    Have a look at the SAMPLE clause of the select statement. The number in parenthesis is a percentage of the table.
    SQL> create table t as select * from dba_objects;
    Table created.
    SQL> explain plan for select * from t sample (1);
    Explained.
    SQL> @xp
    PLAN_TABLE_OUTPUT
    Plan hash value: 2767392432
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |   725 | 70325 |   289   (1)| 00:00:04 |
    |   1 |  TABLE ACCESS SAMPLE| T    |   725 | 70325 |   289   (1)| 00:00:04 |
    8 rows selected.

  • Selecting random values from an array based on a condition

    Hi All,
    I have a small glitch here. hope you guys can help me out.
    I have an evenly spaced integer array as X[ ] = {1,2,3, ....150}. and I need to create a new array which selects 5 random values from X [ ] , but with a condition that these random values should have a difference of atleast 25 between them.
    for example res [ ] = {2,60,37,110,130}
    res [ ] = {10,40,109,132,75}
    I have been thinking of looping thru the X [ ], and selecting randomly but things look tricky once I sit down to write an algorithm to do it.
    Can anyone think of an approach to do this, any help will be greatly appreciated ...

    For your interest, here is my attempt.
    import java.util.Random;
    public class TestDemo {
        public static void main(String[] args) throws Exception {
            for (int n = 0; n < 10; n++) {
                System.out.println(toString(getValues(5, 25, 150)));
        private final static Random RAND = new Random();
        public static int[] getValues(int num, int spread, int max) {
            if (num * spread >= max) {
                throw new IllegalArgumentException("Cannot produce " + num + " spread " + spread + " less than or equals to " + max);
            int[] nums = new int[num];
            int max2 = max - (num - 1) * spread - 1;
            // generate random offsets totally less than max2
            for (int j = 0; j < num; j++) {
                int next = RAND.nextInt(max2);
                // favour smaller numbers.
                if (max2 > spread/2)
                    next = RAND.nextInt(next+1);
                nums[j] = next;
                max2 -= next;
            // shuffle the offsets.
            for (int j = num; j > 1; j--) {
                swap(nums, j - 1, RAND.nextInt(j));
            // add the spread of 25 each.
            for (int j = 1; j < num; j++) {
                nums[j] += nums[j-1] + spread;
            return nums;
        private static void swap(int[] arr, int i, int j) {
            int tmp = arr;
    arr[i] = arr[j];
    arr[j] = tmp;
    public static String toString(int[] nums) {
    StringBuffer sb = new StringBuffer(nums.length * 4);
    sb.append("[ ");
    for (int j = 0; j < nums.length; j++) {
    if (j > 0) {
    sb.append(", ");
    sb.append(nums[j]);
    sb.append(" ]");
    return sb.toString();

  • How can I select random records from one column

    How can I random select 400 records from a column contains more than 500,000 records? And how long will it take in oracle? Thanks.

    here is one option: (just change 5 to suit your needs...)
    SQL>select * from (
      2  select object_name
      3  from all_objects
      4  order by dbms_random.random
      5  ) where rownum < 5
      6  /
    OBJECT_NAME
    UTL_SYS_COMPRESS
    GV_$LOG_HISTORY
    GV_$LOGMNR_LOGS
    WWV_FLOW_THEME_7
    SQL>/
    OBJECT_NAME
    WWV_FLOW_UPGRADE_REPORT
    WRI$_ADV_SQLT_STATISTICS_PK
    V_$DATABASE
    GV_$SERVICEMETRIC
    SQL>/
    OBJECT_NAME
    WWV_FLOW_CREATE_FLOW_API
    WRH$_SERVICE_WAIT_CLASS_BL
    EXU8SNAPL
    GV$SERVICEMETRIC_HISTORY
    SQL>                well, regarding how long will it take... it depends from lots of variables...
    Cheers,
    Andrea

  • Selecting Randoms from Query of Queries

    I can create a query that selects random records
    <cfquery....>
    select top 10 * from table order by newid() <!--- SQL
    Server --->
    </cfquery>
    or
    <cfquery....>
    select top 10 * from table order by rand() limit 10 <!---
    MySQL--->
    </cfquery>
    However, is there a way to cache a query then select random
    records from it?
    I want to cache the overall query that retrieves all the
    records, then
    randomly pull
    from that cached query.
    If I use newid() or rand(), the query bombs on the
    parentheses.
    Any suggestions?
    Tami

    well, it's not really a query of queries... more like a query
    of a cached
    query :)
    "DixieGal" <[email protected]> wrote
    in message
    news:ffsn1b$***$[email protected]..
    |I can create a query that selects random records
    | <cfquery....>
    | select top 10 * from table order by newid() <!--- SQL
    Server --->
    | </cfquery>
    |
    | or
    | <cfquery....>
    | select top 10 * from table order by rand() limit 10
    <!--- MySQL--->
    | </cfquery>
    |
    | However, is there a way to cache a query then select random
    records from
    it?
    | I want to cache the overall query that retrieves all the
    records, then
    | randomly pull
    | from that cached query.
    |
    | If I use newid() or rand(), the query bombs on the
    parentheses.
    |
    | Any suggestions?
    |
    | --
    |
    | Tami
    |
    |

  • Random Integer - Code help

    Hi, I'm having a bit of a problem with a program I am making for class. I'm not asking you guys to do my work for me, I just simply need some guidance as to what I am doing wrong.
    Alright, what I am suppose to write as a program that takes two user defined integers and then prints a random integer from between the two user numbers. This is the code I have thus far:
            int a = Integer.parseInt(args[0]);
         int b = Integer.parseInt(args[1]);
         double r = Math.random();
         int low = a + (int) (r * a);
         int high = a - (int) (r * b);
         int result = low + high;
         System.out.println(result);For the most part it seems to work, however it will only work if the two user defined numbers are more then 10 digits of each other. I.E. 10 20 will work fine, however 1 5 will not, 10 15, etc.
    Any help would be greatly appreciated!
    Edited by: KnivesACE on Sep 18, 2008 11:32 AM

    Stianbl wrote:
    lower = 1000;  // your lower integer value
    upper = 2000; // the larger one of your two integers
    double rand = Math.random();
    int result = lower + (int)((upper - lower)* rand);
    http://forums.sun.com/thread.jspa?threadID=590266&messageID=3948731
    The question here is whether the two limits are to be included in the random range? In your solution 2000 will never happen. If you want it to it should look like this,
    int result = lower + (int)((upper - lower + 1)* rand);

  • Select random entity using JPA ql

    Hallo,
    I'd like to select random entity from database -- e.g. single fortune cookie that will be displayed on application web page. Unfortunately I've been able to think out only very simple (and inefficient) method so far:// Fortune cookie entity
    @Entity
    class FortuneCookie {
      @Id int id;
      String text;
    * @return random fortune
    public void FortuneCookie getRandomFortune() {
      // Query all fortunes
      Query q = em.createQuery("select f from FortuneCookie f");
      List allFortunes = q.getResultList(); 
      // Select one at random
      return getRandomListElement(allFortunes);
    }How do I perform such (random) select without actually fetching all object from database, please? If possible avoid fallback to native query, I use javaDb for development but product will be deployed on mysql database.
    ~~
    Adam
    PS: I am not sure about forum. Does posts about jpa belong here?

    Thank you...
    Don't your fortune cookies have a unique id as a number? ...Yes they have but, cookies can be removed and thus, interval is not continuous. E.g. {1,2,5,6,7} after 3 and 4 has been removed.
    ... you could preload and cache them in a collection and
    randomize on the position of an element in that collection...Cacheing seems like a good idea -- I'll probably add some FortuneCookieDAO as layer between my accessor session beans (FortuneCookieAccess) and cookie entity (FortuneCookie). But where should I store instance of this DAO? It has to be accessible from any session bean instance. Into my server's directory (jndi)?
    Or did you mean cache on site of web application? That's not possible, my selecting random cookie is responsibility of FortuneCookieAccess ejb.
    ~~
    Adam
    PS: I know that using ejbs for fortune cookie selection is not a model usecase (there's saying in my country: "It's like shooting sparrow with a cannon") ... is not a model usecase, but it's just training application.

  • Select Random Rows in PL/SQL

    I would like to know if anyone has a suggestion fora select statement that would select random rows from a table based on the following:
    The table contains 1-to-many categories. From each of these categories I need to select a 'x' amount of rows based upon the category id, with a total of 25 rows being selected overall. Some categories will have only 1 row selected, some will have more than 1. The rows selected contain questions that are either multiple choice (type=1) or true/false (type=2). The total rows selected (25) cannot contain more than 20% of true/false questions. Anyone have a solution for a select statement? Thanks.

    Not having a database at hand. To be treated as a template
    with
    parameters as
    (select all_rows,
            all_categories,
            :all_questions all_questions,                               -- your 25
            :category_questions category_questions,                     -- your 'x'
            ceil(all_categories / :category_questions) pick_categories,
            :type_2_percentage type_2_percentage                        -- your 20% expressed as 0.2
       from (select count(*) all_rows,
                    count(distinct category) all_categories,
               from your_table
    categories_scrambled as
    (select category,dense_rank() over (order by categories_mix) category_choice
       from (select category,
                    ceil(dbms_random.value(0,1000)) categories_mix
               from your_table
              group by category
    rows_scrambled as
    (select category,question_type,question_text,dense_rank() over (order by rows_mix) row_choice
       from (select category,question_type,question_text,
                    ceil(dbms_random.value(0,10000)) rows_mix
               from your_table
    combination as
    (select r.category,r.question_type,r.question_text,r.row_choice,c.category_choice,
            row_number() over (partition by r.row_choice,r.question_type order by r.row_choice) row_mark
       from rows_scrambled r,categories_scrambled c
      where r.category = c.category
    type_2_questions as
    (select question_text,question_type,category
       from combination
      where category_choice <= (select pick_categories from parameters)
        and row_mark <= floor(:all_questions * :type_2_percentage / (select pick_categories from parameters))
        and question_type = 2
    type_1_questions as
    (select question_text,question_type,category,row_number() over () the_count
       from combination
      where category_choice <= (select pick_categories from parameters)
        and row_mark <= ceil((:all_questions - (select count(*) from type_2_questions)) / (select pick_categories from parameters))
        and question_type = 1
    select question_text,question_type,category
      from type_2_questions
    union all
    select question_text,question_type,category
      from type_1_questions
    where the_count <= :all_questions - (select count(*) from type_2_questions)Regards
    Etbin

  • When selecting playback from itunes library on Mac (purchased album from itunes!) i get random song played from that album and my selected song disappears from view. Nothing to do with shuffle.Mac OSX 10.6.8. Help, doing my nut in!!

    When selecting playback from itunes library on Mac (purchased album from itunes!) i get random song played from that album and my selected song disappears from view. Nothing to do with shuffle.Mac OSX 10.6.8. Help, doing my nut in!!

    What is your iTunes version?
    If iTunes 11, have you checked the "Up Next" list? If it is not empty, try if clearing "UP Next" will help:

  • Select statement for JDBC receiver synch scenario for capturing random value from ECC portal

    Dear Experts,
    I am working on ECC <----> SAP-PO 7.31 <----> JDBC synchronous scenario. I am clear about the config part except the Select statement. I will be
    capturing 2 random values from the portal i.e. VendId and VendName in ECC to get the vendor details like Vendor Country, Vendor Status, Vendor Contact , Vendor Address etc from JDBC vendor table/view VENDETAIL.
    What would be the select statement to capture the random values for ECC portal? My select statement would look some thing like this..
    Select f1,f2,f3,f4 from table VENDETAIL where key1 = "VendId" and "VendName"
    Please suggest if the above select statement works for the above scenario...
    Regards
    Rebecca

    Hi Rebecca,
    Your statement should work fine.
    Please see the statement we use below.
    SELECT eT_cashier, eT_proc_yn, eT_proc_date FROM eTest WHERE eb_proc_yn = 'N'
    Just remember to update the change indicator so that you dont duplicate your records.
    UPDATE eTest SET eb_proc_yn = 'Y' WHERE eb_proc_yn = 'N'.
    Regards,
    Jannus Botha

  • Randomly selecting some rows from the database table

    Hi can some one help me in selecting some rows from a database table which has around 90,000 rows.
    Thanks.

    One thing you might try is the "sample" clause if you have 8i which is supposed to return a random percentage of the table. Say for example, you have a sequence number on your table as the pkey. Then you might try:
    select * from <table_name> where pkey in(select pkey from <table_name> sample(10));
    This should give you a random 10 percent of the rows in the table but I tried this once and the results seemed unpredictable. For example it returned a different number of rows each time even though the number of rows in the table didn't change.
    Hope this works for you.

  • Help with selecting 10 random records from all records meeting report selection criteria in Crystal 11

    <p>I am trying to select ten random records from all that match the report selection criteria then report on each of these random records for QA/QI.  I have tried the RND function however it is giving me a random number rather than a random record selection.  I cannot figure this out and am despirately seeking assistance.</p><p>Thank you,</p><p>Amy</p>

    <p>I don&#39;t know of any Random record selection functions but maybe you could write your own custom function inside of a record selection to randomly filter the records.  You would use the Rand function we currently have to decide if a record was included in the report data or not.</p><p>Another possible option is to filter the records before they get to the report.  You can only do this if you are pushing the data into the report instead of having the report pull the data.  An example of this would be passing an ado recordset to a report at runtime. </p><p>Rob Horne</p><p>http://diamond.businessobjects.com/blog/10 </p>

  • How to convert from java.lang.Integer to int

    Could you please show me
    how to convert from java.lang.Integer to int?
    and how to convert from java.lang.Integer to String?
    Thanks,
    Minh

    Could you please show me
    how to convert from java.lang.Integer to int?
    and how to convert from java.lang.Integer to String?Tip: always keep a browser open on the API docs; if you've got a
    couple of MBs to spare, download the docs; it's very convenient.
    kind regards,
    Jos

  • Selecting random from hashtable

    Hi,
    I need a datastructure in which I can store pairs of IP numbers and port numbers. This database might get pretty big (it's like a p2p application). A hashtable seems like a good choice. This way I can quickly check if a certain IP number is in the database.
    But I also need to get a random entry from the database. Is there a nice and easy way to do this? Or should I opt for another datastructure ?
    thanks in advance,

    Thanks for the reactions.
    My concern with these methods is that if I have a large database they will require a lot of extra memory. It will have to work for a database of a couple of thousands entries. That's purely theoretical, but scalability is a key point here.
    Alex's solution clearly makes a distinct array which would use a lot of memory. Would the solution with the enumeration do the same? Or is the enumeration linked to the Hashtable so that it doesn't need a very large seperated structure in memory ?
    cheers,

  • How can i get the random values from database?

    Hi,
    i want to get random values from database.
    I try my best find no solution
    plz give solution in either sql query or java method.
    thanks in advance.

    try this:
    Give a numeric row-id to each row of database.
    say (1-100) for 100 rows
    In the program use random function to get random number between 0 and 1. this value u multiply with 100(or total number of rows) and take integer value of it . u then perform sql query to select the a row which matches randomly genarated value with row-id assigned to each row of database
    madhu

Maybe you are looking for

  • How can I install OEM when full hostname 32 characters

    At the end of my DB creation with DBCA, it fails on Oracle Enterprise Manager (OEM) installation. Installing 10gr2 DB in an 11g2 cluster. Running the emca command in isolation I get: STARTED EMCA at Nov 23, 2010 1:36:51 PM EM Configuration Assistant,

  • HT1430 How do you power off a i Phone in Assistive Touch?

    I have to use Assistive Touch on my phone because the power button does not work, how do I power off the phone completely when I use Assistive Touch?

  • Issue with bodog website

    I have a verizon 8330 curve and my verison is 4.5.0.175. I'm having an issue with https://sports.bodog.com/. I can log in and get all the way to where I click on "Review My Bet." I click the button and it goes nowhere. It acts like I haven't clicked

  • Can't get JDK6 docs to work properly

    I just downloaded and unzipped the JDK6 documentation, however when I launch the index.html file in my IE7 browser and click any of the links I get an "Error on page." Any suggestions?

  • HT4623 Das Geht nicht auf mein iPad was soll ich den noch machen

    Also ich will auf ein iPad IOS 6 runter holen aber es Geht nicht ! Ich hoffe sie können mir helfen?!