Weighted random value (1-10) e.g.3 will be  50 % of records

Hello,
i need to generate random values into my table. For the simplification, lets say that i need to generate values in range from 1 to 10. For this there is a lot of ways.
e.g. UPDATE test_number SET random_value = round (dbms_random.value (1,10))
But what I need is something like weighted random values. I need random values to be inserted into column, but I need e.g. 3 to be inserted more times than other values e.g. if i have 100 rows i want to have 3 in 50 random rows
Do you have any idea how to achieve it?
Thanks a lot for any help or reply !

Hi,
You can do something like this:
WITH     got_p_num     AS
     SELECT     LEVEL                         AS id
     ,     FLOOR (dbms_random.value (1, 19))     AS p_num
     FROM     dual
     CONNECT BY     LEVEL     <= 10
SELECT       id
,       p_num
,       CASE
          WHEN  p_num     < 3     THEN p_num
          WHEN  p_num     < 12     THEN 3
                                 ELSE p_num - 8
       END     AS r_num
FROM       got_p_num
ORDER BY  r_num
;If you want the number 3 to appear on half of the rows; that means that, out of 18 random numbers, you expect 3 to occur 9 times, and the other numbers to appear once each. The query above generates random integers in the range 1 through 18 inclusive, and calls this number p_num. The CASE statement maps p_num to what you really want, a n integer between 1 and 10, with 3 occurring 9/18 (= 1/2) of the time.
Instead of using a CASE expression, you might want to create a table, that has one row for every number that can be in the output, and the probability of picking that number. You could then join to that table to convert the raw random number to the id that you want.
Edited by: Frank Kulash on Oct 6, 2011 3:36 PM

Similar Messages

  • Inserting Random Values

    Hi there!
    just a little question:
    I want to insert into a table random values between -2 and 2, which shoul differ for every row. When I'm writing
      FOR n IN nodes LOOP
        FOR EACH n2 IN nodes2 LOOP
          IF (n2.layer_ = n.layer_ +1) THEN
            INSERT INTO nn2_links (lfdnr, sourceid, destid, weight, delta_weight, Zone_)
                 VALUES (lfdnr#, n.nodeid, n2.nodeid, dbms_random.value(-2,2), 0, Zone#);
            lfdnr# := lfdnr# +1;
          END if;
        END LOOP;
      END LOOP; I'll get the same value for all records fullfilling the IF-criteria in the middle. What can I do? Must I write another loop?
    greetings
    ~Mel

    OP states that she / he would like to have distinct values for every row but instead gets the same value for all rows.
    To OP:
    Sorry mel, not much help. Can't see the error in your script.
    When I put a anonymous block together, it runs smoothly:
    SQL> set serveroutput on
    SQL> declare
      2  outn number;
      3  cnt number;
      4  begin
      5  cnt := 1;
      6  while cnt <=10 loop
      7     select dbms_random.value(-2,2) into outn from dual;
      8     dbms_output.put_line('Wert: '|| to_char(outn));
      9     cnt := cnt + 1;
    10  end loop;
    11  end;
    12  /
    Wert: 1,94760933757912513703045869459081746304
    Wert: ,1850733416444459069798272966494986884
    Wert: -1,28557676353717597230879638125649445416
    Wert: -,20789721958144010481059709280045566588
    Wert: -1,46550435548323732535026606603236048092
    Wert: -1,48594688953909777344516402506798302304
    Wert: -,2162809554864053530960985675499170964
    Wert: 1,71049071188915501435899411045229762652
    Wert: ,53354523369664937673204584890644358732
    Wert: -,96917849158672171927090500710866039384
    PL/SQL-Prozedur wurde erfolgreich abgeschlossen.
    SQL>

  • 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

  • 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();

  • Pending sales order weight and value

    Dear all,
    Please guide me that how ill get pending sales order weight and net value for all line items.
    I used VBUK for pending sales order where lfstk = ''a' or 'b' and vbtyp = 'c'.
    for line item details i used VBUP where LFSTA = ''a' or 'b'.
    for further line item details i used VBAP, in BRGEW and NTEWR i get weight and value for particular line item.
    But if some line item is partially deliverd, then how i come to know that it is partially deliver and where its details are stored. how i calculate the partial delivered weight and value.
    Please help me in this issue.
    Thanks
    Puneet

    hi,
    vbap -for sales orders,
    likp - for delivary.
    if u need remaing qty in partial delivary then u use logic which satisfy the condition below.
    OPEN qty = Order Qty - Delivery Qty.
    by linking vbap & likp u can get this.
    regds:
    rajesh.k

  • Random Value Generation

    FYI, time to give back. I have received a number of excellent
    responses from this forum, so here is one that might help someone
    else.
    I had found and modified the code below to generate a random
    value (letters and numbers) to use as a member ID. With it you can
    set the length of the generated value, as well as the content
    (numbers, capital letters, lower case letters, even special
    symbols). I chose a subset of capital letters along with 0-9 so the
    result contained more numbers.

    I don't get it?! Why not just use something like
    #createUUID()#, which is also apparently meant to be unique
    everytime.
    If you don't like the format of createUUID you can always run
    a couple of functions over it to alter it a bit, like taking out
    some of the dashes, or making it longer etc.
    Maybe I'm missin the point...it's late here!! Me =
    sleepy.

  • Unique Random Values

    OK, firstly, I am a Java n00b. I am not creating a program, just editing some source, but I need some help. What I need, are 5 different variables, each with a random value (integer) between 1 and 5 (inclusive), but, I don't want to variables to have the same value. The outcomes I'm looking for could be as follows:
    t = 4
    i = 3
    g1 = 5
    g2 = 1
    y = 2
    and then the next time the code is run I might get:
    t = 1
    i = 5
    g1 = 4
    g2 = 2
    y = 3
    Each variable has a random value (integer) between 1 and 5 (inclusive), but no 2 variables have the same value.
    Here is what I tried:
         Random rand = new Random();
         int t = (rand.nextInt(5) + 1);
         int i = (rand.nextInt(5) + 1);
         int g1 = (rand.nextInt(5) + 1);
         int g2 = (rand.nextInt(5) + 1);
         int y = (rand.nextInt(5) + 1);
    // While i is the same as t, make i a new random integer between 1 and 5. Yes? Or no...?
         do {
         i = (rand.nextInt(5) +1);
         } while (i == t);
         do {
         g1 = (rand.nextInt(5) +1);
         } while (g1 == t);
         do {
         g1 = (rand.nextInt(5) +1);
         } while (g1 == i);
         do {
         g2 = (rand.nextInt(5) +1);
         } while (g2 == t);
         do {
         g2 = (rand.nextInt(5) +1);
         } while (g2 == i);
         do {
         g2 = (rand.nextInt(5) +1);
         } while (g2 == g1);
         do {
         y = (rand.nextInt(5) +1);
         } while (y == t);
         do {
         y = (rand.nextInt(5) +1);
         } while (y == i);
         do {
         y = (rand.nextInt(5) +1);
         } while (y == g1);
         do {
         y = (rand.nextInt(5) +1);
         } while (y == g2);But when I use the variables in the next part of the program, sometimes it works, but sometimes 2 of them are the same. Sometimes even 4...
    Can someone help me please?

    Thinking about it now though, I would like to learnproperly. What is a good Java guide that starts from
    scratch?
    I think the Core Java books, by Cay Horstmann, are a
    great way to start learning Java. I refered to his
    books constantly durning college:
    http://www.amazon.com/exec/obidos/tg/detail/-/013148202
    /qid=1096410169/sr=1-1/ref=sr_1_1/104-3324308-3016709?v
    glance&s=books
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • Get a random value out of a query result

    I have a query:
    select id
    from class_schedule
    where id not in (
    select distinct(event_id) from trainer_schedule)I want to pick up a random value from this query result and assign it to a varible e.g. randomID.
    please help

    here is the example
    SQL> SELECT empno,ename
      2  FROM (
      3    SELECT empno,ename
      4    FROM EMP
      5    ORDER BY dbms_random.VALUE)
      6  WHERE ROWNUM = 1;
          7876 ADAMS
    SQL> /
          7566 JONES
    SQL> /
          7900 JAMES
    SQL> /
          7844 TURNER
    SQL>

  • 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

  • Build array from random values via ethernet

    Am trying to save data that comes from ehternet ((random values (modbus protocol)) in an array.
    I am using an index array.....but all the values are the same!! How can I sort them??
    It functions correctly with a for loop with random numbers build.......but it doesn't work with the data from ethernet.
    Can someone please help me??
    Attachments:
    Data.vi ‏16 KB

    chendel wrote:
    Am trying to save data that comes from ehternet ((random values (modbus protocol)) in an array.
    I am using an index array.....but all the values are the same!!
    You just read the same shared variable 100 times within a few nanoseconds. Apparently, the variable gets modified less often on the other end.
    chendel wrote:
    How can I sort them??
    If all array values are the same, they are already sorted.
    You need to rethink your code. maybe you can make the shared variable an array and write the entire random array on the other end, the read it out once.
    LabVIEW Champion . Do more with less code and in less time .

  • I have two problems with my 2012 13" MacBook Pro. 1. Gray screen shows at startup  2. Randomly disconnects from network. Any help will be greatly appreciated.

    I have two problems with my 2012 13” MacBook Pro.
    Gray screen shows at startup
    Randomly disconnects from network.
    Any help will be greatly appreciated.

    First, open Terminal in your Utilities folder and paste this into the prompt line:
    sudo update_dyld_shared_cache
    Press RETURN. You will be prompted to enter your admin password which will not be echoed to the screen. Press RETURN again.
    Next, boot the computer into Safe Mode.
    Next, do the following:
    Reinstalling Lion/Mountain Lion Without Erasing the Drive
    Boot to the Recovery HD: Restart the computer and after the chime press and hold down the COMMAND and R keys until the menu screen appears. Alternatively, restart the computer and after the chime press and hold down the OPTION key until the boot manager screen appears. Select the Recovery HD and click on the downward pointing arrow button.
    Repair the Hard Drive and Permissions: Upon startup select Disk Utility from the main menu. Repair the Hard Drive and Permissions as follows.
    When the recovery menu appears select Disk Utility. After DU loads select your hard drive entry (mfgr.'s ID and drive size) from the the left side list.  In the DU status area you will see an entry for the S.M.A.R.T. status of the hard drive.  If it does not say "Verified" then the hard drive is failing or failed. (SMART status is not reported on external Firewire or USB drives.) If the drive is "Verified" then select your OS X volume from the list on the left (sub-entry below the drive entry,) click on the First Aid tab, then click on the Repair Disk button. If DU reports any errors that have been fixed, then re-run Repair Disk until no errors are reported. If no errors are reported click on the Repair Permissions button. Wait until the operation completes, then quit DU and return to the main menu.
    Reinstall Lion/Mountain Lion: Select Reinstall Lion/Mountain Lion and click on the Continue button.
    Note: You will need an active Internet connection. I suggest using Ethernet if possible because it is three times faster than wireless.

  • If the LDAP "icsCalendar" value contains a space, an error will occur when creating events or tasks

    If a user's LDAP
    "icsCalendar" value
    contains a whitespace, the user will still be able to log in to the iPlanet
    Calendar Server(iCS). However, the user will receive a bad request
    error when creating events or tasks. The event or task is created,
    but the error will occur every time the user tries to save one.
    The "icsCalendar"
    preference cannot have a space in it. To avoid the above problem,
    the administrator must fix this value in LDAP.

    Hi Mahendra,
    check the following links:
    http://www.sapgenie.com/saptech/lsmw.htm
    http://www.scmexpertonline.com/downloads/SCM_LSMW_StepsOnWeb.doc
    May be u can find some help.
    Hope this helps you.
    Regards,
    Anuradha.B

  • In WL 6.1 SP4 random value updated in NUMBER column

    Our application used to update a NUMBER(15) column in Oracle with current time
    in milliseconds.
    After migrating from SP3 to SP4 I observed that ORA-01438 was being thrown during
    the update intermittently.
    Increasing the size to default NUMBER, I observed that the values getting inserted
    are sometime random like 59, 81 digits long!
    The update code just does a prepared statement and does setObject of a java.lang.Long.
    I am using the oracle thin driver in oracle's classes12.zip.
    I am sure that this is happening since using SP4, have anyone faced similar problems?

    We have changed default thin driver to 920 from 817 in 610sp4. If you are using 817
    dbserver, please put 817 classes12.zip in your classpath before weblogic.jar and you will
    be ok.
    Mitesh
    Harish SK wrote:
    Our application used to update a NUMBER(15) column in Oracle with current time
    in milliseconds.
    After migrating from SP3 to SP4 I observed that ORA-01438 was being thrown during
    the update intermittently.
    Increasing the size to default NUMBER, I observed that the values getting inserted
    are sometime random like 59, 81 digits long!
    The update code just does a prepared statement and does setObject of a java.lang.Long.
    I am using the oracle thin driver in oracle's classes12.zip.
    I am sure that this is happening since using SP4, have anyone faced similar problems?

  • How to change double i = Math.random(); value to (int) value

    I am trying to find out how to convert a given double value to integer, which is, to conver double myNumber = Math.random() to (int) value. Here is the sample program look like this.
    Thank you for the help.
    import javax.swing.JOptionPane;
    public class numbers
    public static void main(String[] args)
    int upperLimit = Integer.parseInt(JOptionPane.showInputDialog
    (null, "Enter the upper range integer."));
    double myNumber = Math.random();
    //Test of Random numbers.
    System.out.println("The Upper random number limit is: " +
    myNumber * upperLimit);
    } //End of main.
    } // End of class.

    Not sure exactly what you want and why you want to change the double to an int. I'm assuming by this you want to generate random integers, from 1 to the upper limit the user enters? If so, this is how I would do it:import java.util.*;
    import javax.swing.*;
    public class Numbers
        public static void main(String[] args)
            int upperLimit = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the upper range integer."));
            Random r = new Random();
            int myNumber = r.nextInt(upperLimit) + 1;
            System.out.println(myNumber);
    }

  • Random value out of a HashMap

    Hi, I'm trying to make a translation program (for testing purposes)
    I've put the words and their explanation in a HashMap like
    key value
    Run --- loop(wich is the translation in dutch)
    I'm not sure if this is the right collection i need for it.
    Another way i know is to create 2 arrays and do it that way...
    But now I want to show a random key out of that Map or just loop trough them,how can that be done.
    Can a moderator replace my message to the java newbies section :p I didn't saw it until now.
    Message was edited by:
    stef569
    Message was edited by:
    stef569
    null
    Message was edited by:
    stef569
    Message was edited by:
    stef569

    I'm in a generous mood
    define this interface
    import java.util.Map;
    public interface RandomMap extends Map {
         Object getRandomValue();
    }define this class
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Random;
    import java.util.Set;
    public class RandomMapImpl implements RandomMap {
         private Map innerMap;
         public RandomMapImpl() {
              innerMap = new HashMap();
         public Object getRandomValue() {
              List list = new ArrayList(innerMap.values());
              if ( list.isEmpty() ) {
                   return null;
              int index = new Random(System.currentTimeMillis()).nextInt(list.size() -1);
              return list.get(index);
         public void clear() {
              innerMap.clear();
         public boolean containsKey(Object key) {
              return innerMap.containsKey(key);
         public boolean containsValue(Object value) {
              return innerMap.containsValue(value);
         public Set entrySet() {
              return innerMap.entrySet();
         public Object get(Object key) {
              return innerMap.get(key);
         public boolean isEmpty() {
              return innerMap.isEmpty();
         public Set keySet() {
              return innerMap.keySet();
         public Object put(Object key, Object value) {
              return innerMap.put(key, value);
         public void putAll(Map t) {
              innerMap.putAll(t);
         public Object remove(Object key) {
              return innerMap.remove(key);
         public int size() {
              return innerMap.size();
         public Collection values() {
              return innerMap.values();
    }you could make it simpler still by defining the following class instead
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Random;
    public class RandomMapImpl extends HashMap implements RandomMap {
         public Object getRandomValue() {
              List list = new ArrayList(values());
              if ( list.isEmpty() ) {
                   return null;
              int index = new Random(System.currentTimeMillis()).nextInt(list.size() -1);
              return list.get(index);
    }but I'm not a big fan of class inheritance, it could cause you problems later. up to you

Maybe you are looking for

  • Can't send or receive mail from Outlook

    just purchased a wireless router and hooked up recently. Can access the internet & outlook express but can't get my mail from outlook which is my main email account. Message says can't find exchange server. I can access Outlook from my laptop wireles

  • Safari unable to open PDf's.

    I installed Adobe Reader to fill out a PDF document and then deleted the Application. Now when I select a PDF file within Safari, it prompts me to locate Adobe instead of opening the file within Safari or in Preview. In an attempt to resolve this, I

  • How to insert data into two different lists in sharepoint 2010

    I have a page containing a dropdown list having two departments like IT, HR. If i select HR, one input form will display for filling HR related info, these i need to store in HR list. In the same way for other dept through custom coding. someone help

  • Resetting my password

    I have received an e-mail, purportedly from Adobe, requesting me to reset my password. is this official?

  • Which account was used to purchase apps

    I need to re-download a few apps. I've used two accounts to purhcase apps in the past. To avoid using the wrong account and being charged, I'd like to figure out before-hand which account was used to purchase an app. Any way to do this? Appreciate it