Help sort randomly generated integers

I am having trouble with this peace of code; I wrote a little test and found the same problem in my larger program. My problem is I can't sort an array that I randomly put int values in but if I put them in manually the values will sort. And hits or help would be great.
public class test {
    public static void main (String [] args) {
        int[] array = new int[20];
// Generator random int into array
        for (int i=0; i<array.length; i++) {
            array[i] = (int)(Math.floor(Math.random() * (20.0 - 0.0)) + 0.0);
// Selection sort
        int si, temp;
        si = 0;
        for(int i=0; i<=array.length-2; i++) {
            for(int j=i+1; j <=array.length-1; j++) {
                if(array[j]<array)
si = j;
// Swap
temp = array[i];
array[i] = array[si];
array[si] = temp;
// Output
for(int t=0; t<array.length; t++) {
System.out.println(array[t]);

This code will sort, and i am not asking anyone to do it for me, just and hits on what the problem could be.
public class test {
    public static void main (String [] args) {
        int[] array    = {9,8,4};
// Generator random int into array
        for (int i=0; i<array.length; i++) {
            array[i] = (int)(Math.floor(Math.random() * (20.0 - 0.0)) + 0.0);
// Selection sort
        int si, temp; 
        si = 0;
        for (int i=0; i<=array.length-2; i++) {
            for (int j=i+1; j<=array.length-1; j++) {
                if(array[j] < array) {
si = j;
// Swap
temp = array[i];
array[i] = array[si];
array[si] = temp;
// Output
for(int t=0; t<array.length; t++) {
System.out.println(array[t]);

Similar Messages

  • Randomly generate an ID for SQL Create Table command

    Hi,
    I need help to randomly generate an integer, which i can use as a primary key for the ID of a table field. I have no idea how to do this so that it generates a different number every single time.
    Right now it just increments the ID by 1. Maybe, is there a way to get the last ID value of the table field and then increment starting from that one? thanks

    Your analysis is flawed! One of my main reasons for
    doing this is to reduce the load on the db server. I
    don't have to go to the db to get an id every time I
    need one. Every now and again (usually less than one
    in a 2000) I have to repeat an insert operation.
    You already stated that this was the reason, so I used that as part of my assessment. With most, perhaps all databases, the ability to increment a key is done as part of the insert operation. It requires no additional 'trip' to the database to get the ID. There is so much wrong with your idea, I hardly know where to start. I wouldn't be so firm except you stated that you do this all the time. Even using it once is very questionable I wouldn't want this idea to profilerate to other peoples systems without comment.
    You also said:
    On one project I was having to place usage transaction records
    into a database with each one needing an ID. I started using your
    technique but it was taking almost as much time as the insert of
    each transaction into the database.I agree, and I think dcminter agreed that there are less expensive practices then max(fld)+1 which are in fact using the vendor specific capabilities. However, if this was taking as long as your insert, there was probably something else wrong. For example, if the field you are getting the max value for isn't indexed, or isn't the first field in a contatenated index (an index of multiple fields), then some databases (there are exceptions like redbrick) will require either a full table scan, an index scan or an ackward index lookup to give back the max value. It shouldn't be that way, but it is and you have undestand how your database is resolving max() in order to make the best decisions.
    I stand by analysis and I would suggest that rather then use your method "all the time" that you save it for that unusual situation where nothing else will work for you.

  • Sorting randomly genareted string in alphapetic order

    import java.util.*;
    public class test {
        public static char[] chars;
        public static Random random;
        static {
            chars = new char[26];//taking caracters from asci table
            for (int i = 0; i < 26; i ++) {
                chars[i] = (char) (97 + i);           
            random = new Random ();
        public static void main (String[] args) { //printing random characters
                for (int i = 1; i <= 10; i++ ) {                                                                          
                System.out.println(randomString(20)); 
        private static String randomString (int length) { //generating random
            char[] array = new char[length];
            for (int i = 0; i < length; i ++) {
                array[i] = chars[random.nextInt (chars.length)];
        return new String (array);
        i have this code.i found that in the forums and modified it a bit.but i have still problems to sort randomly genareted strings in alphabetic order.i have a method to do it.but i couldn't implement it correctly.the way that i try to sort them is
    void sort(String[] a) {
      for (int i=0; i<a.length-1; i++) {
         for (int j=i+1; j<a.length; j++) {
            if (a.compareTo(a[j]) > 0) {
    String temp=a[j];
    a[j]=a[i];
    a[i]=temp;
    thats a method i try to use but i couldn't put it in a correct place in the code and couldn't call him.always it gives error.pls help this unexprienced java user...

    Hard to understand your problems, because you're too vague. At one point you mention you don't know where to put your method, at another you say you don't know how to call your method. If that is the case (which seems unlikely but oh well) here's an example.
    public class Testing9 {
         public Testing9() { // constructor
              String basicString = "BasicExample";
              String sortedString = mySortMethod(basicString); // call mySortMethod passing the string
              System.out.println("sortedString = " + sortedString);
         public static void main(String[] args) { // main method starts app
              Testing9 app = new Testing9(); // calls constructor
         public String mySortMethod(String s) { // put the method here cause I feel like it
              String sortedString = "";
              // do your own work here to sort, etc....
              return sortedString;
    }

  • How to make a random generator with a max and a minimum

    hello
    can anybody telle me how to make a random generator for numbers with a maximum and minimum input
    thanks in advance

    Hi suske,
    If you want a random day for a given month, this is how I would do it.
    Hope this helps,
    -D
    Message Edited by Darren on 02-02-2006 01:35 PM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Days_per_month.jpg ‏32 KB

  • Writing a class using random generator in bluej

    Hello
    Im trying to write a class for a deck of cards. Im using a random generator but I dont know how to write the instance variable.
    I have to make 4 suits heart, club, spade, dimonds. and 13 for face value. I know how to random generate numbers. Like if I were making a slot machine to give me 3 numbers in a rage from 0-10. Thats just numbers. How do I random generate values of 1-13 and have it output a random suit? Also how do I make it say if its a jack king or queen? Do I need a constructor or how would I make the card with the face value of 13 suit heart and the card be a queen.
    before jumping down my throat about this being a homework assignment...yes it is but this step Im seeking help on there is no example for this type of generating.
    Thanks for any help
    Rewind

    Well, this is far from bullet-proof, but I think gets the basic idea across. This does sampling with replacement; if you wanted to do something like shuffle a deck of cards you'll need a smarter approach than this.
    import java.util.*;
    public class RandomCards {
      public static void main(String[] args) {
        Suit suit=new Suit();
        for (int i=0; i < 10; i++) {
          System.out.println(suit.nextSuit());
      private static class Suit {
        public static final String HEART="Heart";
        public static final String DIAMOND="Diamond";
        public static final String SPADE="Spade";
        public static final String CLUB="Club";
        private final String[] SUITS={ HEART, DIAMOND, SPADE, CLUB };
        private Gen suitGen=new Gen(0,3);
        public String nextSuit() {
          return SUITS[suitGen.nextInt()];
      private static class Gen {
        private int floor,ceiling;
        private Random rand;
        public Gen(int floor, int ceiling) {
          this.floor=floor;
          this.ceiling=ceiling;
          rand=new Random();
        public int nextInt() {
          return rand.nextInt(ceiling-floor)+floor;

  • QCPatch 'Random Generator' Broken Seed?

    Hi there all,
    Just putting this out there - perhaps I'm wrong, but want some other QC developers who are more experienced to compare with.
    Quartz Composer Patch "Random Generator" - one of the inbuilt patches available.
    Its purpose is to generate random numbers between a range, and supply the number on its output port.
    To this end, it works fine.
    My problem with this patches behavior occurs when it is nested in a macro patch, and that patch is then duplicated (purpose obvious).
    *The duplicated macro patch appears to also copy the Random Generators' base seed.*
    For example I have the same picture resulting from Random Generators nested inside a macro patch that contains processing for a random choice of image to a sprite.
    The only way i could work around this (and this may help others with the same problem) was to Publish the Input ports all the way up to the root level patch, and supply new instances of a Random Generator for each instance of the duplicated macro patch.
    Then I received fresh random seeds from the generator and different images were selected for output to my nested sprite.
    Awfully inconvenient given that each macro had 4 levels of nesting using objects like render in image, 3D transformation and Lighting - all patches that require nesting, and also reset your ports being passed to a parent, meaning you have to - 're-map' the Published Inputs with every layer of nesting. Not to mention the fact that the root level of the document is cluttered all to **** with millions of Random Generator patches.
    Anyone get this behavior?
    Please let me know if I'm just screwing my design up, or if this is encountered by you too and we should report it as a bug. (Ive only been devving QC for several weeks straight, so I'm want to actually report it as a bug yet).
    Many thanks in advance,
    Wilks.

    A random created with the same seed will give the same set of random numbers.
    Take out the Random creation from the loop
    try
                 BufferedWriter out = new BufferedWriter(new FileWriter("c:/test.txt"));
                    //Create Random here.
                     Random r = new Random( );//No need for any seed
                 for (int i = 0; i < 1000; i++)
                      out.write(String.valueOf(r.nextInt(9)));
                 out.close();
    catch (IOException e)
    [url http://www.feedfeeds.com/feedtv]Feed Your Feeds

  • Labview random generator leds

    Hey Labview users,
    I'm a novice with labview and i have to solve the next exercise. Create a random generator 10 which generates random numbers between 0 and 100.
    Provide between 2 numbers generated a delay of 1s.
    Provide also 3 LEDs that light up as follows:
    - Red LED: 70 <random number
    - Green LED: 30 <random number <70
    - Orange LED: random number <30
    Only when the 10 random numbers are generated, enter this  1 dimensional, profiled collection (1D array).
    Can anybody show me the block diagram
    Can somebody help me please ? It's quite urgent.(i have untill saterday 26/1)
    Any solution is welcome !

    Well, if you have to have this done, you hade better get on with it.
    A couple hints:
    The random number generator built into LV puts out a DBL float value between 0 and 1.
    You can use the threshold function to determine which of the three LEDs should be on.
    You know ahead of time that the VI needs to loop 10 times, so you can use a for loop.
    There is a wait function in LV that you can use to generate the 1 sec delay.
    Beyond this, we will not write your homework for you. We don't need your degree, we have degrees of our own.
    Post code and we will help you by answering specific questions.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • How to produce the digital random generator,which counts 0 and 1 randomly

    hi , i want to generate the digital random generator for my project,which counts the 0 and 1 randomly. can anybody help me in doing this.

    Your question has been phrased in a way to cause confusion to what you actually want to achieve. Are you trying to display the random generator like a bit stream on a graph ie:
    If so then this vi will do that:
    Every time you press the 'Generate' Button it will create a digital array according to the 10 bit random number generated and display on a graph.
    There is a way of doing this using a 'Digital waveform graph', i personally have never used it and after about 5 minutes of just looking into it for you gave up It is something i should spend the time to look into as it presents your digital data nicely, showing the 0's and 1's within the graph.
    If i have misunderstood what you want again i apologise
    Rgs,
    Lucither
    Message Edited by Lucither on 05-10-2010 06:27 AM
    "Everything should be made as simple as possible but no simpler"

  • Trying to build a random generator

    Hi, I am quite new to java and was wondering how do I complete building this program.
    The objective of the program is to randomly generate 100 2 digit odd integer values.
    I can generate the values but I don't know how to sieve only 100 odd integers.
    I am also supposed to find the maximum, minimum and average of all the numbers generated. I can find the average but can't seem to find maximum and minimum.
    I also need to point out the location of the maximum and minimum which I do not have a clue on how to do.
    Lastly, my program is suppose to loop when keyed in 'y' or 'Y'. I think I have done that.
    My codes are as below
    import java.io.*;
    class Question2
         public static void main (String args []) throws IOException
              BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
              Question2 theClass = new Question2();
              String strValue = "";
              int value = 0;
              int random [] = new int [100];
              int l= random.length;
              int max=0, min=0;
              int sum = 0;
              do {
              System.out.print("Enter 'Y' to Start / Begin ");
              strValue = stdin.readLine();
              if (strValue.equalsIgnoreCase("Y")){
              for(int i = 0; i<l ; i++)
                   if (i%10==0)
                        System.out.println("");
                   random[i] = randomNumber(value);//recall method to generate numbers
                   System.out.print(random[i] + " ");
                   int maximum = random;
                   max = findMaximum(maximum);//recall method for maximum
                   int minimum = random[i];
                   min = findMinimum(minimum);//recall method for minimum
                   sum = sum + random[i];
              else
              break;
              int average=0;
              average = findAverage(sum);//recall method for average
              System.out.println("\nThe average is " + average);
              System.out.println("The Maximum Number is " + max);
              System.out.println("The Minimum Number is " + min);
         }while (strValue.equalsIgnoreCase("Y"));     
              //random number generator
         public static int randomNumber (int value)
              int choose=0;
              choose = 10 + (int)(Math.random()*89);
              return choose;
         //maximum number generator
         public static int findMaximum(int maximum)
              int maxi = 0;
              if (maximum>maxi)
              maxi=maximum;
              return maxi;
         //average generator
         public static int findAverage (int sum)
              int avg = 0;
              avg = sum/100;
              return avg;
    //minimum generator
         public static int findMinimum(int minimum)
              int mini = 0;
              if (minimum<mini)
              mini = minimum;
              return mini;
    Thank you.

    Yes, but it guarantees that the process will be
    complete after 100 iterations. The discarding
    strategy will be completed in 200 iterations, on
    average, and there is no guarantee that once in a
    while, it will not take 1000 iterations.Pshaw. It's not that expensive to generate a new
    number. Heck, Random.nextInt(int) numbers are
    generated by throwing away numbers. There's a chance
    that it will never return.
    And if you are worried about that, I've got a server
    to sell you.
    ~CheersI myself (almost) always prefer clarity over performance. In this case,
    I think 2 * n + 1 produces both. You may say that I overdo it, for such
    a simple exercise. This I don't dispute. By the way, the way nextInt() is
    implemented is irrelevant, don't we like encapsulation anymore?

  • Draw histogram of random generator

    hi
    i has bulit  a random generator by use  LFSR+1D Cellular Automata
    i need to draw histogram of the system to check the distribution shape
    i have labview vision 
    can any help me to draw it
    thank in advace
    regards
    hi ?Q>
    Solved!
    Go to Solution.
    Attachments:
    random ge ca+lfsr.vi ‏14 KB

    Under Mathematics -> Probability and statistics you will find a histogram express vi that will help you.
    CLA
    www.dvel.se

  • Random generator for given distribution function

    I need to write a random generator, not for normal distribution only but for any distribution function.
    That function can be a black-box distribution function, or that can be a table [ x | f(x) ].
    For those not familiar with this term, distribution function is f(x) that returns the posibility of that the radmon number is lesser than x. f(-inf) = 0, f(+inf) = 1, x > y => f(x) >= f(y).

    I don't have my stats text books with me, but Google is your friend! :-)
    This looks like what we coverd in stats class:
    http://www.mathworks.com/access/helpdesk/help/toolbox/stats/prob_di7.shtml
    >
    Inversion
    The inversion method works due to a fundamental theorem that relates the uniform distribution to other continuous distributions.
    If F is a continuous distribution with inverse F^-1, and U is a uniform random number, then F^-1(U) has distribution F.
    So, you can generate a random number from a distribution by applying the inverse function for that distribution to a uniform random number. Unfortunately, this approach is usually not the most efficient.
    How do you get a random number from a uniform distribution? Easy: with java.util.Random, or some other java math package (I like http://hoschek.home.cern.ch/hoschek/colt/index.htm).
    The first link details some other methods, as will most stats text books.

  • Random generator

    Peeps, to the following match list how do i implent the random generator so that each match is picked at random but still checks the following conditions? help is desperatley needed, i tried using the guide
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html
    but to no avail - im REALLY stuck, thanks
    public class Matchlist
        private studentdetails sd = new studentdetails();
        /** matchList StringBuilder stores the match list in progress */
        private StringBuilder matchList = new StringBuilder();
        private int loop = 0;
        private int matches = 0;
        public Matchlist()
            sd.createstudentdetails();
        /** Method to create the actual match list, returns the list as a string */
        public String CreateMatch()
            int g;
            int y;
                for (g = 0; g < 4; g++)//g = game
                    for (y = 17; y > -1; y--)//y = green house
                        /** Check to see if the game is empty */
                        if (sd.getgh(y).getGame(g).equalsIgnoreCase(""))
                            for (int x = 0; x < 18; x++) //x = yellow house
                                if (sd.getyh(x).getGame(g).equalsIgnoreCase(""))
                                    if (sd.getgh(y).getC_lass() != sd.getyh(x).getC_lass())
                                        /** Check to see if the person has played the other person */
                                        if (sd.getgh(y).checkPlayed(sd.getyh(x).getName()) == false)
                                            /** Set the game to the name of the opponent played */
                                            sd.getyh(x).changeGame(g, sd.getgh(y).getName());
                                            sd.getgh(y).changeGame(g, sd.getyh(x).getName());
                                            /** Build the match list step by step using append with \n at the end to create a new line */
                                            matchList.append(sd.getyh(x).getName() + " vs " + sd.getgh(y).getName() + "\n");
                                            matches++;
                                            break;
                /** Convert the stringbuilder into an actual string, then return it */
                String completeMatchList = matchList.toString();
                System.out.println(matches);
                for (int i = 0; i <18; i++)
                    sd.getyh(i).getEmptyMatches();
                    sd.getgh(i).getEmptyMatches();
                return completeMatchList;
        }

    jermaindefoe wrote:
    lol, ok then, the code above is a match list generator that works on a set of conditions, the conditions dont need to be mentioned at the moment as that part of the code works, what does need to be mentioned though is the fact that in another class there is a student list, 2 lots of groups with 18 students each. what i want is to implement the random generator on my code so that players are picked at random and then the conditons are checked, if a match isnt found then another is picked randomly
    i just dont no how, i really would like some help if poss?Are you allowed to use java.util.Random?

  • Mail software-hundreds of undeliverable emails randomly generated

    Mac mail using iCloud. Undeliverable emails randomly generated and undeliverable

    Dear Brody:I turned on my computer this morning but when I connected to Outlook Express it asked for my password (which is saved on my computer) so I usually don't get this mesage. When I entered password the message returned. The problem reads:Jan 22 2014  There was a problem logging onto your mail server. Your Password was rejected. Account: 'Dot Lewis', Server: 'mail.bigpond.com', Protocol: POP3, Server Response: '-ERR invalid user name or password.', Port: 110, Secure(SSL): No, Server Error: 0x800CCC90, Error Number: 0x800CCC92  I have now tried to access mail on my labtop and get the same response.I have not changed any settings. Have Telstra changed something? Funnily enough I can access webmail (for the moment!!!) and I was able to send a test message in Outlook Express which was unexpected.Can you help?ThanksDotPS I did a Malwarebytes complete scan of my desktop computer but nothing was found.CheersD

  • Randomly Generate alpha-numeric strings?

    Hi, can somebody help me to randomly generate strings such as A1, B5, E 2, etc. The range for the values I need generated are [A-E][1-5]. I looked at lots of code for Random generating numbers, but found nothing related to what I need. I hope somebody can help me out here. Thanks!

    nevermind, i figured it out! thanks anyway

  • How to create a new user in IDM 8.1 with random generated password?

    Hi, i want create a new user using a modified tabbed user fom that cannot ask for password and confirm password to the administrator but randomly generate a new password (only when the form is opened in user creation) according to password policy and display it on the form.
    I think it is possible because Reset User Password Form does it, but i don't know how put this kind og logic in an other form.
    thanks
    Marco

    If you want to generate a users password randomly then you could take a look at the com.waveset.provision.PasswordGenerator class inside the Identity Mgr REF kit. Here's an example:
    <Rule name='generateRandomPassword'>
           <Comments>generate a random password</Comments>
           <RuleArgument name='accountId' value='Configurator'>
             <Comments>accountId of the user</Comments>
             <String>Configurator</String>
           </RuleArgument>
           <RunAsUser>
             <ObjectRef type='User' id='#ID#Configurator' name='Configurator'/>
           </RunAsUser>
           <block trace='true'>
             <defvar name='session'>
               <or>
                 <ref>context</ref>
                 <ref>display.session</ref>
               </or>
             </defvar>
             <defvar name='wsuser'>
               <invoke name='getObject' class='com.waveset.ui.FormUtil'>
                 <ref>session</ref>
                 <s>User</s>
                 <ref>accountId</ref>
               </invoke>
             </defvar>
              <defvar name='pwgenerator'>
               <new class='com.waveset.provision.PasswordGenerator'>
                 <ref>session</ref>
               </new>
             </defvar>
             <invoke name='generatePassword'>
               <ref>pwgenerator</ref>
               <ref>wsuser</ref>
             </invoke>
           </block>
        </Rule> You'll want to take the password.password field and inside the Default event handler check to see if waveset.id is null, if it is then call the Rule above.
    HTH,
    Paul

Maybe you are looking for

  • Calling a webservice from within Bex Web Application Designer

    Hi I have a web-template built with BEx web application designer which also contains textboxes. This text should be stored by calling a webservice (standard BI-documents are not an option). Can anyone tell me how I could call a webservice from within

  • Exchange/Outlook 2007 and Oracle Calendar Collaboration

    Hi Guys! I have a situation here in my incoming migration project. Is it really possible that an Oracle Calendar and Exchange/Outlook 2007 Calendar will collaborate or synchronize with each other? I only know that theres an Oracle Connector for Outlo

  • Purchase Orders for special/controlled items

    Hello everyone: I'm trying to create an aproval process for Purchase Orders that include special items that: - we only buy when one of our customers needs them (non-stock items), - have had no activity for 60 days or more, - and/or items that don't h

  • Regarding DBlink of source

    Hi everyone, I am stuck in a doubt I am having 2 different database.One is source and other is target Is it compulsary to install OWB in source system also?? I am asking this because while creating DB link it ask for userid and password.. what i need

  • Priority from Alert Data Service

    Hi Guys Well the problem is that I am not able to display 'priority' in the output table from the alert service... The priority comes as a text field in the alert service output port and i had initially loaded images in the backend (to show diff leve