Generating a Random sequence

Hello All,
I want some help writing a method which generates a set of 100 numbers with values 0 and 1, but the input should be percent of number of 1's and 0's...I mean if I give 20% for 0's and 80% for 1's then in the generated sequence I should get 20, 0's and 80, 1's...randomly.....hope Iam clear with my question.....please help me
Thanks,
Raghu.

Here is a utility you can use.. you just need to make the call to get the proper random number of ones and pass the size you want.. it returns an array of strings of ones and zero's but you can convert it to whatever type you need.
--John Putnam
import java.util.*;
* <p>Title: ShuffleBits</p>
* <p>Description: example of creating a string of 1's and 0's and shuffling them</p>
* <p>Copyright: Copyright (c) 2003</p>
* @author John Putnam
* May be use freely with inclusion of this copyright notice
* @version 1
public class ShuffleBits
      * method to create an array of strings of 1's and zeros then shuffle them
      * @param numberOfOnes exatly to include (the rest are zero's)
      * @param maxNumberOfBits total number of ones and zeros.
      * @return randomized list of ones and zeros
  public String[]  randBits(int numberOfOnes, int maxNumberOfBits)
       ArrayList bits  = new ArrayList(maxNumberOfBits);
       for(int i=0;i<numberOfOnes;i++) bits.add("1");
       for(int j=0;j<(maxNumberOfBits-numberOfOnes);j++) bits.add("0");
       Collections.shuffle(bits);  //--do the shuffling of order
       Iterator ib = bits.iterator();
       String[] bitsBack = new String[maxNumberOfBits];
          //--pull out the shuffled bits
       int rb = 0;
       while(ib.hasNext()) bitsBack[rb++] = (String)ib.next();
       return bitsBack;
   } //--end randBits
//--------------------------------unit testing main--------------------------------
   public static void main(String[] args)
         ShuffleBits test = new ShuffleBits();
         int numOnes;
         int maxNumber;
         String[] bitsBack = null;
         numOnes = 5;
         maxNumber = 15;
         bitsBack = test.randBits(numOnes,maxNumber);
         System.out.println("\n--Test for #ones: " + numOnes + " max: " + maxNumber);
         for(int i=0;i<maxNumber;i++) System.out.println("--I: " + i + " bit: " + bitsBack);
numOnes = 12;
maxNumber = 15;
bitsBack = test.randBits(numOnes,maxNumber);
System.out.println("\n--Test for #ones: " + numOnes + " max: " + maxNumber);
for(int i=0;i<maxNumber;i++) System.out.println("--I: " + i + " bit: " + bitsBack[i]);
numOnes = 12;
maxNumber = 15;
bitsBack = test.randBits(numOnes,maxNumber);
System.out.println("\n--Test for #ones: " + numOnes + " max: " + maxNumber);
for(int i=0;i<maxNumber;i++) System.out.println("--I: " + i + " bit: " + bitsBack[i]);
numOnes = 12;
maxNumber = 15;
bitsBack = test.randBits(numOnes,maxNumber);
System.out.println("\n--Test for #ones: " + numOnes + " max: " + maxNumber);
for(int i=0;i<maxNumber;i++) System.out.println("--I: " + i + " bit: " + bitsBack[i]);
} //--end main
} //--end shuffle bits
The output was.
--Test for #ones: 5 max: 15
--I: 0 bit: 0
--I: 1 bit: 1
--I: 2 bit: 0
--I: 3 bit: 0
--I: 4 bit: 1
--I: 5 bit: 0
--I: 6 bit: 0
--I: 7 bit: 0
--I: 8 bit: 0
--I: 9 bit: 1
--I: 10 bit: 0
--I: 11 bit: 0
--I: 12 bit: 1
--I: 13 bit: 1
--I: 14 bit: 0
--Test for #ones: 12 max: 15
--I: 0 bit: 1
--I: 1 bit: 1
--I: 2 bit: 0
--I: 3 bit: 0
--I: 4 bit: 1
--I: 5 bit: 1
--I: 6 bit: 0
--I: 7 bit: 1
--I: 8 bit: 1
--I: 9 bit: 1
--I: 10 bit: 1
--I: 11 bit: 1
--I: 12 bit: 1
--I: 13 bit: 1
--I: 14 bit: 1
--Test for #ones: 12 max: 15
--I: 0 bit: 1
--I: 1 bit: 1
--I: 2 bit: 0
--I: 3 bit: 1
--I: 4 bit: 1
--I: 5 bit: 0
--I: 6 bit: 1
--I: 7 bit: 1
--I: 8 bit: 0
--I: 9 bit: 1
--I: 10 bit: 1
--I: 11 bit: 1
--I: 12 bit: 1
--I: 13 bit: 1
--I: 14 bit: 1
--Test for #ones: 12 max: 15
--I: 0 bit: 1
--I: 1 bit: 1
--I: 2 bit: 1
--I: 3 bit: 1
--I: 4 bit: 1
--I: 5 bit: 1
--I: 6 bit: 1
--I: 7 bit: 0
--I: 8 bit: 0
--I: 9 bit: 1
--I: 10 bit: 1
--I: 11 bit: 1
--I: 12 bit: 1
--I: 13 bit: 0
--I: 14 bit: 1
notice the last few are the same sizes but come out in different order.
--John Putnam                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • How to generate pseudo random noise(PRN) binary sequence using shift registers?

    what is the block diagram to generate pseudo random noise (PRN) binary sequence of 1's and 0's using shift registers
    please help
     i need 2 submit this project in this week

    This is a fairly simple homework problem. My hints (on the LabVIEW side):
    1- look at while loops
    2- look at shift registers on while loops with multiple input elements
    3-look at the logic components, AND, OR XOR
    Look at this wiki article: http://en.wikipedia.org/wiki/Linear_feedback_shift_register
    Do the work, you won't learn if someone shows you how it is done! The palette that the previous post points to are of PRN and other "noise generators" but I suspect that is not what you are after.
    Know that creating a PRN with a reasonable number of shift register taps produces very pseudo results, as the "random" pattern begins to repeat pretty quickly, thereby making it not a truly random number. 
    When you have an attempt that is sort of working and want additional suggestions, post the code here. We won't do your work, we will help you try to do it, and learn it, yourself.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • Generating 7 numbers random sequence

    Hello,
    create sequence centers_seq
    start with 1234567 increment by 1;
    This statement will create and start sequence from 1234567 and will increment by 1 whereas I am trying to generate random 7 digits and of course unique
    Thanks in anticipation
    Best regards

    Raakh wrote:
    I want to generate login ID but not in a sequence. The IDs are in 100's not more so I need to auto generate unique random IDs of 7 digitsWell, you can take a semi-random approach:
    SQL> create sequence s start with 100 maxvalue 999
      2  /
    Sequence created.
    SQL> select s.nextval * 10000 + trunc(dbms_random.value(1000,9999)) unique_semi_random_7_digit_num from dual
      2  /
    UNIQUE_SEMI_RANDOM_7_DIGIT_NUM
                           1007776
    SQL> /
    UNIQUE_SEMI_RANDOM_7_DIGIT_NUM
                           1017247
    SQL> /
    UNIQUE_SEMI_RANDOM_7_DIGIT_NUM
                           1025913
    SQL> /
    UNIQUE_SEMI_RANDOM_7_DIGIT_NUM
                           1033573
    SQL>  SY.

  • RANDOM SEQUENCE

    HI,
    CAN I GET A RANDOM NUMBER USING A FUNCTION OR CALLING A SELECT...'SOMETHING' ... FROM DUAL ???
    THANKS, MARCO.

    Here is an example from site http//asktom.oracle.com
    Randomly generate and unique is sort of an oxymoron.
    What I've done in the past is to combine 3 or so numbers together to achieve this. One that I use alot is:
    sequence_name.nextval &#0124; &#0124; to_char( sysdate, 'DDDSSSSS' )
    You can do the same thing with a random number (replace the to_char(sysdate) with a random number of a FIXED length -- eg:
    sequence_name.nextval &#0124; &#0124; to_char( random.rand,'fm00000' )
    See
    http://osi.oracle.com/~tkyte/Misc/Random.html
    for howto generate a random number.
    You need to combine a sequence or some other UNIQUE thing with the random number to get uniqueness.
    Another option is to use the sys_guid() function available in 8i. For example:
    ops$[email protected]> create table t as select sys_guid() u_id from dual;
    Table created.
    ops$[email protected]> desc t;
    Name Null? Type
    U_ID RAW(16)
    ops$[email protected]> select * from t;
    U_ID
    722EF40A77F1386AE034080020A767E0
    sys_guid() generates a 16byte globally unique key that is non-sequential.
    If you need it as a number, it can be converted:
    ops$[email protected]> set numformat
    999999999999999999999999999999999999999999999999
    ops$[email protected]> select to_number(
    '722EF40A77F1386AE034080020A767E0',
    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ) from dual;
    ops$[email protected]> /
    TO_NUMBER('722EF40A77F1386AE034080020A767E0','XXXXXXXXXXXXXX
    151775786912318261447473874650479945696
    ops$[email protected]> select sys_guid(),
    2 to_number(sys_guid(),'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' )
    from dual;
    SYS_GUID()
    TO_NUMBER(SYS_GUID(),'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
    722EF40A77F2386AE034080020A767E0
    151775786912320679299113103908829358048
    ops$[email protected]> /
    SYS_GUID()
    TO_NUMBER(SYS_GUID(),'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
    722EF40A77F4386AE034080020A767E0
    151775786912323097150752333167178770400
    Helena

  • Generating a pulse sequence in NI5401 board

    Sirs,
    I?m sending this email massage because I have a doubt concerning NI 5401 Function Generator Board.
    I?m working with a PXI system together with a NI5401 board, and I want to generate a pulse sequence with this board.
    The propose of this is to synchronize my pulses with the acquisition of data by another board (PXI board from Goeppel ? Boundary Scan board which has 4 I/0 ports of 8 bits)
    I want for each pulse generated to acquire and transfer data in that board, thus I need to know how can I send a predetermined sequence of pulses, (N pulses and then stop). (attached I send a figure to illustrate my question)
    Please, I tried to understand the triggers but....
    If the triggers is the solution for my probl
    em please send me an example.
    Note: Now I'm generating a sequence of pulses using a simple pin I/O of the Goeppel Board but the problem is if I run many Labview applications sometimes the software is not fast enough to generate that pulses. Then I think if I use a hardware solution, like in the 5401 board,I could get faster a better responses for my pulses. Note that I'll need to now, in each instant, how is the level of each pulse.
    Note2:I'm using LabView6i software.
    Thanks very much.
    Attachments:
    PULSE.jpg ‏25 KB

    Hi
    The NI 5401 is a Function Generator; this is significant in that it is made to make periodic waveforms such as Sine, Square, and even a user defined periodic waveform that a user can download (the 16K buffer). The board can be triggered to start generation, and with a software call, abort generation. But there is no hardware that can specify how many cycles of a waveform has been generated to control the number of cycles at the output.
    Depending on the rate of the pulses you need, it may be possible to do something. A pulse train is essentially a square wave with a certain duty cycle. Set up the device for a certain frequency that matches the rate of your pulses, and program it to start with a Software trigger. The best output to use is the Sync output which w
    ill give you a TTL pulse.
    After the software trigger is called in your code, use the Wait VI to wait a certain amount of time that corresponds to the number of cycles/pulses for the signal that you need, and then after the wait, immediately call NI-FGEN Abort to stop the output generation.
    If you are unable to control the number of pulses through software, the NI 5401 really isn't made for this operation. The NI 5411 Arbitrary Waveform Generator is the device made to do this, create the pulse waveform you need, select how many times you want it to "loop", and then generate a waveform of zero volts. The NI 5411 has the hardware to count number of loops, and trigger, etc.
    I hope this helps.
    Jerry

  • How to generate n random dates

    Can anyone help me in generating Random dates, i want to generate 100 random dates in yyyy-mm-dd format.

    I've tried this, but will appreciate any neat solutions...
    public static void main(String arg[]) {
        int no = 0;
        while (no < 100) {
          // Year
          int yylower = 1970; // your lower integer value
          int yyupper = 2000; // the larger one of your two integers
          double rand = Math.random();
          int yyresult = yylower + (int) ( (yyupper - yylower) * rand);
          // Month
          int mmlower = 1; // your lower integer value
          int mmupper = 12; // the larger one of your two integers
          rand = Math.random();
          int mmresult = mmlower + (int) ( (mmupper - mmlower) * rand);
          // Month
          int ddlower = 1; // your lower integer value
          int ddupper = 29; // the larger one of your two integers
          rand = Math.random();
          int ddresult = ddlower + (int) ( (ddupper - ddlower) * rand);
          System.out.println(yyresult  + "-" + mmresult + "-" + ddresult);
          no++;
      }

  • How to generate n random dates between 2 time periods

    Hi,
    I'm trying to write a method that generates n random dates between 2
    time periods. For example, lets say I want to generate n random dates
    between Jan 1 2003 and Jan 15 2003. I'm not sure how to go about
    doing the random date generation. Can someone provide some direction
    on how to do this?
    The method signature should look like this.
    public String[] generateRandomDates(String date1,String date2,int n){
    // date1 and date2 come in the format of mmddyyyyhh24miss.
    // n is the number of random dates to generate.
    return dateArray;
    Thanks.
    Peter

    first take a look at the API concerning a source of randomness (Random might be a good guess), then take a look at stuff concerning dates (Date might be cool, maybe you will find some links from there).
    Who wrote this stupid assignment?

  • Urgent How to generate a random code such as registration code?

    I would like to ask that how to generate a random code?
    For example, when you register a E-mail account, you need to enter the code for activation. I would like to create a java Bean to do this job. Would you help me?

    In fact, I would like to set a 10 digi codes randomly (such as FH654CS081, MKO624VG9f) for user input when they register the forum account. This random code will be sent to the user's email. User have to input this code to a JSP web site. Also, the code which is inputed by user will be matched with the database. If user input success, the forum account will be activated.
    By generating this 10 digi codes, I want to handle this generation by using java bean.
    1) Any thing else i need to import ? (such as <% page import="java.......?")
    2) Any functions can handle this task?
    3) Any example can be my reference?
    Thank you very much

  • Overriding method to generate a random radius

    So I'm working on this small homework assignment for my Computer Science course. What I'm supposed to be doing here is overriding my drawCircle to provide a radius for my circle between 10 - 100. Anyway I've figured out some of what I need, but I'm having an issue generating the random number. Any insight would be helpful.
    public class MyCircle {
        public MyCircle(){
        double radius;
    // == Page 365, EX 6.6
        public void drawCircle(Graphics g, int x, int y, int radius, Color color){
            int x1 = x - radius;
            int y1 = y - radius;
            int side = 2 * radius;
            g.setColor(color);
            g.drawOval(x, y, side, side);
       // == Page 365, EX 6.7
        public void drawCircle(Graphics g, int x, int y, int radius){
            //int x1 = x - radius;
            //int y1 = y - radius;
            //int side = 2 * radius;
            //g.setColor(Color.green);
            //g.drawOval(x, y, side, side);
            drawCircle(g, x, y, radius, Color.green);
        public void drawCircle(Graphics g, int x, int y){
            radius = (int)Math.random();
            int x1 = x - (int)radius;
            int y1 = y = (int)radius;
            int side = 2 * (int)radius;
            g.setColor(Color.WHITE);
            g.drawOval(x, y, side, side);
    }So as you can seeim using Math.radius to try and do this but it only provides a number between 0.0 and 1.0.

    Thanks for the input guys I got it to work, and it might be a little more then what I may have to do to get it to work, but its the only way I could figure it out at this point.
    public void drawCircle(Graphics g, int x, int y, Color color){
            // Creates a Random number generater that Generates values from 10 - 100
            Random generator = new Random();
            double radius = generator.nextDouble() * 60 + 10;
            int x1 = x - (int)radius;
            int y1 = y = (int)radius;
            int side = 2 * (int)radius;
            g.setColor(color);
            g.drawOval(x, y, side, side);
        }

  • How do I generate a random String

    Hi, there is probably a very simple answer to this question, but nevertheless....
    Is there a class I can use which will allow me to generate a random String of any length?
    Many thanks.

    depending on which chars you want to use for the String, sometimes it is more handy to use a char[], something like
    publc static final char[] CASE_SENSITIVE_ALPHNUM = {'a', ...., 'A',....'1',...};//for alphamumeric case sensitive chars
    public static final char[] CASE_INSENSITIVE_ALPH = {"a", ....,'z'};
    public String randString(int length, char[] charset) {
    StringBuffer sBuf = new StringBuffer();
    for (int i = 0; i < length; i++ ) {
    sBuf.append(charset[(int)(Math.random() * charset.length)] )
    return sBuf.toString();

  • Function to generate a random ID

    Hello all,
    Do we have any inbuilt function in SAP to generate a random alphanumeric ID?
    The requirement is such that there is an import parameter "Sales Rep ID" which is optional. So if the user is not providing the ID, then we have to randomly generate it ourselves. Hence I am looking for a FM which does that job.
    Regards,
    Abhishek

    look at the function modules in F052, rthere yiou can generate random value for any data type.
    RANDOM_AMOUNT
    RANDOM_C
    RANDOM_C_BY_SET
    RANDOM_F8
    RANDOM_I2
    RANDOM_I4
    RANDOM_INITIALIZE
    RANDOM_P
    RANDOM_TABLE_ENTRY

  • How to generate a random session variable in php

    i want to generate a random session variable and insert the variable in a mysql record to use later to validate an account set up.
    person fills out form to create account and submits; inserts form information in mysql record.
    i want the random variable to be inserted from a hidden field and the page sends an email with a link to click on to compare the variable to validate the user.
    Not sure how to generate a random session variable and get that to the hidden field value to be inserted with the other form information.
    thanks for your help,
    Jim Balthrop

    To insert the key I would personally do something like...
    $key = md5($username . $password . $salt);
    Insert that into your MySQL database, then send them a email with it, my next code shows how to activate it.
    This is to activate the account.
    <?php
    $key;
    $errors = array();
    if(isset($_GET['key']){
         $key = $_GET['key'];
         $sql = 'SELECT * FROM users WHERE key = \'' . $key '\' LIMIT 1';
         $result = mysql_query($sql) or die(mysql_error());
         if(mysql_num_rows($result)){
              $sql2 = 'UPDATE users SET active = 1 WHERE key = \'' . $key '\' LIMIT 1';
              $result2 = mysql_query($sql2) or die(mysql_error());
              if($result2){
                   //successfully activated account
              else{
                   //Something Went Wrong!
         else{
              $errors[] = 'Invaild Key, Please try again!';
    else{
         $errors[] = 'Invaild Key, Please try again!';
    ?>

  • Generating a random include file

    I'm trying to generate a random "include" file in an HTML web page. I have a group of 20 files, each with one sentence, and I'd like to randomly call one of those files into my web page, using a statement like
    <!--include virtual = "includes/file1.inc" -->
    Is there a way to use Javascript to generate that line of code, but make the number just before ".inc" be randomly entered?
    Thanks in advance.
    Bob

    Well, dynamically formed file name for include is not possible in javasript. Includes are processed before any javascript runs on the page.
    But
    You can do this if you keep the lines in the HTML file:
    <SCRIPT LANGUAGE="JavaScript">
    lines = new Array;
    lines[1] = "Well, some things in Javascript are not cool";
    lines[2] = "Sometimes Javascript is cool";
    lines[3] = "Ok, I am getting tired of typing now";
    lines[4] = "But then again, who is worried";
    lines[5] = "A random line can be shown";
    var total = 5;
    var randomNumber = Math.random();
    var idx = Math.round( (total-1) * randomNumber) + 1;
    document.write(lines[idx]);
    </SCRIPT>

  • How can you generate a random number?

    Say I have a timer, and I need it to choose a random number between 100 and 1000. How would I do that?
         timer.delay(***RANDOM***);Thanks!

    I have this, and it's working for me:
    int j = rand.nextInt(500);
    But I actually want it to generate a random number between 100 and 500, not 0 and 500. How could I do this?
    ~Dac

  • Generate a random number and make it STAY after "save"

    I searched around this forum and found that I can use this code to generate a random number:
    //this.rawValue = Math.round(Math.random() * 1000000);
    Works great. only problem is, once I practice on the "real" form and save, close, and reopen - it changes the random number every time. I need to figure out a way to make it save the 1st number it generates when someone opens the form and types info in it....then they save and close, etc.
    Can anyone help me? Thanks!!

    Example steps:
    1. Add a hidden field to the same subform with name 'hiddenField'.
    2. First time you open 'hiddenField' rawValue will be null.
    3. where ever you run the code to generate random number use scenario like this.
    if (hiddenField.isNull) {
    this.rawValue = Math.round(Math.random() * 1000000);
    }else {
    this.rawValue = hiddenField.rawValue;
    Hope this thelps.
    SekharN

Maybe you are looking for

  • HP LaserJet 500 color MFP M570dn ePrint information sheet won't print

    When I attempt to Enable Web Services Connect I receive a message that an information sheet will print that contains important information.  That information sheet doesn't print.  After selecting OK, there is another button on the right that says "Pr

  • HP LaserJet 200 Color M251NW

    Hey Yall, I've been searching and watching videos, but it seems like my problem is more complex than it should be. I just purchased a LaserJet 200 Color M251nw and I use a Macbook runnining on Mavericks OSx (10.9.2) Two-Sided Printing is why I purcha

  • Oracle BI: Right Choice?

    Hello, We are in process of revamping our reporting solution. We want to publish our reports over the internet with some graphics (charts, graphs, scales, meters, etc). Also want reports where business user can drill down into different level and als

  • Couldn't create temporary file.

    I have a 1TB drive in my Mac Pro running Mavericks 10.9.4 and I went to disk utility to erase some free space on the drive. However I keep getting the error message: Secure Erase Free Space failed Secure erase Free Space failed with the error: Couldn

  • How does one get rid of opaque strip?

    I cannot begin to express how much I hate this so-called "improvement". How does one rid the screen of the tiresome opaque strip at the bottom? As to the new icons, Apple seem to have employed an incompetent child to design them.