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

Similar Messages

  • Get value from the array based on the HashCode

    public static void runJoin(int[][] t1,int[][] t2)
         PrintWriter out=null;
         int rows = 1000;
         int cols = 7;
         int [][] myTable3 = new int[rows][cols];
         int x = 0;
         System.out.print("Running HashJoin:Method loads the "+
         "smaller table in the memory and applies a hashing function "+
         "to common column and stores it in another table. "+
         "The larger table is then read from the file. "+
         "The same hashing function is applied to Col n of the table and a       matching record in the first table is looked up. A match will create a row in Table 3. ");          
    //Apply hashing function to smaller table and store it in the memory.
              Integer[] It2 = new Integer[t2.length];
              int [] hashCodest2 = new int[t2.length];
              Hashtable ht = new Hashtable();
              for(int i =0; i <t2.length;i++){
                   It2[i] = new Integer(t2[0]);
                   hashCodest2[i] = It2[i].hashCode();
                   ht.put(new Integer(hashCodest2[i]),It2[i]);
              //Larger table get hashcodes
              Integer It1[] = new Integer[t2.length];
              int [] hashCodest1 = new int[t2.length];          
              for(int j =0; j <t1.length;j++){
                   It1[j] = new Integer(t1[j][4]);
                   hashCodest1[j] = It1[j].hashCode();               }
              //Based on the hashcode get the value from the Table2;
              try{
    out = new PrintWriter( new FileOutputStream( "c:\\HashJoinTable.txt" ) );
              Enumeration e = ht.keys();
                   while(e.hasMoreElements())
    //How do I get the value from the array based on the HashCode? Do I need to do a loop here???                         
    hashCodes1.get(e.nextElement());           
              }catch(Exception e){}

    ok I got it......
              //Apply hashing function to smaller table and store it in the memory.
              Integer[] It2 = new Integer[t2.length];
              int [] hashCodest2 = new int[t2.length];
              Hashtable ht = new Hashtable();
              for(int i =0; i <t2.length;i++){
                   It2[i] = new Integer(t2[0]);
                   hashCodest2[i] = It2[i].hashCode();
                   ht.put(new Integer(hashCodest2[i]),It2[i]);
              //Larger table get hashcodes and compare
              Integer It1[] = new Integer[t2.length];
              int [] hashCodest1 = new int[t2.length];          
              Hashtable ht2 = new Hashtable();
              for(int j =0; j <t1.length;j++){
                   It1[j] = new Integer(t1[j][4]);
                   hashCodest1[j] = It1[j].hashCode();               
                   ht2.put(new Integer(hashCodest1[j]),It1[j]);
              //Based on the hashcode get the value from the Table2;
              try{
    out = new PrintWriter( new FileOutputStream( "c:\\HashJoinTable.txt" ) );
              Enumeration e = ht.keys();
              Integer t3[] = new Integer[t2.length];
                   while(e.hasMoreElements())
                        t3[x] = (Integer) ht2.get(e.nextElement());                
                        x++;
              }catch(Exception e){}

  • Trying to get a value from 1 array based off the ID in another

    Something like this.
    rankGrade = model.rankArray.RANKABBRIVIATION where
    model.rankArray.RANKGRADEID = model.student.RANKGRADEID
    Any suggestions?

    You could use associative arrays, or even better to use XML
    with e4x syntax. See these FB3 help topics:
    Associative arrays
    The E4X approach to XML processing
    myXML.item.(menuName=="small fries").@quantity = "2";

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

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

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

  • Get distinct values from plsql array

    Hi,
    I have declared a variable as below in plsql proc.
    type t_itemid is table of varchar2(10);
    inserted set of items in to this using a program
    now i want distinct values from that array how can i get it.

    I am using 9i so i cannot use set operator and more over my problem is that i am declaring the variable inside the plsql block . when i tried i am getting the below errors:
    SQL> r
    1 declare
    2 type t_type is table of varchar2(10);
    3 v_type t_type;
    4 begin
    5 v_type := t_type('toys','story','good','good','toys','story','dupe','dupe');
    6 for i in (select column_value from table(v_type)) loop
    7 dbms_output.put_line(i.column_value);
    8 end loop;
    9* end;
    for i in (select column_value from table(v_type)) loop
    ERROR at line 6:
    ORA-06550: line 6, column 41:
    PLS-00642: local collection types not allowed in SQL statements
    ORA-06550: line 6, column 35:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    ORA-06550: line 6, column 10:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 7, column 22:
    PLS-00364: loop index variable 'I' use is invalid
    ORA-06550: line 7, column 1:
    PL/SQL: Statement ignored

  • How can i get the random values from database?

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

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

  • How to Select a value from DropDownByIndex -Urgent

    Hi All,
    I have dropdownbyindex UI elements in my Views, I get values from BAPI. When click records in a table, It goes to another view to display full record. Here i have dropdownbyIndexes So it should select one of appropriate value in dropdownbyindex based on record(Value) in table.
    Example:
    <u><i><b>In Table View</b></i></u>
    id                  title                 status          priority
    10000      webDynPro            New              Low
    <i><u><b>Detail View:</b></u></i>
    id                   10000
    title                 webDynPro
    Status             New                  [New,Old,Open,Closed]---DropDownbyIndex
    Priority            Low                   [High,Low,Medium]---DropDownByIndex..4m BAPI
    How to select Appropriate Values from DropdownbyIndex. if any one has sample code, that will be helpful.
    Note: I am using Model Nodes
    Thanks and Regards
    Ravi Golla

    Hi Ravi,
    In details view, you will have corresponding context node created for Status and priority dropdown fields.
    Let suppose, context node for Status is, StatusNode.
    value attribute inside this is,
    StatusNode
      |_ StatusAttrib
    Now, you need to write following code to set l_status ="LOW" value in it.
    wdContext.nodeStatusNode().moveFirst();
    for(int i=0; i<wdContext.nodeStatusNode().size(); i++)
        if(wdcontext.currentStatusNodeElement().getStatusAttrib().equals(l_status)
              wdContext.nodeStatusNode().setLeadselection(i);
              break;
    wdContext.nodeStatusNode().moveNext();
    write same code for priority also.
    Let me know if it is not working with you.
    regards,
    Bhavik

  • Finding the smallest value from an array

    Hi there :)
    I started learning Java a few days ago and have now run into my first problem :p
    I am using Netbeans on Mac OS X.
    I need to find the smallest value from an array. So far I've had no luck. Any suggestions would be fantastic.
    The code so far:
    * Math Problems
    * Created on May 4, 2007, 10:54 AM
    * PROJECT 1: - IN PROGRESS
    * Create a program that allows you to create an integer array of 18 elements with the following values
    * 3, 2, 4, 5, 6, 4, 5, 7, 3, 2, 3, 4, 7, 1, 2, 0, 0, 0
    *  - The program computes the sum of elements 0 to 14 and stores it in element 15                              // COMPLETED
    *  - The program computes the average and stores it in element 16                                              // COMPLETED
    *  - The program finds the smallest value from the array and stores it in element 17
    * PROJECT 2: - TO DO
    * Write a program that accepts from the command line and prints them out. Then use a for loop to print
    * the next 13 numbers in the sequence where each number is the sum of the previous two. FOR EXAMPLE:
    *  - input>java prob2 1 3
    *  - output>1 3 4 7 11 18 29 47 76 123 322 521 843 1364
    * PROJECT 3: - TO DO
    * Write a program that accepts from the command line two numbers in the range from 1 to 40. It then
    * compares these numbers against a single dimension array of five integer elements ranging in value
    * from 1 to 40. The program displays the message BINGO if the two inputted values are found in the array
    * element. FOR EXAMPLE:
    *  - input>java prob3 3 29
    *  - output>Your first number was 3
    *  -        Your second number was 29
    *  -        Its Bingo!  // This message if 3 and 29 are found in the array
    *  -        Bokya!      // This message if 3 and 29 are not found in the array
    *  -        The array was 7 5 25 5 19 30
    * PROJECT 3 EXTENSION: - OPTIONAL
    * Generate the array of 5 unique integers using random numbers
    package mathproblems;
    * @author Mohammad Ali
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
        public static void main(String[] args) {
            int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0};
            int O = A.length - 3;
            int B = A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] + A[9] + A[10] + A[11] + A[12] + A[13] + A[14];
            A[15] = B;  // Stores the sum of the integers in A[15]
            int C = B / O;
            A[16] = C;  // Computes and stores the average in A[16]
            int D = 101;
                if (A[0] < A[1]) { D = A[0]; }
                else { D = A[1]; }
                if (A[1] < A[2]) { D = A[1]; }
                else { D = A[2]; }
            System.out.println("There are " + O + " numbers in the Array");
            System.out.println("Those numbers add up to " + B + ".");
            System.out.println("The average of those numbers is " + C + ".");
            System.out.println("The smallest value in the array is " + D + ".");
    }The code is incomplete, but it works so far. The problem is I know there must be an easier way. SAVE ME :)

    OK :)
    Just thought I should show you the output as to help anyone else with the same problem:
    * Math Problems
    * Created on May 4, 2007, 10:54 AM
    * PROJECT 1: - IN PROGRESS
    * Create a program that allows you to create an integer array of 18 elements with the following values
    * 3, 2, 4, 5, 6, 4, 5, 7, 3, 2, 3, 4, 7, 1, 2, 0, 0, 0
    *  - The program computes the sum of elements 0 to 14 and stores it in element 15                              // COMPLETED
    *  - The program computes the average and stores it in element 16                                              // COMPLETED
    *  - The program finds the smallest value from the array and stores it in element 17                           // COMPLETED
    * PROJECT 2: - TO DO
    * Write a program that accepts from the command line and prints them out. Then use a for loop to print
    * the next 13 numbers in the sequence where each number is the sum of the previous two. FOR EXAMPLE:
    *  - input>java prob2 1 3
    *  - output>1 3 4 7 11 18 29 47 76 123 322 521 843 1364
    * PROJECT 3: - TO DO
    * Write a program that accepts from the command line two numbers in the range from 1 to 40. It then
    * compares these numbers against a single dimension array of five integer elements ranging in value
    * from 1 to 40. The program displays the message BINGO if the two inputted values are found in the array
    * element. FOR EXAMPLE:
    *  - input>java prob3 3 29
    *  - output>Your first number was 3
    *  -        Your second number was 29
    *  -        Its Bingo!  // This message if 3 and 29 are found in the array
    *  -        Bokya!      // This message if 3 and 29 are not found in the array
    *  -        The array was 7 5 25 5 19 30
    * PROJECT 3 EXTENSION: - OPTIONAL
    * Generate the array of 5 unique integers using random numbers
    package mathproblems;
    * @author Mohammad Ali
    import java.util.Arrays;
    public class Main { 
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
         public static void main(String[] args) {
                  int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0};
              Arrays.sort(A);
              System.out.println("The smallest value in the array is " + A[0] + ".");
              int num = A.length;
              System.out.println("There are " + num + " values in the Array.");
              int sum = 0;
              for (int i = 0; i < A.length; i++) {
                   sum+=A;
              System.out.println("Those numbers add up to " + sum + ".");
              double d = (double)sum/num;
              System.out.println("The average value of those numbers is " + d + ".");
    What Iearned:
    1) How to create for loops properly
    2) How to import java.util.Arrays ( =D )
    3) How to get a more accurate average using double instead of int
    4) This forum is the best and has very helpful people 24/7 ( =D)
    Thanks Again,
    Mo.

  • 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.

  • I have created a PDF form with multiple drop downs, all with the same drop down values. When I select a value from 1 of the drop down fields, it replicates in all of the others - which I do not want. How can I fix this?

    I have created a PDF form with multiple drop downs, all with the same drop down values. When I select a value from 1 of the drop down fields, it replicates in all of the others - which I do not want. Can I fix this?

    I'm fairly new to this, but I think it has to do with the way you have the drop downs named. Did you copy one then keep pasting it in each field? If so, that is the problem. You should rename each one with a different number: Dropdown1, Dropdown2, etc. I think that might solve the issue.

  • Selecting multiple values from a search help

    Hi Experts
    Anyone knows if it is possible to select multiple values from a search help?
    Thanks
    Gaurav

    Hi,
    You cannot select mutiple values from search help as it is linked to inputfield and hence it will accept single value only. But at the same time, you may able to pass row of values to different inputfields.
    Refer http://help.sap.com/saphelp_dm40/helpdata/en/3d/e53642e2a3ab04e10000000a1550b0/content.htm
    Thanks,
    Chandra

  • How to select multiple values from a listbox

    Hi,
    I have a list box on my UI which is not allowing me to select multiple values
    I want to use multi select list box .. When i go to source of UI component and change that to select many listbox my page is not rendering it is giving error
    When i drag & drop the component i am unable to drop it as a multi select list box that option is not coming.
    I am working on Jdev 11.1.1.3 and I am using ADF/BC components
    How to select multiple values from a listbox ?
    Thanks,

    Hi,
    I want to use multi select list box .. When i go to source of UI component and change that to select many listbox my page is not rendering it is giving errorank
    And what is the error ?
    Frank

  • How to select several values from a user exit variable in a planning folder

    Hello,
    I have created a user exit variable for limiting the values only to which the user need to access.
    For a simulation part, it is then necessary for him to select several values from these values (not only one, and not all)
    But It seems in this case the user has only two possibilities :
    - keep all the values without any restriction
    - restrain the selection to only one value.
    It seems possible for the user to access to a multiple choice window, but this possibility doesn't seems to work : in all tests we did, only the first value was taken into account by BPS.
    If this method is not good do you know an other manner to permit the user to choice several values amongst a set of pre-selected  (because the original set is too important) values ?
    Thanks for your help.

    Hi Mayank,
    Thanks for your response, but I don't think it corresponds to my problem.
    I my case, I use a user exit variable to filter some data. It seems BPS offers the possibility to the user to select several values amongts the pre-selected values presented by the user exit variable, but it doesn't work. We can use a popup in which we enters the required values, but in final, only the first value is taken into account.
    I don't know if it is due to a BPS bug or if it is not a good solution in regard to BPS philosophy. In this case, the concerned caracteristic isn't in the header but in lead columns.
    I must present a solution to my client next monday, so I have not enough time to open an OSS message.
    An alternate solution should be interesting too.
    My need is to present to a user a selection of values amongst all values from an infoobject (the user exit variable seemed to be a good solution) and the user must have the possibility to select some values amongst these as filter.
    Regards

  • How to select multiple values from the parameters in BI Publisher report

    How to select multiple values from the parameter drop down in BI Publisher, and how to handle this mulitple values from the report sql...

    Hi kishore,
    I have used all the steps as you mentioned in your previous reply....including checking Mulitple Selection Check Box..
    Iam able to get the results when I am selecting one value..
    and also I am able to handle multiple values the in the query by using IN :Parameter, but seems when we select more than one value from the parameter drop down i think the Bi Publisher is sending the values in concatenated form something ilke
    ex: "'ACCOUNT','HR','SALES'" ,and when trying to display the parameters values in the output, its throwing the error as 'missing right paranthesis' ....on the whole do you have any solution which would handle
    1.Single selection.
    2.Multiple selection.
    3.'ALL' Values.
    4.Separating the concatenated string into individual strings and dispaly them on the output of the report..etc..in case of Mulitple selection.
    Ex:
    Concatenated String from BI Publisher:"'ACCOUNT','HR','SALES'"
    Expected Output on the report:ACCOUNT,HR,SALES
    reply to this would be much appreciated....
    thanks,
    manoj

  • How to select multiple values from the Parameters in the concurrent program

    How to select multiple values from the Parameters defined in the concurrent program...and i believe multiple selection is not a direct feature of EBS, but is there any workaround solution to acheive mulitple selection?

    I think there's no way to do that using standard feature.
    Some workaround I use :
    1. If the number of selections are fixed, you could use multiple parameters for the same valueset. For example :
    Selection1 : <choose first selection>
    Selection2: <choose 2nd selection>
    ..etc.
    If you don't use it then leave it empty.
    2. Use text varchar valueset and enter it manually and separate by comma (or other value) , eg : selection1,selection2,selection3....etc.

Maybe you are looking for

  • 2-way SSL using t3s protocol

    Goodmorning, I'm trying to get a 2-way SSL connection between two WLS 10.3 in production mode. WLS #1 contains the client application and WLS #2 contains the server application. I've got a standalone Microsoft CA. I've configured WLSs with custom ide

  • I have a Nvidia Galaxy GT 610. The driver keeps failing, what can I do about this?

    I have an Nvidia Galaxy GT 610, and the driver keep's failing on me. What can I do about this, I have uninstalled the driver and reinstalled the driver, and I keep getting the same thing. I am at the point where I am going to buy an other card. So if

  • Update 7.1.1 problem

    I'm getting this alert when trying to update Logic Express: 'An eligible Logic Express application was not found in /Applications.' However it's there and it's working (version 7.0.1). I installed the original Logic Express again from the dvd but I'm

  • Finding a url link to partially completed form already submitted -

    I wonder if you can help - I am the author of an application form for which I am currently collating responses.  I have enabled the form to be saved  for 7 days by applicants too. I noticed when I was reviewing some of the responses that one person h

  • Query on PIR consumption.

    Hi all, One of the PIR created in Aug (MD61/MD62) is still appearing in MD04. If it is not consumed, whether it will still reflect in MD04 now (October). I have a doubt in this. I think if the PIR is -30 days and +30 days after date of forecast, it s