RE: Random number keys

I have a need to generate random number keys for a DB2/6000 database. I am
expecting 10000 new entries per day to the table and due to design
constraints need to use an eight digit key. Also for design reasons the key
on the database is an integer attribute. I have looked at the built in
random number generator and it only produces a 2 byte number - I need 4.
Does anyone have a handy routine to produce larger random numbers?
TIA
/\/\ark /\/ichols
"Focus on the QUESTION, not on the ANSWER."
Lee Wei of Forte contributed a demo called RandomSort to Vol 1. of
the FShare CDROM. This has some generation code based on the Sedgewick LC
algorithm that you could probably adapt to your purposes. (e.g. I generated
8-digit integer values by multiplying Lee Wei's default for MAX by 10).
You can fiddle with the thing to change the minimum end of the range.
Robert Sedgewick's Algorithms in C (Addison Wesley 1990) is useful to
have for this sort of amusement.
If you don't have access to the FShare 1 CDROM I could send you the
pex file.
Regards,
Stephen Porterfield
Longs

There is an excellent book written by Knuth about
Randon Numbers generator algorithms...
"The Art of Computer Programming, Donald E. Knuth" -- Vol 2, pp 1-170
Have a look at these other books if you want more info:
"Monte Carlo Simulations: Hidden Errors from 'Good' Random Number
Generators",Physical Review Letters, Alan M.
Ferrenberg, D. P. Landau, and Y. Joanna Wong, Vol 69 No. 23, Dec 7 1992
"Monkey Tests for Random Number Generators",Computers Mathematics
Applications, G Marsaglia, and A Zaman, Vol 26, No
9 1993, pp 1-10.
A Current View of Random Number Generators", Computer Science and
Statistics: 16th Sympossium on Interface, Elsevier,
1985.
Hope this helps,
--francois
From: Vasas, Marty
Sent: Thursday, April 10, 1997 8:31 AM
To: mark h. nichols; forte users
Subject: RE: Random number keys
16
Let's write 2 as twoToThe16th
If there's nothing built-in to do the job, write a method for the
following algorithm:
generate 2 two-byte integers, A and B, from the built-in random number
generator.
return A * twoToThe16th + B
From: mark h. nichols
Sent: Thursday, April 10, 1997 10:10 AM
To: forte users
Cc: vasasm; murthis
Subject: Random number keys
MCI Mail date/time: Thu Apr 10, 1997 7:25 am EST
Source date/time: Thu, 10 Apr 1997 06:37:17 -0500
I have a need to generate random number keys for a DB2/6000 database. I
am
expecting 10000 new entries per day to the table and due to design
constraints need to use an eight digit key. Also for design reasons the
key
on the database is an integer attribute. I have looked at the built in
random number generator and it only produces a 2 byte number - I need 4.
Does anyone have a handy routine to produce larger random numbers?
TIA
/\/\ark /\/ichols
"Focus on the QUESTION, not on the ANSWER."

Similar Messages

  • Random number keys

    I have a need to generate random number keys for a DB2/6000 database. I am
    expecting 10000 new entries per day to the table and due to design
    constraints need to use an eight digit key. Also for design reasons the key
    on the database is an integer attribute. I have looked at the built in
    random number generator and it only produces a 2 byte number - I need 4.
    Does anyone have a handy routine to produce larger random numbers?
    TIA
    /\/\ark /\/ichols
    "Focus on the QUESTION, not on the ANSWER."

    There is an excellent book written by Knuth about
    Randon Numbers generator algorithms...
    "The Art of Computer Programming, Donald E. Knuth" -- Vol 2, pp 1-170
    Have a look at these other books if you want more info:
    "Monte Carlo Simulations: Hidden Errors from 'Good' Random Number
    Generators",Physical Review Letters, Alan M.
    Ferrenberg, D. P. Landau, and Y. Joanna Wong, Vol 69 No. 23, Dec 7 1992
    "Monkey Tests for Random Number Generators",Computers Mathematics
    Applications, G Marsaglia, and A Zaman, Vol 26, No
    9 1993, pp 1-10.
    A Current View of Random Number Generators", Computer Science and
    Statistics: 16th Sympossium on Interface, Elsevier,
    1985.
    Hope this helps,
    --francois
    From: Vasas, Marty
    Sent: Thursday, April 10, 1997 8:31 AM
    To: mark h. nichols; forte users
    Subject: RE: Random number keys
    16
    Let's write 2 as twoToThe16th
    If there's nothing built-in to do the job, write a method for the
    following algorithm:
    generate 2 two-byte integers, A and B, from the built-in random number
    generator.
    return A * twoToThe16th + B
    From: mark h. nichols
    Sent: Thursday, April 10, 1997 10:10 AM
    To: forte users
    Cc: vasasm; murthis
    Subject: Random number keys
    MCI Mail date/time: Thu Apr 10, 1997 7:25 am EST
    Source date/time: Thu, 10 Apr 1997 06:37:17 -0500
    I have a need to generate random number keys for a DB2/6000 database. I
    am
    expecting 10000 new entries per day to the table and due to design
    constraints need to use an eight digit key. Also for design reasons the
    key
    on the database is an integer attribute. I have looked at the built in
    random number generator and it only produces a 2 byte number - I need 4.
    Does anyone have a handy routine to produce larger random numbers?
    TIA
    /\/\ark /\/ichols
    "Focus on the QUESTION, not on the ANSWER."

  • Random number Primary Key column

    Hi All
    I am trying to set up a method of stopping....better I explain
    A multipart form is filled out (anyone can access this form)
    using ADDT the only way I can get the info from pageto page is form1?id=id
    If person 1 fills out the form the default primary id = 1
    If person 2 fills out the form the default primary id = 2
    However if person 2 thinks, lets see what person 1's details are, he/she/it only has to change the ID to 1
    I thought to get around this a random number would be great.
    Does anyone know how I would set the primary key to a random number using ADDT
    I will try and work this out in the meantime.
    Cheers
    Laurence

    Hi Laurence,
    My first thought would be to go over this tutorial.
    Straight to tutorial:
    http://www.interaktonline.com/Documentation/MXKollection/076200_tutorialuserauthentication .htm
    All of the online documentation: (Keep in mind this was when ADDT was MXKollection) So if you encounter differences use your best judgment.
    http://www.interaktonline.com/Documentation/MXKollection/
    My thinking is...
    1. User goes to register, they fill out form 1 (email, name, etc).
    2. Values from form 1 get carried to form 2 (hidden values, session or post) then they fill out form 2. (Address, phone, etc).
    3. Completion of form 2 has 1 insert trigger to enter in all data from both forms.
    Basically at this point the user has entered all profile information and is waiting on confirmation email to accept membership.
    Then in the membership side they can edit their profile based on an total authentication system. Because if you don't have one in place users will always be able to manipulate your $_GET values to see other peoples data.

  • How to efficiently get hold of N randomly selected keys out of X?

    I am writing some benchmark programs for Coherence caches and would need a way to as efficently as possible get hold of a "fairly random" selection of N keys from the cache out of the total X keys (where X >> N).
    With "fairly random" I am in particular looking for a way to get keys somewhat uniformly spread over all partitions.
    First i tried picking the first N keys obtained when iterating the key-set but they all seemed to come from just a few partitions (perhaps iteration is performed partition by partition?). Next I tried some algortihms I have used in the past to pick random keys from in memory-map (where one basically iterate and if a randomly generated value between 0.0 and 1.0 exceed a percentage calculatwed as the factor N/X the key is included. This does work (one may occasionally need to iterate the map more than once) but is VERY slow since iterating the key-set of a large cache remotly is kind of expensive.
    All sugestions are warmly appreciated - the best would be solutions that do not require anything to be added to the pof-config (i.e. not rely on custome aggregators or invocables etc) - this because I would liek to be able to easilly use my benchmark as part of several applications without having to modify there configuration files!
    /Magnus
    Edited by: MagnusE on Aug 7, 2009 10:21 AM

    Hi Magnus,
    you can go the other way round:
    With key-association you can ensure that your request goes to the partition you want it to go. You just need to generate a reverse mapping array between partition ids and integer associated key values which are mapped to that partititon.
    You can use this method for it:
    public static int[] generateReverseAssociatedKeysForService(DistributedCacheService service) {
         KeyPartitioningStrategy keyPartitioningStrategy = service.getKeyPartitioningStrategy();
         int partitionCount = service.getPartitionCount();
         int[] reverseKeys = new int[partitionCount];
         int i=1;
         while (partitionCount > 0) {
              Integer associatedKey = new Integer(i);
              int partitionId = keyPartitioningStrategy.getKeyPartition(associatedKey);
              if (reverseKeys[partitionId] == 0) {
                   reverseKeys[partitionId] = i;
                   --partitionCount;
              ++i;
         return reverseKeys;
    }After this, you generate an equal amount of entries for each partitions with composite keys which implement key association in a way that it returns an integer which maps to your designated partition id to serve as your data. Alternatively you can sort an existing key-set into per-partition keysets.
    After this, you just generate evenly spread random numbers between 0 and (partitionCount - 1) (both inclusive) which random number you use as an index to the reverse map to get an associated key value. Then you can generate another random number if you have multiple keys within a partition, or choose a key from the per-partition keyset for that partition if you have a set of existing keys.
    This way you get keys which are as evenly spread between partitions as your random generator generating your associated key indexes is spread.
    Best regards,
    Robert
    Edited by: robvarga on Aug 7, 2009 11:55 AM
    Added some more ideas and method implementation.

  • How to define "leading" random number in Infoset fpr parallel processing

    Hello,
    in Bankanalyzer we use an Infoset which consists of a selection across 4 ODS tables to gather data.
    No matter which PACKNO fields we check or uncheck in the infoset definition screen (TA RSISET), the parallel frameworks always selects the same PACKNO field from one ODS table.
    Unfortunately, the table that is selected by the framework is not suitable, because our
    "leading" ODS table which holds most of our selection criteria is another one.
    How to "convince" the parallel framework to select our leading table for the specification
    of the PACKNO in addition (this would be times 20 faster due to better select options).
    We even tried to assign "alternate characteristics" to the packnos we do not liek to use,
    but it seems that note 999101 just fixes this for non-system-fields.
    But for the random number a diffrent form routine is used in /BA1/LF3_OBJ_INDEX_READF01
    fill_range_random instead of fill_range.
    Has anyone managed to assign the PACKNO of his choice to the infoset selection?
    How?
    Thanks in advance
    Volker

    Well, it is a bit more complicated
    ODS one, that the parallel framework selects for being the one to deliver the PACKNO
    is about equal in size (~120GB each) to ODS two which has two significant field which cuts down the
    amount of data to be retreived.
    Currently we execute the generated SQL in the best possible manner (by faking some stats )
    The problem is, that I'd like to have a Statement that has the PACKNO in the very same table.
    PACKNO is a generated random number esp. to be used for parallel processing.
    The job starts about 100 slaves
    Each slave gets a packet to be processed from the framework, which is internaly represented
    by a BETWEEN clause on this PACKNO. This is joined against ODS2 and then the selective fields
    can be compared resultin in 90% of the already fetched rowes can be discarded.
    Basicly it goes like
    select ...
    from
      ods1 T_00,
      ods2 T_01,
      ods3 T_02,
      ods4 T_03
    where
    ... some key equivalence join-conditions ...
    AND  T_00.PACKNO BETWEEN '000000' and '000050' -- very selective on T_00
    AND  T_01.TYPE = '202'  -- selective Value 10% on second table
    I'd trying to change this to
    AND  T_01.PACKNO BETWEEN '000000' and '000050'
    AND  T_01.TYPE = '202'  -- selective Value 10%
    so I can use a combined Index on T_01 (TYPE;PACKNO)
    This would be times 10 more selective on the driving table and due to the fact,
    that T_00 would be joined for just the rows I need, about a calculated time 20-30 faster.
    It really boosts when I do this in sqlplus
    Hope this clearyfies a bit.
    Problem is, that I can not change the code either for doing the
    build of the packets or the one that executes the application.
    I need to change the Inofset, so that the framework decides to build
    proper SQL with T_01.PACKNO instead of T_00.PACKNO.
    Thanks a lot
    Volker

  • How to generate a unique random number in a MySQL db

    I'm creating a volunteer and also a separate vendor application form for an airshow. The volunteer and vendor info is stored in separate tables in a MySQL db, one row per volunteer or vendor. There will be about 100 volunteers and 50 vendors. When the application is submitted it should immediately be printed by the applicant, then signed and mailed in. This past year we had problems with some people who didn't immediately print their application so I'd like to still give them the option to immediately print but also send them an e-mail with a link to their specific row in the MySQL db. I have an autoincrement field as the primary key for each table, but I think sending this key to the applicant in an e-mail would be too easy for them to guess another id and access other people's info.
    I'm thinking I should add a column to each table which would contain a unique random number and I would then send this key in the e-mail to the applicant. So, can anyone suggest a simple way to do this or suggest a better way of giving the applicant a way to access their own application and no-one elses after they have submitted their form?
    Thanks all.
    Tony Babb

    Thanks so much, that was very helpful. I added the code you suggested to create and display the random number - I called it "vollink" and that worked fine. Then I added the hidden field toward the bottom of the form - it shows at line 311 when I do a "View Source in Int Explorer and then tried adding the code to add it to the table and when I tested it failed with "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1" . The test version of the page is here www.hollisterairshow.com/volunteerapp2.php . The changes I made to add it to the table is shown below , I must be missing something blindingly obvious, if you could suggest a fix I'd really appreciate it. I did add the field to the MySQL table also.
    Thanks again
    Tony
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
      $insertSQL = sprintf("INSERT INTO volunteers (firstname, lastname, email, thursday, friday, saturday, sunday, monday, activity, talents, specialrequests, tshirt, phone, street, city, st, zip, updatedby, vollink) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, $s)",
                           GetSQLValueString($_POST['firstname'], "text"),
                           GetSQLValueString($_POST['lastname'], "text"),
                           GetSQLValueString($_POST['email'], "text"),
                           GetSQLValueString($_POST['thursday'], "text"),
                           GetSQLValueString($_POST['friday'], "text"),
                           GetSQLValueString($_POST['saturday'], "text"),
                           GetSQLValueString($_POST['sunday'], "text"),
                           GetSQLValueString($_POST['monday'], "text"),
                           GetSQLValueString($_POST['activity'], "text"),
                           GetSQLValueString($_POST['specialtalents'], "text"),
                           GetSQLValueString($_POST['specialrequests'], "text"),
                           GetSQLValueString($_POST['tshirt'], "text"),
                           GetSQLValueString($_POST['phone'], "text"),
                           GetSQLValueString($_POST['street'], "text"),
                           GetSQLValueString($_POST['city'], "text"),
                           GetSQLValueString($_POST['st'], "text"),
                           GetSQLValueString($_POST['zip'], "text"),
            GetSQLValueString($_POST['vollink'], "text"),
                           GetSQLValueString($_POST['lastname'], "text"));
      mysql_select_db($database_adminconnection, $adminconnection);
      $Result1 = mysql_query($insertSQL, $adminconnection) or die(mysql_error());

  • Keyboard Number Key and Directional Key Issues

    This is a problem with the keyboard number keys and the Plus Key on the number pad, the number keys at the top of the keyboard above the letters, and the  directional keys at the bottom of the keyboard next to the alt/ctrl keys.   When pressed they are malfunctioning as follows, and I am actually typing the result on the keyboard numbers or number pad keys to demonstrate the result. Keys at top of keyboard: Pressing the Dash Key: `1Pressing Number One:  `1Number 2 works finePressing Number 3 dims the screenPressing Number four: 54Pressing Number five: 54Pressing Number six: 67Pressing Number seven: 67Pressing Number eight:  \8Number 9 works finePressing Zero:  -0 Number Keypad: Pressing Number one: +1Number 2 works fineNumber 3 works finePressing Number four: 64Number 5 works finePressing Number six: 64Number 7 works fineNumber 8 works fineNumber 9 works fineNumber 0 works fine Keypad symbols: Pressing Plus Key:  +1 Directional Keys: Right Arrow Key:  Cursor moves up a random number of lines in a document.Left Arrow Key works fineUp Arrow Key works fineDown Arrow Key (inserts back slash):  \  I have searched and searched and have not been able to find a solution to this or even another post outlining this type of problem.  Please Help.    

    Hello there,
    It sounds like you're going to either need your keyboard replaced, or have the buttons fixed. You can either have this done professionally, or personally, since the warranty states that you're permitted to replace the keyboard. For more information on how to replace it, visit this pdf and scroll down to keyboard, under replacement. https://www.google.com/url?sa=t&source=web&rct=j&ei=4U2bVeSZOMSu-QGwtIuIBQ&url=http://h10032.www1.hp.com/ctg/Manual/c03935332&ved=0CCIQFjAB&usg=AFQjCNFI7Za3MTOYi3U2gqYwky_v2R-eIA&sig2=BEpyqWkFFkSjkR0z4r5v-Q
    I apologize for it being a Google link, since I am on mobile.
    Best Regards,
    Shawn

  • Random number issue

    I'm making a mobile game and I can't seem to generate a random number successfully
    Game.java:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class Game extends MIDlet implements CommandListener {
    private Display theDisplay;
    private GameCanvas canvas;
    private Player p1;
    private Block[] Grid;
    static final Command exitCommand = new Command("Exit", Command.STOP, 1);
    class Player {
      public int x, y;
      public int width=60, height=15;
      public Player(int curX, int curY) {
       x = curX;
       y = curY;
    public Game() {
      setupGrid(5, 8, 5);
      p1 = new Player(90, 250);
      theDisplay = Display.getDisplay(this);
    private void setupGrid(int rows, int cols, int cellspacing) {
      Grid = new Block[200];
      int ind = 0;
      int posX = 10;
      int posY = 20;
      int colPosY;
      int colPosX;
      colPosY = posY;
      colPosX = posX;
      for(int x = 0; x < rows; x++) {
       Grid[ind] = new Block(posX, posY);
       colPosY = posY;
       for(int y = 0; y < cols; y++) {
        ind++;
        colPosX += 20+cellspacing;
        colPosY = posY;
        Grid[ind] = new Block(colPosX, colPosY);
       colPosX = posX;
       posY += 15+cellspacing;
       ind++;
    class Block {
       public int x, y;
       public int Health;
       public int r = 0, g = 0, b = 0;
       public Block(int curX, int curY) {
       x = curX;
       y = curY;
       double rand = Math.random()*5;
       if(rand > 0 && rand < 2) {
        g = 255;
        r = 0;
        b = 0;
       if(rand > 2 && rand < 4) {
        r = 255;
        g = 0;
        b = 0;
       if(rand > 3 && rand < 5) {
        b = 255;
        g = 0;
        r = 0;
    class GameCanvas extends Canvas {
      private int width;
      private int height;
      GameCanvas() {
       width = getWidth();
       height = getHeight();
      public void paint(Graphics g) {
       g.setColor(0, 0, 0);
       g.fillRect(0, 0, width, height);
       g.setColor(100, 100, 100);
       g.fillRect(p1.x, p1.y, p1.width, p1.height);
       for(int x = 0; x < Grid.length; x++) {
        if(Grid[x] != null) {
         g.setColor(Grid[x].r, Grid[x].g, Grid[x].b);
         g.fillRect(Grid[x].x, Grid[x].y, 20, 10);
      public void keyPressed(int keyCode) {
       int key = getGameAction(keyCode);
       if(key == LEFT && p1.x > 0) {
        p1.x-=4;
       else if(key == RIGHT && p1.x < canvas.width-p1.width) {
        p1.x+=4;
       repaint();
    protected void startApp() throws MIDletStateChangeException {
      canvas = new GameCanvas();
      canvas.addCommand(exitCommand);
      canvas.setCommandListener(this);
      theDisplay.setCurrent(canvas);
    public void pauseApp() { }
    public void destroyApp(boolean unconditional) { }
    public void commandAction(Command c, Displayable d) {
      if(c == exitCommand) {
       destroyApp(false);
       notifyDestroyed();
    }Game.java:58: cannot find symbol
    symbol : method random()
    location: class java.lang.Math
    double rand = Math.random()*5;
    ^
    1 error
    Line 58:
    double rand = Math.random()*5;

    b1nary wrote:
    Unfortunately, no - it won't work. Prior to posting this thread I researched different ways to generate random numbers but, apparently, the WTK only allows certain packages to be recognized.You can always write your own generator. For portability I use
    * Uniform random number generator.
    * <p>
    * Based on
    * <blockquote>
    * <pre>
    * Efficient and Portable Combined Random Number Generators
    * <a href="http://www.iro.umontreal.ca/~lecuyer">Pierre L'Ecuyer</a>
    * Communications of the ACM
    * June 1988 Volume 31 Number 6
    * </pre>
    * </blockquote>
    * @author Sabre
    public class Ecuyer
         * Constructs the generator based on two starting seeds.
         * <p>
         * Two generators using the same pair of seeds will produce
         * exactly the same sequence of pseudo random numbers.
         * @param seed1 the starting seed.
         * @param seed2 the second starting seed.
        public Ecuyer(int seed1, int seed2)
            s1 = (seed1 > 0) ? seed1 : 1;
            s2 = (seed2 > 0) ? seed2 : 1;
         * Constructs the generator based on a starting seed.
         * <p>
         * Two generators using the same seeds will produce
         * exactly the same sequence of pseudo random numbers.
         * @param seed the starting seed.
        public Ecuyer(long seed)
            this((int) ((seed >> 32) & 0x7fffffff), (int) (seed & 0x7fffffff));
         * Constructs a generator using the current time as seed.
        public Ecuyer()
            this(System.currentTimeMillis());
         * Returns the next random number
         * @return the next random number
        public double nextValue()
                // m = 2147483563, a = 40014
                int k = s1 / q1;
                s1 = a1 * (s1 - k * q1) - k * r1;
                if (s1 < 0)
                    s1 += m1;
                // m = 2147483399, a = 40692
                int k = s2 / q2;
                s2 = a2 * (s2 - k * q2) - k * r2;
                if (s2 < 0)
                    s2 += m2;
            int z = s1 - s2;
            if (z < 0)
                z += m1;
            return z * 4.656613e-10;
        static final int m1 = 2147483563;
        static final int a1 = 40014;
        static final int q1 = 53668;
        static final int r1 = 12211;
        static final int m2 = 2147483399;
        static final int a2 = 40692;
        static final int q2 = 52774;
        static final int r2 = 3791;
        private int s1;
        private int s2;
    }Make sure you test it thoroughly before committing to it.

  • 17 digit random number

    I need to create a 17 digit random number to be used as a primary field in a database. They must all be unique. First, what is the best way to create a 17 digit random number, and second, how do I make sure it is unique?

    I have a servlet that is parsing an email distribution
    list and creating multiple users. For each user I
    need to create a user id in the form of
    "ID87890988909099900" that is unique. I do not know
    how I would get Access to do this for me.Wow, you must have a lot of users. There aren't that many ants on earth.
    Seriously, if the ID will always start with ID, then can't you just leave it off the key and add it when the ID is displayed?

  • 8900 only number keys are working on keyboard and symbols only showing numbers

    Hi All
    curve 8900 - I turned the handheld off last night and this morning only the number keys are working on keyboard and when I press symbols it only showing numbers. Did i press an unusual key combination? I tried taking battery out and restarting.
    Can anyone help me out?
    Best
    Kobi

    Hi and Welcome to the Forums!
    You did not state fully, so I cannot know if you did the battery pull properly (with power ON). Anytime random strange behavior or sluggishness creeps in, the first thing to do is a battery pop reboot. With power ON, remove the back cover and pull out the battery. Wait about a minute then replace the battery and cover. Power up and wait patiently through the long reboot -- ~5 minutes. See if things have returned to good operation. Like all computing devices, BB's suffer from memory leaks and such...with a hard reboot being the best cure.
    Best!
    Occam's Razor nearly always applies when troubleshooting technology issues!
    If anyone has been helpful to you, please show your appreciation by clicking the button inside of their post. Please click here and read, along with the threads to which it links, for helpful information to guide you as you proceed. I always recommend that you treat your BlackBerry like any other computing device, including using a regular backup schedule...click here for an article with instructions.
    Join our BBM Channels
    BSCF General Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • A simple question on random number generation?

    Hi,
    This is a rather simple question and shows my newbieness quite blatantly!
    I'm trying to generate a random number in a part of a test I have.
    So, I have a little method which looks like this:
    public int getRandomNumber(int number){
            Random random = new Random(number);
            return random.nextInt(number);
        }And in my code I do int random = getRandomNumber(blah)...where blah is always the same number.
    My problem is it always returns the same number. What am I missing here. I was under the impression that nextint(int n) was supposed to generate the number randomly!! Obviously I'm doing something wrong or not using the correct thing. Someone please point out my stupidity and point me in the right direction? Ta

    I think the idea is that Random will generate the same pseudo-random sequence over and over if you don't supply a seed value. (The better to debug with, my dear.) When you're ready to put an app into production, the seed value should be the current system time in milliseconds to guarantee a new sequence with each run.
    Do indeed move Random outside the loop. Think of it like a number factory - instantiate it once and let it pump out the random values for you as needed.

  • Magic mouse and number keys not working

    Last year, Wet Baloney had a problem:
    I have a first generation iMac with the wireless keyboard of that vintage and a new Magic Mouse.
    All of a sudden the keys on the numeric keypad part of the keyboard do not work. The number
    keys at the top do work.
    Also (all of a sudden) this computer is not detecting my wireless Magic Mouse. There is no battery
    problem. The mouse works fine with my MacBook Pro.
    Does anyone have any troubleshooting ideas ??
    While this question was not answered, Apple decided to archive it anyway so I'm reposting. I had this problem and my sysadmin wizard figured out what is happening. The solution is to open "System Preferences" --> "Universal Access" and select Mouse. Turn off "Mouse Keys". What I don't know is how that got turned on but it happened when I did a Mac OS update that came out around March 28, 2011. Anyway, that fixed both the mouse and the keypad problems. I'm posting so that someone doing the same search I did can find this answer.

    Thank You for this!! I was having problems using my Numeric keypad on a wired keyboard - when I used the number keys, the wireless magic mouse would lock up - the only way out was to Force Close the Application . . . Turning off "Mouse Keys" and hitting Shift > Clear turned everything back to normal.

  • How do I assign images to grid cells based on their random number value?

    Hello everyone!
         I need a good point (or shove) in the correct direction.
    Background
         I've created (with previous help from this forum) a 12 x 9 random number grid which cycles through the numbers 1 to 9 a total of twelve times each. I've then created a button which shuffles the current grid's cells each time it is clicked. I now want to use 9 images that I have imported as individual symbols into the library (I have given them each their own class titled "skin1," "skin2," ... "skin9") as cell labels or the equivalent. I have also set the images up as individual movie clips (using the .Sprite class as the extended base class but keeping the actual image class names in line with their object name, i.e. the "skin1" image is the "skin1.as" class).
    Question
         How do I assign these images to the grid cells based on their respective values (ranging from 1 to 9) and have them populate the grid each time I click the "shuffle" button? So for example, in my grid the numbers 1 through 9 randomly appear 12 times each. Every time the number 4 appears in a cell, I want it to be assigned to the image "skin4" (which is just a graphic that looks like a button and has a fancy number "4" printed on it). Below is a chunk of the code I am using to draw the grid cells with:
    // Creates a grid cell when called by generateGrid().
    private funciton drawCell(_numeral:int):Sprite
              This is the code I am currently implementing to populate the grids with (although I
              don't want to use text labels as I want to fill each grid with an image according
              to its numerical value (1 to 9).
         var _label:TextField = new TextField();
         _label.multiline = _label.wordWrap = false;
         _label.autoSize = "center";
         _label.text = String(_numeral);
         // Add numerical label to cell array.
         cellLabels.push(_label);
         var _s:Sprite = new Sprite();
         _s.graphics.lineStyle(2, 0x019000);
         _s.graphics.drawRect(30, 0, cellW, CellH);
         _s.addChild(_label);
         return _s;
         While the following isn't working code, it will hopefully demonstrate what I want to achieve inside this function so I don't have to use the above snippet for text labels:
         //This will "hopefully" create an array of all 9 images by calling their classes.      var _imageArray:Array = [skin1, skin2, skin3, skin4, skin5 , skin6, skin7, skin8, skin9];      // This is what I want to happen for each cell using the above image array:      for (i = 0; i < cells; i++)      {           if (_numeral == 1)           {                // Insert skin1 image for each instance of #1 in the grid.           }           if (_numeral == 2)           {                // Insert skin2 image for each instance of #2 in the grid.           }           ...           if (_numeral == 9)           {                // Insert skin9 image for each instance of #9 in the grid.           }      } 
         Again, I don't want to use text labels. I have a custom skin graphic that I want to go over each number on the grid based on its numerical value (1 to 9). Any help with this is much appreciated!

    kglad,
         Thank you for your help with this one. Using the code below, I have successfully populated my grid cells with the desired corresponding graphics. I noticed one thing though regarding my use of the shuffle button with this particular implementation: even though the numerical values residing in each cell get shuffled, the original images remain in the grid rather than being replaced by new ones. The first code snippet below is the revised cell drawing function including your help; the second snippet shows you my simple shuffle button function (where the problem lies, I think).
    Snippet #1:
         // Creates a grid cell when called by generateGrid().
         private function drawCell(_numeral:int):Sprite
              var _label:TextField = new TextField();
              _label.multiline = _label.wordWrap = false;
              _label.autoSize = "center";
              // Creates a label that represents the numerical value of the cell.
              cellLabels.push(_label);
              var _s:Sprite = new Sprite();
              _s.graphics.lineStyle(2, 0x019000);
              _s.graphics.drawRect(30, 0, cellW, cellH);
              // Physically adds the labels to the grid.
              _s.addChild(_label);
              // Assigns a graphic class to a cell based on its numerical value.
              var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
              // Undefined variable for holding graphic classes.
              var _image:* = new _classRef();
              // Lines the images up with the grid cells.
              _image.x = 30;
              // Physically adds a graphic on top of a cell label.
              _s.addChild(_image);
              return _s;
         So far so good (although I question needing text labels at all if they are just going to remain invisible underneath the images, but enough about that for now). This next part is the reason that the images won't shuffle with the cell values, I think.
    Snippet #2:
         // When shuffleButton is clicked, this event shuffles
         // the number array and fills the cellLabels with the new values.
         private function onButtonShuffleClick(e:MouseEvent):void
              // Shuffles the number array.
              shuffle(numbers);
              // Verifies the array has been shuffled.
              trace("After shuffle:", numbers);
              // Loop replaces old cellLabels with new number array values.
              for (var i:int = 0; i < cells; i++)
                   cellLabels[i].text = String(numbers[i]);
         As you can see, it never replaces the original images that populate the grid. I tried using the _s.removeChild(image) function but that didn't work, nor would copying/pasting some of the code from snippet #1 directly into this function as it would cause another instance of the images to be placed over top of the existing ones rather than actually swapping them out. Any continued help here is greatly appreciated!
         PS Is there a quicker method for posting code into these forums without having to type it all out by hand again (i.e. copy/paste or drag/drop from my .fla or Notepad file directly into this thread)?

  • What algorithm does Excel 2010 use for Pseudo Random Number Generation (MT19937?)

    Does Excel 2010+ use the Mersenne Twister (MT19937) algorithm for Pseudo Random Number Generation (PRNG), implemented by the RAND() function?
    This has been a nagging question for some time now, with "hints" that it indeed does.  However, a relatively thorough search turns up no definitive documentation.  The most direct indication is perhaps given by Guy Melard [Ref 9] where
    he tests Excel 2010's RAND() function using the Crush battery of tests in TestU01 by L'Ecuyer & Simard.  Melard references a "semi-official" indication that Microsoft did indeed implement MT19937 for the RAND() function in
    Excel 2010, but this reference no longer seems to be available. http://office.microsoft.com/enus/excel-help/about-solver-HP005198368.aspx?pid=CH010004571033.
    The other references below [Ref 1-10] document the history of the statistical suitability of the PRNG and probability distributions in various versions of Excel.  This includes the Wichmann-Hill PRNG implementations supposedly (arguably) used in
    Excel 2003 & 2007 for random number generation.  But still, we have no answer as to which PRNG algorithm is used in
    Excel 2010 (and 2013 for that matter).
    Microsoft indicates that RAND() has been improved in Excel 2010; Microsoft states, "...and the RAND function now uses a new random number algorithm." (see https://support.office.com/en-ca/article/Whats-New-Changes-made-to-Excel-functions-355d08c8-8358-4ecb-b6eb-e2e443e98aac). 
    But no details are given on the actual algorithm.  This is critical for Monte Carlo methods and many other applications.
    Any help would be much appreciated. Thanks.
    [Ref 1] B. McCullough, B. Wilson.  On the Accuracy of Statistical Procedures in Microsoft Excel 97. 
    Computational Statistics & Data Analysis. Vol. 31 No. 1, pp 27-37. July 1999.
    http://users.df.uba.ar/cobelli/LaboratoriosBasicos/excel97.pdf
    [Ref 2]L. Knüsel.  On the accuracy of the statistical distributions in Microsoft Excel 97. Computational Statistics & Data Analysis. Vol. 26 No. 3, pp 375-377. January 1998.
    http://www.sciencedirect.com/science/article/pii/S0167947397817562
    [Ref 3]B. McCullough, B. Wilson.  On the Accuracy of Statistical Procedures in Microsoft Excel 2000 and Excel XP. 
    Computational Statistics & Data Analysis. Vol.40 No. 4, pp 713-721. October 2002.
    https://www.researchgate.net/publication/222672996_On_the_accuracy_of_statistical_procedures_in_Microsoft_Excel_2000_and_Excel_XP/links/00b4951c314aac4702000000.pdf
    [Ref 4] B. McCullough, B. Wilson.  On the Accuracy of Statistical Procedures in Microsoft Excel 2003. 
    Computational Statistics & Data Analysis. Vol.49. No. 4, pp 1244-1252. June 2005.
    http://www.pucrs.br/famat/viali/tic_literatura/artigos/planilhas/msexcel.pdf
    [Ref 5] L. Knüsel. On the accuracy of statistical distributions in Microsoft Excel 2003. Computational Statistics & Data Analysis, Vol. 48, No. 3, pp 445-449. March 2005.
    http://www.sciencedirect.com/science/article/pii/S0167947304000337
    [Ref 6]B. McCullough, D.Heiser.  On the Accuracy of Statistical Procedures in Microsoft Excel 2007. 
    Computational Statistics & Data Analysis. Vol.52. No. 10, pp 4570-4578. June 2008.
    http://users.df.uba.ar/mricci/F1ByG2013/excel2007.pdf
    [Ref 7] A. Yalta. The Accuracy of Statistical Distributions in Microsoft<sup>®</sup> Excel 2007. Computational Statistics & Data Anlaysis. Vol. 52 No. 10, pp 4579 – 4586. June 2008.
    http://www.sciencedirect.com/science/article/pii/S0167947308001618
    [Ref 8] B. McCullough.  Microsoft Excel’s ‘Not The Wichmann-Hill’ Random Number Generators. Computational Statistics and Data Analysis. Vol.52. No. 10, pp 4587-4593. June 2008.
    http://www.sciencedirect.com/science/article/pii/S016794730800162X
    [Ref 9] G. Melard.  On the Accuracy of Statistical Procedures in Microsoft Excel 2010. Computational Statistics. Vol.29 No. 5, pp 1095-1128. October 2014.
    http://homepages.ulb.ac.be/~gmelard/rech/gmelard_csda23.pdf
    [Ref 10] L. Knüsel.  On the Accuracy of Statistical Distributions in Microsoft Excel 2010. Department of Statistics - University of Munich, Germany.
    http://www.csdassn.org/software_reports/excel2011.pdf

    I found the same KB article:
    https://support.microsoft.com/en-us/kb/828795
    This was introduced (according to the article) in Excel 2003. Perhaps the references in notes 2 and 3 might help.
    The article describes combining the results of 3 generators, each similar to a Multiply With Carry (MWC) generator, but with zero carry. MWC generators do very well on the Diehard battery of randomness tests (mentioned in your references), and have
    very long periods. But using zero carry makes no sense to me.
    Combining the three generators only helps if the periods of the 3 are relatively prime (despite what the article implies). Then the period of the result will be the product of the 3 periods. But without knowing the theory behind these generators, I have
    no idea what the periods would be. The formulas for MWC generators fail here.
    Richard Mueller - MVP Directory Services

  • How to get a random number in a range?

    as title
    how to get a random number in a range?
    like 2000~3000 thks :)

    int between 10 and 20 with the method Math.random():
    public class Rnd
         // Test
         public static void main(String[] args)
             int start=10, end = 30;
             for (int i = 0; i < 10; i++)
                int n = (int)(start + Math.random() * (end-start));
                System.out.println(n);
    }best regards.

Maybe you are looking for

  • New SSD in T430, Windows not loading, tried everything...

    Hi there, I bought a T430 about a week ago. I'm not completely inept with computers: I successfully added another 4GB of RAM with no problems. Then I wanted to replace my HDD with my SSD. I know the SSD works because it was in another laptop. I put i

  • How to Update ECC when there is error in Receiver channel

    Hello Experts, I have a query like how to inform ECC when there is a error in Receiver channe.My interface is ABAP PROXY to JDBC in ECC moni message is through in PI moni also message is through but in Receiver JDBC Channel is in error saying for a p

  • Is there a TLOG? What's wrong?

    Hi, How can I find out if my application has a TLOG device configured. In the dmconfig I see that the parameter DMTLOGDEV is set. Often I see this following error in the ULOG - LIBGWT_CAT:1042: ERROR: Can't open domain log What could be going on? Wil

  • How can I import svg files into photoshop?

    I am trying to import some svg files into photoshop shapes, how is that done?

  • Disabling Accounts

    Hello all, As users move through the deprovisioning process, we have several stages we wish there accounts to go through. First we want to flag users as non-affiliatied with our organization. This will start a clock and they will have a window of tim