Selecting random from hashtable

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

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

Similar Messages

  • Selecting Randoms from Query of Queries

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

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

  • Selecting random values from an array based on a condition

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

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

  • How to randomly select data from excel using labview.

    A very good day to all. I am actually working on a system that will be selecting integer number from randomly generated set of number. If that wouldnt be possible, I would like the system to be able to select number from the set of numbers which have already been randomly generated from excel. kindly help me with the solution. To make myself clear, supposing I have set of numbers from 1 to 10, I want a labview setup that will be picking these numbers one after the other either with replacement or without from excel or self generated. I know this is possible in matlab but would prefer labview if possible.  Thanks
    Solved!
    Go to Solution.

    Most, if not all, of the languages I've run across have a rand() function that returns a random number between 0 and 1.  Getting some other range is up to the programmer.  Usual method is to multiply by the range you need and add an offset to adjust the mean.  For instance if you need a random number between 200 and 300 the formula might look like  " rand()*100+200 ".   If you need an integer, you can use the round function (which will leave it as a float with no decimal pportion) or the conversion (to int).    All of this is doable and straightforward in LabVIEW.  Have a look: http://digital.ni.com/public.nsf/allkb/FCCDCD678EEF3A9186256D7B008054F5
    If you feel more comfortable pulling from a file, try this: http://digital.ni.com/public.nsf/allkb/C944B961B59516208625755A005955F2 

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

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

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

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

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

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

  • How do I change the image used on an movie project icon? iMovie seems to select an image at random from the images I imported.

    How do I change the image used on an movie project icon?
    iMovie seems to select an image at random from the images I imported.

    Not sure I understand how to use what you have posted. Here's what my init() looks like:
    public void init()
    setLayout(new BorderLayout());
    p=new Panel();
    p.setLayout(new GridLayout(1,1));
    callnowButtonURL = getURL(callnowButtonFilename);
    if (callnowButtonURL != null)
    callIcon = new ImageIcon(callnowButtonURL,"call");
    endcallButtonURL = getURL(endcallButtonFilename);
    if (endcallButtonURL != null)
    endIcon = new ImageIcon(endcallButtonURL);
    b=new JButton(callIcon);
    b.setBorder(new EmptyBorder(0,0,0,0));
    b.setBorderPainted(false);
    b.addActionListener(this);
    p.add(b);
    add(p,"Center");
    Now the ActionListener is basically:
    public void actionPerformed(ActionEvent e)
    if (mybool == false)
    <Perform actions here set mybool to true>
    Change JButton b to use EndIcon
    else
    <Perform actions here set mybool to false>
    Change JButton b to use CallIcon
    Can you clarify how to perform the action I require? You can have a couple of Dukes if you can help me sort this out.

  • Select Random Rows in PL/SQL

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

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

  • Select Random Records with Group By?

    Hi,
    I currently select random records by using this type of SQL:
    (SELECT *
    FROM ( SELECT *
    FROM ( SELECT *
    FROM TABLEA
    ORDER BY dbms_random.value
    WHERE ROWNUM <= 100
    Based on the following data, I now want to still pick out random records but I only want 1 record from the same ID and START_DATE but where the FLAG could be Y or N.
    So with grouping by ID and START_DATE, I need to still be able to choose the record if it has anything from 1 entry or 10 entries per ID and START_DATE.
    Could this be performed with a GROUP BY?
    ID START_DATE FLAG
    1 12/12/2005 Y
    1 12/12/2005 N
    1 12/12/2005 N
    1 30/12/2005 Y
    1 30/12/2005 N
    1 30/12/2005 N
    2 10/10/2005 Y
    2 07/07/2005 Y
    Thanks for any help.
    Daniel

    Try this [not tested]:
    SELECT *
         FROM
              (SELECT *
                   FROM
                   ( SELECT
                              ID
                             ,START_DATE
                             ,FLAG
                             ,ROW_NUMBER() OVER
                                  (PARTITION BY ID,START_DATE ORDER BY dbms_random.value) RN
                        FROM TABLEA
                   ORDER BY dbms_random.value
         WHERE RN = 1
              AND ROWNUM <= 100
         ;

  • Photoshop file corruption (selections deleted from layers)

    I was working on 5 photoshop files today. Photoshop stared previewing one of the files very oddly (when you zoomed in nothing was there).
    I saved all open files and quit Photoshop.
    Upon opening Photoshop all files had random selections deleted from the layers (please see attached)
    I have basically lost a full days work.
    has anyone had anything similar??
    Photoshop CS5 version 12.0.2

    Yes, I have this corruption issue as well. For me, it is not reproducable (no specific action causes it that I have found), and intermittant (happens inconsistently but not infrequently, maybe once or twice a month out of hundreds of files and working hours). It seems like it more often happens in layer masks first, but once the corruption starts, it shows in layer image data as well. Often it looks blocky like you are seeing, and also as you mention, cached zoom levels don't show the corruption.
    I hesitate to call it corruption, but it seems to be the case—once it shows up in an open file, going back in history does NOT undo the corruption, and if you save, your image is screwed. Only way to avoid losing lots of work is to save often and close without saving when you notice corrution, then go back to where you were last time you saved. I have noticed that once you see corruption, you have to re-launch PS even if you close and re-open the file. Otherwise additional corruption will happen almost immediately.
    It smells like a RAM related issue, but it's the ONLY issue I have on any of the workstations I use where I've noticed the PS corruption issue, so if it's RAM corruption then it's something PS and only PS does to my RAM. I do a lot of heavy processing with large files, so if I had any bad RAM, I'm pretty sure I'd have noticed by now.
    I'm working on files over a local network (nearly always, all day every day). I've had the issue on multiple Macs, multiple OS versions, multiple versions of PS (since CS3, it seems like.) I do use more levels of undo that default but well within available range (100 undos--PS allows up to 1000). And my History & Cache settings are default.
    I'm glad to hear I'm not the only person with this issue. It would be nice to see it fixed.

  • BC4J smarter way to:   select sysdate from dual  ????

    Our architecture uses the DB server's date/time as the application's single
    place to get date / time. So our UI's / business logic needs sysdate in several
    places through screen flow and VO/Entities called by the business logic.
    I'll create a SQLView at design time to package calling select sysdate from dual.
    We're currently using Dynamic unnamed Views which are more expensive than just
    getting sysdate deserves and also are a memory leak if you don't
    call vo.remove() after you're done with the result set.
    But is there a simplier or smarter way to get sysdate from the DB than the more
    heavy weight than seems necessary step of instantiating a VO and creating a
    result set to get the String sysdate???
    Thanks,
    curt

    I cache viewObjects in the MT using some ViewObjectManager and had no
    problems till now (more then 6 months of production). Any AM that
    serve dynamic requests should have own ViewObjectManager-object.
    import oracle.jbo.*;
    import java.util.Hashtable;
    import java.util.Enumeration;
    public class ViewObjectManager {
    private ApplicationModule _appMod;
    private Hashtable _viewObjectNames;
    public ViewObjectManager(ApplicationModule am) {
    _appMod = am;
    _viewObjectNames = new Hashtable();
    public ViewObject getViewObject( String selectClause_,
    String fromClause_,
    String whereClause_ ) {
    ViewObject vo_ = null;
    String sqlStmt_ = _getSQLStmtFromClauses
    ( selectClause_, fromClause_, whereClause_ );
    String key_ = sqlStmt_;
    String voName_ = (String)_viewObjectNames.get(key_);
    boolean isNew_ = ( voName_ == null );
    if ( !isNew_ ) {
    vo_ = appMod.findViewObject(voName);
    if ( vo_ == null ) {
    viewObjectNames.remove(key);
    isNew_ = true;
    if ( isNew_ ) {
    vo_ = appMod.createViewObjectFromQueryStmt( null, sqlStmt );
    viewObjectNames.put( key, vo_.getName() );
    return vo_;
    private String getSQLStmtFromClauses( String selectClause,
    String fromClause_,
    String whereClause_ ) {
    return
    "SELECT "+selectClause_
    +" FROM "+fromClause_
    +( whereClause_ == null || whereClause_.equals("")
    ? "" : " WHERE "+whereClause_ ) ;
    Client method in this case looks like that:
    public static synchronized BigDecimal getNewId
    ( RequestOnNewId request__,
    QueryableApplicationModule am__ ) {
    String viewObjectName_ = request__.viewObjectName,
    sequenceName_ = request__.sequenceName,
    fromClause_ = request__.fromClause;
    BigDecimal new_id_ = null;
    ViewObject vo_;
    Row row_;
    Object obj_;
    vo_ = am__.getViewObjectManager()
    .getViewObject( sequenceName_+".NEXTVAL AS \"NEWID\"",
    "DUAL",
    null );
    vo_.executeQuery();
    row_ = vo_.first();
    obj_ = row_.getAttribute("NEWID");
    new_id_ = (obj_ == null) ? null : ((Number)obj_).bigDecimalValue();
    return new_id_;
    Hope this helps.
    Arkadi Ganov
    [email protected]

  • Selecting random records out of a table

    Hi,
    I guess this question isn't new, but I didn't found anything about this using the search of this forum.
    How can I get e.g. 5 random records out of a table?
    I have a small table, which stores the special offers of a shop. Let us say, there are 30 records in it. How can I fetch (e.g.) 5 random records of this table?
    I tried to use this statement in a loop:
    SELECT t_item_id FROM tbl_special_offers SAMPLE (1) WHERE ROWNUM = 1
    But this is a very small table, so most of the query returns no data. Additionally I have to check if this number was already selected and ignore it in this case. This isn't a good solution, is it?
    Can somebody help me out with a better solution? Thanks :)

    create or replace package shop_stuff
    is
       function random_number return number;
    end;
    create or replace package body shop_stuff
    is
       function random_number return number
       is
       begin
          return dbms_random.value;
       end;
    begin
       dbms_random.initialize (to_number(to_char(sysdate,'mmddsssss')));
    end;
    create table tbl_special_offers (t_item_id number);
    insert into tbl_special_offers values (1);
    insert into tbl_special_offers values (2);
    insert into tbl_special_offers values (3);
    insert into tbl_special_offers values (4);
    insert into tbl_special_offers values (5);
    insert into tbl_special_offers values (6);
    insert into tbl_special_offers values (7);
    insert into tbl_special_offers values (8);
    insert into tbl_special_offers values (9);
    insert into tbl_special_offers values (10);
    select t_item_id
      from (select t_item_id
              from tbl_special_offers
             order by shop_stuff.random_number)
    where rownum <= 5                       
    SQL> /
    T_ITEM_ID
             6
             7
             5
             4
            10
    SQL> /
    T_ITEM_ID
             1
             5
             3
             9
             6
    SQL> /
    T_ITEM_ID
             6
             5
             3
             2
            10
    SQL> /
    T_ITEM_ID
            10
             2
             8
             4
             1
    SQL>

  • Select random entity using JPA ql

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

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

  • Selecting Random notes for transform function

    Has anyone figured out a way to select 'random' notes? I have a series of guitar chords through out a song, and I want to randomly go in and shorten lengths so that every note has a different length.
    I have used 'humanize' and just alter lengths. I do several steps of varying strength. I've tried by selecting sub-divsion of beat. etc..
    But I couldn't figure out a way to only 'randomly select notes' to operate on.
    Anyone have any insight to offer?
    Thanx...

    As I said earlier, you can't do anything with the audio.
    MIDI, I used a system similar to yours. I was creating auto drummers, auto bass parts & chord players for live backing tracks. ( I think this was in Logic 4 - 7. It can be done in Logic 8, but I use MainStage for live work now.)
    The auto instruments created their own parts from a set of rules I gave each one. This meant that the backing tracks were always consistent in their feel, but never played a piece the same twice running. I did this as an experiment for several years with varying degrees of success. It was most successful with the George Shearing/Errol Garner styles of jazz harmony and with Latin & Afro/Latin rhythms. I had some useful results with Arab/Greek belly dance rhythms.
    They were created in the Environment with a complex series of delay loops, transformers & chord memorizers. They took quite a while to build & the results did not always justify the time spent. The drums were the most useful, but Ultrabeat can do a similar job for much less effort.

  • Error while selecting date from external table

    Hello all,
    I am getting the follwing error while selecting data from external table. Any idea why?
    SQL> CREATE TABLE SE2_EXT (SE_REF_NO VARCHAR2(255),
      2        SE_CUST_ID NUMBER(38),
      3        SE_TRAN_AMT_LCY FLOAT(126),
      4        SE_REVERSAL_MARKER VARCHAR2(255))
      5  ORGANIZATION EXTERNAL (
      6    TYPE ORACLE_LOADER
      7    DEFAULT DIRECTORY ext_tables
      8    ACCESS PARAMETERS (
      9      RECORDS DELIMITED BY NEWLINE
    10      FIELDS TERMINATED BY ','
    11      MISSING FIELD VALUES ARE NULL
    12      (
    13        country_code      CHAR(5),
    14        country_name      CHAR(50),
    15        country_language  CHAR(50)
    16      )
    17    )
    18    LOCATION ('SE2.csv')
    19  )
    20  PARALLEL 5
    21  REJECT LIMIT UNLIMITED;
    Table created.
    SQL> select * from se2_ext;
    SQL> select count(*) from se2_ext;
    select count(*) from se2_ext
    ERROR at line 1:
    ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    ORA-29400: data cartridge error
    KUP-04043: table column not found in external source: SE_REF_NO
    ORA-06512: at "SYS.ORACLE_LOADER", line 19

    It would appear that you external table definition and the external data file data do not match up. Post a few input records so someone can duplicate the problem and determine the fix.
    HTH -- Mark D Powell --

Maybe you are looking for

  • How Do I Share Music From My Mac to My Android Cellphone

    Got an Android LG Volt cell, anyone know how I can share music from my Mac to it? Every time I connect the phone by USB cable, it charges it, but the phone never shows up on the desktop or in finder. I can't figure out how to give it some music. Even

  • Problems with JSF&Tiles (displaying twice one inserted page in tiles)

    I'm using Tiles framework withih Dynamic Web Project in Websphere (WSAD 5.1.1), the project is based on JSF. - included tiles.jar in WEB-INF/lib directory - in web.xml defined servlet action as: <servlet>           <servlet-name>action</servlet-name>

  • Errors in the OLAP storage engine: A duplicate attribute key has been found when processing

    Hi dear MSDN Community, I am facing a problem while processing a cube with a customer hierarchy as follows: Global Account --> Main Customer --> Master Customer --> Customer The data comes from a flatted parent child table, that is, I create an extra

  • Iphone 4s keeps crashing....

    I recieved iPhone 4s for Christmas and it worked fine for about a month then it started rebooting randomly.  I tried factory restores, DFU and anything else (no it was not wet) and nothing worked.  I took the phone to Apple in early March and they re

  • Networking with Windows computers

    After over 20 years of working in IT support in the Microsoft world, I'm buying an iMAC for my home computer and ditching the Microsoft box. However, my wife will continue to use her Windows machine, at least on the short term. I currently have a sha