TSP: Generating N unique random indices in tricky set

Hi! I'm working on a type of the euclidian travelling salesman problem, and I'm going to try to solve it using an Genetic Algorithm.
One solution may be a route like this: 1-2-4-3-7-6-5. This means travel from town 1 to 2 etc up to city number 5 and also implies travelling
back to town 1 after town 5. Since the distances between cities are symmetrical, the above given solution is equal to the solution
1-5-6-7-3-2 (since the route 1-2-4-3-7-6-5-1 is equal (in travelling distance) to 1-5-6-7-3-4-2-1 due to symmetry).
I need to create an initial population of N solutions. These need to be unique, preferrably totally random solutions in the set of possible
solutions (wich is this case does not consist of all possible permutations!). Is there a way of doing this without running the risk of
getting stuck in a loop (generating the same solutions many times and retrying)? I don't want to risk this, since speed is an issue.
I've thought about ranking solutions and unranking them, but this involves computing faculties, and that may be very time consuming
and does not seem to be the optimal solution, although i've seen some implementations running in time complexity O(N).
Note: the number of cities may vary.
Any thoughts?
Regards
Alex

Generating a random order of indices is not that difficult.
int[] arr = new int[n];
for (int i = 0; i < n; i++)
    arr[i] = i;
for (int i = 0; i < n; i++) {
     int k = (int) (Math.random() * n);
     int x = arr[k];
     arr[k] = arr;
arr[i] = x;
However, when dealing with a graph this approach probably doesn't
make that much sense, since it's unlikely there is an edge between
every node.
You probably want to generate an initial population where sequential
indices are adjacent nodes.
An alternative to GA is to determine the minimum spanning tree, and
traverse that. The MST appoach is within a factor of 2 of optimal. If
you're stuck on GA for this problem, then I think the hardest part is to
determine a good appoach for combining two solutions.

Similar Messages

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

  • How can I generate multiple unique random numbers?

    Hello,
    I am trying to generate multiple random numbers between a given set of numbers (1-52) and not have the same number generated twice within that set. I can compare the last and next numbers with the compare function but how would I go about comparing all of the generated numbers without using a huge list of shift registers...
    Any help/ideas are welcome and appreciated.
    Jason
    Solved!
    Go to Solution.

    Here is an implementation of Jason's solution.
    steve
    Help the forum when you get help. Click the "Solution?" icon on the reply that answers your
    question. Give "Kudos" to replies that help.
    Attachments:
    random.vi ‏10 KB

  • Unique random alpha num string

    Hi Guys,
    I have a unique question.
    I need to generate a unique random Alpha Num string.
    I cannot use 0,5,8 and 0,S,B in the generated output string.
    The string generated should be no more than length 7 max
    Pls help.

    Following solution generates random unique strings combinations
    from any given base set. Here is a sample output.
    $ java UniqueStringGenerator 7 100 10
    FCT2RYT
    2M31BU8
    VV8FU4Z
    BON2MKE
    OKUJZT0
    68E8X8S
    YTNLZAY
    CPEKPFP
    C176M24
    GQB9QE9The idea is quite simple.
    Pre-work:
    1. The base set is first mixed to increase entropy.
    2. All possible combinations are divide up into random buckets.
    Work for every unique string:
    1. Pick a bucket at random.
    2. Get next number in bucket.
    3. Convert the number to a unique string token.
    It is possible to adjust how much entropy you want in your
    sequence of generated combinations by choosing how many buckets
    the generator contains. However, every bucket will take up some
    memory.
    import java.util.*;
    import java.math.*;
    public class UniqueStringGenerator {
        public static String[] ALPHA_NUM =
         {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
          "Q","R","S","T","U","V","X","Y","Z",
          "0","1","2","3","4","5","6","7","8","9"};
        private List _parts = null;
        private List _buckets = null;
        private int _length;
        private BigInteger _range = null;
        public UniqueStringGenerator(String[] parts, int length,
                         int numberOfBuckets) {
         _length = length;
         // mixing the base set to increase entropy
         _parts = new Vector();
         List all = new Vector();
         for (int i = 0;i < parts.length;i++) {
             all.add(parts);
         while (all.size()>0) {
         int p = (int)(((double)all.size())*Math.random());
         _parts.add(all.get(p));
         all.remove(p);
         // dividing all possible numbers into given number of buckets
         BigInteger numParts = BigInteger.valueOf(parts.length);
         _range = BigInteger.ONE;
         for (int i = 0;i<_length;i++) {
         range = range.multiply(numParts);
         TreeSet starts = new TreeSet();
         Random rand = new Random();
         while (starts.size()<numberOfBuckets-1) {
         BigInteger bi = new BigInteger(_range.bitLength(), rand);
         if (bi.compareTo(_range)<=0) {
              starts.add(bi);
         _buckets = new Vector();
         Bucket last = new Bucket(BigInteger.ZERO);
         _buckets.add(last);
         for (Iterator i = starts.iterator();i.hasNext();) {
         Bucket next = new Bucket((BigInteger)i.next());
         _buckets.add(next);
         last.setTo(next.getStart());
         last = next;
         last.setTo(_range);
    private class Bucket {
         private BigInteger _start;
         private BigInteger _next;
         private BigInteger _to;
         public Bucket(BigInteger start) {
         _start = start;
         _next = start;
         public void setTo(BigInteger to) {
         _to = to;
         public BigInteger getStart() {
         return _start;
         public boolean hasNext() {
         return next.compareTo(to)<0;
         public BigInteger next() {
         BigInteger ret = _next;
         next = next.add(BigInteger.ONE);
         return ret;
         public String toString() {
         return "["+start+", "+next+", "+_to+"]:"+hasNext();
    public String nextUnique() {
         // getting next big integer
         BigInteger left = null;
         while (left==null) {
         Bucket b = (Bucket)
              buckets.get((int)(Math.random()*buckets.size()));
         if (b.hasNext()) {
              left = b.next();
         // converting it to a combination
         StringBuffer unique = new StringBuffer();
         BigInteger base = BigInteger.valueOf(_parts.size());
         for (int i = 0;i<_length;i++) {
         BigInteger[] resRem = left.divideAndRemainder(base);
         left = resRem[0];
         unique.append(_parts.get(resRem[1].intValue()));
         return unique.toString();
    public static void main(String[] args) {
         if (args.length!=3) {
         System.out.println("Usage: UniqueStringGenerator "+
                   "[string size] [# buckets] [# prints]");
         return;
         int length = Integer.parseInt(args[0]);
         int numBuckets = Integer.parseInt(args[1]);
         int num = Integer.parseInt(args[2]);
         UniqueStringGenerator usg = new UniqueStringGenerator
         (UniqueStringGenerator.ALPHA_NUM, length, numBuckets);
         for (int i=0;i<num;i++) {
         System.out.println(usg.nextUnique());

  • How to best generate a unique alphanumeric key

    Hi:
      I have a requirement to generate a unique alphanumeric key 20 characters long.
      I know that I can use sys.dbms_random.string('X', 20) but I also have a requirement to not include certain characters that could be missread, i.e. no 0 (zero), O(uppercase oh) and a few others.
      My questions are:
         1) Is there a way to tell dbms_random to not include certain characters in the key generation
         2) If the answer to 1 is No, what would be the best way to replace the unwanted characters.  I am thinking just do a translate right afterwards with a randomly generated set of characters that do not include the characters I am interested in and seeded
             upon package initialization.  Any other ideas.
        3) Is there a better way of meeting this requirement within PL/SQL?
    Thanks,
    Thomas

    The most safe would be to use something like below if efficient enough
    select listagg(x.ltr,'') within group (order by y.step desc) key
      from (select level lvl,
                   substr(:alphabet,level,1) ltr
              from dual
            connect by level <= length(:alphabet)
           ) x,
           (with
            to_base(step,num,base,quot,remain) as
            (select 1 step,num,base,trunc(num / base) quot,mod(num,base) remain
               from (select :sequence_value num,length(:alphabet) base
                       from dual
                      where :sequence_value between power(length(:alphabet),:key_length - 1)
                                                and power(length(:alphabet),:key_length) - 1
             union all
             select step + 1,quot,base,trunc(quot / base),mod(quot,base)
               from to_base
              where num > 0
            select step,remain
              from to_base
             where num > 0
           ) y
    where x.lvl = y.remain + 1
    Regards
    Etbin

  • Array of unique random numbers - help?

    basically, i'm trying to create a BINGO card.
    i stared learning Java a week ago and am finding it easy to learn and use....at least so far.
    my instructor gave me the assignment to created a BINGO card. so i used the system.out.format command to make 5 tab fields, 8 spaces each ("%8s %8s %8s %8s %8s", "B", "I", "N", "G", "O"). although the assignment only wanted me to think numbers out of thin air, just to use as examples, i went above and beyond with the idea to make a BINGO card generator that could actually function.
    then i started the random number sequences, using the Math.random() command. all told, there are 24 of these in the program, one for each number on a bingo card. the field in the middle is the FREE space, so it has no Math.random command.
    in BINGO, each letter (one of my five tab fields) can have a number in ranges of 15. B is 1 to 15, I is 16 to 30, etc. it looks similar to this:
    B I N G O
    9 19 39 57 66
    3 28 32 51 74
    3 29 FREE 46 70
    14 28 43 55 67
    9 24 35 59 62
    as you can tell, i'm having trouble with actually making unique random numbers so that none repeat.
    is there a command or string or something to help me accomplish this?

    The best way I've come up with is to use an object to store the numbers that implements Collection--like ArrayList...
    Then you load it with the range of numbers that you want and call, shuffle() on the object, that will randomize your range of numbers and then you can choose the quantity you want from the storage object. So let's say you need 25 number in the range of 1 to 100:
    Add the numbers (you have to use classes so I would do Integers) 1 to 100;
    call shuffle()
    pull back the first 25 numbers
    This will guarantee that each number is distinct and in a random order.
    If you need multiple sheets populated, you can just call shuffle() between population of each sheet.
    package Junk;
    import java.util.ArrayList;
    import java.util.Collections;
    class Junk{
      private ArrayList<Integer> l;
      Junk(){
        l = new ArrayList<Integer>();
      public void loadList(int s, int e){
        for(int i=s; i<=e; i++){
          l.add(new Integer(i));
      public void randomizeList(){
        Collections.shuffle(l);
      public void printList5(){
        for(int i=0; i<5; i++){
          System.out.println(l.get(i));
      public static void main(String[] args){
        Junk j = new Junk();
        j.loadList(10,99);
        j.randomizeList();
        j.printList5();
        System.out.println();
        j.randomizeList();
        j.printList5();
    }

  • 7 digit unique random number

    I would like to generate 7 digit unique random number. I have it something like this :
    Random generator = new Random();
              generator.setSeed(System.currentTimeMillis());
              //generates seven digit random number.
              return generator.nextInt(9999999) + 999999;
    But it generates 8 digit numbers sometimes. I am giving the Max limit in the braces and min limit after the "+" sign. Could anybody help me figure out what is wrong.

    This is not a horrible solution but an intelligent &
    easy solution ;)Actually this would be the easy and intellegent solution to the problem "give a random 7 digit integer."
    Random generator = new Random();
    //generates seven digit random number.
    return generator.nextInt(10000000);Though the orginal post does not specify this as part of the problem others have assumed (probably correctly) that in fact the poster wants a number between 1000000 and 9999999 (inclusive) which can easily be produced with the following modification to the above.
    Random generator = new Random();
    //generates seven digit random number.
    return generator.nextInt(9000000) + 1000000;I am confused by your response. Are you saying the becasue the original question was asking why flawed code doesn't work, that makes your solution good?

  • Ideas on generating seeds for random number generators?

    Does anyone here have any ideas or know of any good links to articles that discuss how to generate good seeds for random number generators?
    I am aware that I could always probably call SecureRandom.generateSeed as one technique.
    The major problem that I have with the above is that I have no idea how any given implementation of SecureRandom works, and whether or not it is any good. (For instance, Sun seems to hide their implementation outside of the normal JDK source tree; must be in one of their semi-proprietary sun packages...)
    I thought about the problem a little, and I -think- that the implementation below ought to be OK. The javadocs describe the requirements that I am looking for as well as the implementation. The only issue that still bugs me is that maybe the hash function that I use is not 1-1, and so may not guarantee uniqueness, so I would especially like feedback on that.
    Here's the code fragments:
         * A seed value generating function for Random should satisfy these goals:
         * <ol>
         *  <li>be unique per each call of this method</li>
         *  <li>be different each time the JVM is run</li>
         *  <li>be uniformly spread around the range of all possible long values</li>
         * </ol>
         * This method <i>attempts</i> to satisfy all of these goals:
         * <ol>
         *  <li>
         *          an internal serial id field is incremented upon each call, so each call is guaranteed a different value;
         *          this field determines the high order bits of the result
         *  </li>
         *  <li>
         *          each call uses the result of {@link System#nanoTime System.nanoTime}
         *          to determine the low order bits of the result,
         *          which should be different each time the JVM is run (assuming that the system time is different)
         *  </li>
         *  <li>a hash algorithm is applied to the above numbers before putting them into the high and low order parts of the result</li>
         * </ol>
         * <b>Warning:</b> the uniqueness goals cannot be guaranteed because the hash algorithm, while it is of high quality,
         * is not guaranteed to be a 1-1 function (i.e. 2 different input ints might get mapped to the same output int).
         public static long makeSeed() {
              long bitsHigh = ((long) HashUtil.enhance( ++serialNumber )) << 32;
              long bitsLow = HashUtil.hash( System.nanoTime() );
              return bitsHigh | bitsLow;
         }and, in a class called HashUtil:     
         * Does various bit level manipulations of h which should thoroughly scramble its bits,
         * which enhances its hash effectiveness, before returning it.
         * This method is needed if h is initially a poor quality hash.
         * A prime example: {@link Integer#hashCode Integer.hashCode} simply returns the int value,
         * which is an extremely bad hash.     
         public static final int enhance(int h) {
    // +++ the code below was taken from java.util.HashMap.hash
    // is this a published known algorithm?  is there a better one?  research...
              h += ~(h << 9);
              h ^=  (h >>> 14);
              h +=  (h << 4);
              h ^=  (h >>> 10);
              return h;
         /** Returns a high quality hash for the long arg l. */
         public static final int hash(long l) {
              return enhance(
                   (int) (l ^ (l >>> 32))     // the algorithm on this line is the same as that used in Long.hashCode
         }

    Correct me if I'm incorrect, but doesn't SecureRandom just access hardware sources entropy? Sources like /dev/random?What do you mean by hardware sources of entropy?
    What you really want is some physical source of noise, like voltage fluctuations across a diode, or Johnson noise, or certain radioactive decay processes; see, for example
         http://www.robertnz.net/true_rng.html
         http://ietfreport.isoc.org/idref/draft-eastlake-randomness2/
         this 2nd paper is terrific; see for example this section: http://ietfreport.isoc.org/idref/draft-eastlake-randomness2/#page-9
    But is /dev/random equivalent to the above? Of course, this totally depends on how it is implemented; the 2nd paper cited above gives some more discussion:
         http://ietfreport.isoc.org/idref/draft-eastlake-randomness2/#page-34
    I am not sure if using inputs like keyboard, mouse, and disk events is quite as secure as, say, using Johnson noise; if my skimming of that paper is correct, he concludes that you need as many different partially random sources as possible, and even then "A hardware based random source is still preferable" (p. 13). But he appears to say that you can still do pretty good with these these sources if you take care and do things like deskew them. For instance, the common linix implementation of /dev/random at least takes those events and does some sophisticated math and hashing to try to further scramble the bits, which is what I am trying to simulate with my hashing in my makeSeed method.
    I don't think Java can actually do any better than the time without using JNI. But I always like to be enlightened; is there a way for the JVM to generate some quality entropy?Well, the JVM probably cannot beat some "true" hardware device like diode noise, but maybe it can be as good as /dev/random: if /dev/random is relying on partially random events like keyboard, mouse, and disk events, maybe there are similar events inside the JVM that it could tap into.
    Obviously, if you have a gui, you can with java tap into the same mouse and keyboard events as /dev/random does.
    Garbage collection events would probably NOT be the best candidate, since they should be somewhat deterministic. (However, note that that paper cited above gives you techniques for taking even very low entropy sources and getting good randomness out of them; you just have to be very careful and know what you are doing.)
    Maybe one source of partial randomness is the thread scheduler. Imagine that have one or more threads sleep, and when they wake up put that precise time of wakeup as an input into an entropy pool similar to the /dev/random pool. Each thread would then be put back to sleep after waking up, where its sleep time would also be a random number drawn from the pool. Here, you are hoping that the precise time of thread wakeup is equivalent in its randomness to keyboard, mouse, and disk events.
    I wish that I had time to pursue this...

  • Generating 7 numbers random sequence

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

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

  • Unique random

    Hi all I need algorithm to generate unique random number.

    but i need it all of them as digit number
    and i need it it unique, if i have saved it before in a
    DB , and i need to re-generate again i need unique number.I'll have to make a guess at what you mean...
    Just use a cyclic random number generator, and save the "current position" somewhere.

  • Generating a unique ID to pass to Payment Provider?

    Hi.
    I have a site that has "orders" from customers which have a
    unique ID (PK).
    I'm using ASP / SQL.
    I was passing this ID to my payment service provider but have
    discovered
    that, if a customer for some reason cancels the order (highly
    likely), then
    that ID cannot be passed to the payment provider again.
    Therefore, when the
    customer logs back in to our site, they'll still see the
    order as "requiring
    payment" but when they try to re-submit the order, the
    payment provider
    won't allow it! Groan!
    Anyway, that is the way their system works, and I understand
    why I suppose
    (unique identifier 'an all that).
    So, my solution is to simply pass a unique value (which
    doesn't have to
    relate to my unique order ID) to the payment provider.
    My question is....how can I create/generate a unique value on
    my checkout
    page and ensure that the same value is never generated twice?
    Is there a
    feature in DW?
    Oh yes, and I need it to be a numerical value! :o)
    Thanks.
    Nath.
    Brain < Pea

    Here is a guaranteed unique algorithm for any string (sequence of characters.)
       String createMyId(String stringToEncode)
          String uniqueId = stringOfChars;
          return uniqueId;
       }The code above guarantees the following properties (expressed as psuedo logic code, not java code.)
    For any given sequence of chars A and B.
    If A = B is true if and only if createMyId(A) = createMyId(B)
    And of course
    If A != B is true if and only if createMyId(A) != createMyId(B)
    Of course the problem with the above algorithm is that it produces a variable sized value. But if you use a char array of of size Integer.MAX_VALUE then you can guarantee that it will work for any String in java. There is still a downside to this in that it requires a lot of data.
    Of course someone who is particularily observant might note that this suggests that one might as well just store the string. That however is just an optimization in the above algorithm and as nothing to do with the validity of the algorithm itself.

  • How to generate a Unique key based on a some String value

    Hello every one,
    I am sorry , If I post this question in wrong group... I have a requirement to generate a unique key ( what every it may be alpha, numeric or alpha numeric) based on some String..
    For ex : String str = "AbCX" - Gives a unique key based on "AbCX" value..
    Is there any way we can get the unique value using Java ?
    Thanks

    May be not what you are looking for, but here's may idea:
    use a sequence (db sequence) and add it the the string value. This way the value is unique, because the sequence is unique. So you could omit the string theoretically, but your requirement is met.
    It's very easy to get a unique sequence number from the db using java, depending of the technology you use (which you did not say :-( )
    Timo

  • Help in generating the same random numbers each time of the program executi

    dear friends
    i am facing a problem that the random numbers generated at time of each exectuion of the program are not the same, i want to generate the same random numbers every time time i run the program. i need your help. i am giving the code in c++ if anybody can help in providing the solution so that i get the same random numbers at every run of the program. waiting for your help
    wit regards
    jaya shankar
    #include<iostream.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    #include<math.h>
    class density
    int s[150][150],parent[150][150],i,j,l,n,loop;
    public:
    void bd(void);
    void css(void);
    void density :: bd(void)
    cout<<"ENTER THE POPULATION SIZE = ";
    cin>>n;
    cout<<"\nENTER THE NO.OF LOOPS = ";
    cin>>loop;
    for(i=0;i<n;i++)
    for(j=0;j<80;j++)
    s[i][j]=rand()%2;
    cout<<"s:"<<s[i][j];
    void density :: css(void)
    int a,b;
    float c;
    for(i=0;i<n;i=i+2)
         b=rand()%100;
         cout<<"random b="<<b;
    main()
    density d;
    d.bd();
    d.css();

    To generate the same random,it's impossible!
    why do you want to do that?

  • Help in generating the same random numbers at every time of executuion

    dear friends
    i am facing a problem that the random numbers generated at time of each exectuion of the program are not the same, i want to generate the same random numbers every time time i run the program. i need your help. i am giving the code in c++ if anybody can help in providing the solution so that i get the same random numbers at every run of the program. waiting for your help
    wit regards
    jaya shankar
    #include<iostream.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    #include<math.h>
    class density
    int s[150][150],parent[150][150],i,j,l,n,loop;
    public:
    void bd(void);
    void css(void);
    void density :: bd(void)
    cout<<"ENTER THE POPULATION SIZE = ";
    cin>>n;
    cout<<"\nENTER THE NO.OF LOOPS = ";
    cin>>loop;
    for(i=0;i<n;i++)
    for(j=0;j<80;j++)
    s[j]=rand()%2;
    cout<<"s:"<<s[j];
    void density :: css(void)
    int a,b;
    float c;
    for(i=0;i<n;i=i+2)
    b=rand()%100;
    cout<<"random b="<<b;
    main()
    density d;
    d.bd();
    d.css();

    You have to read the documentation for the java.util.Random class.
    "If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random"
    Here is a peace of code that will do wat you need:
    Random rand = new Random(100);
    for(int i=0; i<10; i++)
         System.out.println("Random="+ rand.nextInt(10));

  • Generate file names randomly

    are there anyways to generate file names randomly? if there are, are there any reference codes i could refer to? thanks.
    heard that using random characters from ascii code (generating random numbers and translating them into chars) could do the job but i am rather new to it. can anybody advise me on how to go about it? thanks.

    There is a method called createTempFile in the java.io.File class for this purpose. I suggest you use that one.

Maybe you are looking for

  • From folder on Search iView

    Hi Is it possible to define a "search from" folder on the search iView? I was thinking about the query option. Any ideas? Best regards, Ole

  • How to reference LEVEL in a TREE's SQL code

    Is it possible to somehow reference LEVEL in a tree's sql code so that you can use a decode statement to selectively create links on specific levels only i.e. NOT on the root level? e.g. select "CHILD_ID" id, "PARENT_ID" pid, "NAME" name, decode( LEV

  • New Hard Drive still have Question Mark Folder

    So I first got the 'Question Mark Folder' and had to keep running Safe Boot Mode to use computer. Finally got around to replacing the Hard Drive, but this Question Mark Folder still comes up trying to turn the computer on and now trying to setup the

  • LOV works fine when run from JDEV

    Hi OAF Gurus, I have an issue with one of the LOV population. It is an external LOV and I have created it as a seperate region and it works fine when I run from the Jdeveloper . When I deploy it in the server,it throwing me an error with a OAF except

  • How to power US Macbook Air in UK

    To charge my US Macbook Air when traveling in the UK, do I need a voltage converter or can I use an inexpensive adapter plug to fit UK outlets?