One more java random number question

which of the following codes are correct to generate a random number between start and end inclusively. Both methods seem to be working for me but im pretty sure one would be incorrect
int num = (int)(start + (Math.random() * (end-start)));
int num = (int)(start+1 + (Math.random() * (end-start)));

I say neither of them work. Let's use 5 and 8 as our start and end. In the Math class, random() is said to generate a random number, x, where 0 <= x < 1.
The first one:
First, multiply by 8 - 5 (3).
0 <= x < 3
Then, add 5.
5 <= x < 8
Then, casting to an int, we get a number 5 - 7.
The second one:
First, multiply by 8 - 5 (3).
0 <= x < 3
Then, add 6.
6 <= x < 9
Then, casting to an int, we get a number 6 - 8.
The "correct" way:
int num = (int) (Math.random() * (end - start + 1) + start);First, multiply by 8 - 5 + 1 (4).
0 <= x < 4
Then, add 5.
5 <= x < 9
Then, casting to an int, we get a number 5 - 8.

Similar Messages

  • Java random number generator

    Hi does java have a random number generator. If it does can you point me to it please. Thank you.

    you can use "java.Math.random()" this function returns a value which is greater than or equal
    to 0.0 and less than 1.It returns a double value,so you can multiply by 10 and cast it to int,so that it
    can produce numbers between 0 & 9.Yes, you can do that. But, as stated before, java.util.Random has methods that are easier to use for random int values than using java.Math.random is for random int values. It all depends what the OP wants. The OP hasn't come back with additional questions, or to say that he found his answer. So, we don't know whether he has his answer (he has several options now!) or not. :)

  • AppleScript Random Number Question.

    I know there are several "guess a random number" AppleScript examples on the web, but I tried writing my own to see if I could pull it off.  Works pretty good except for one bug.  If the random number is lower than 10 (single digit) and I guess a number 10 or higher, my script comes back saying my guess is too small!  Everything in my code looks reasonable to me, but obviously I'm overlooking something!  Here's my code:
    set rnd to (random number from 1 to 20)
    set rnd to rnd as string
    set num to 5
    repeat 5 times
              if num = 1 then
                        set anw to text returned of (display dialog "You have only 1 guess left!
    Pick a number from 1 to 10." default answer "" buttons {"OK"} default button 1)
              else
                        set anw to text returned of (display dialog "You have " & num & " guesses left!
    Pick a number from 1 to 20." default answer "" buttons {"OK"} default button 1)
              end if
              if anw < rnd then
      display dialog "Too Small!" buttons {"OK"} default button 1
              else
                        if anw > rnd then
      display dialog "Too Big!" buttons {"OK"} default button 1
                        else
                                  if anw = rnd then
      display dialog "Correct!" buttons {"OK"} default button 1
                                            return
                                  end if
                        end if
              end if
              set num to num - 1
    end repeat
    display dialog "You have run out of guesses!
    The number was " & rnd & "." buttons {"OK"} default button 1

    you need to convert the variable anw to an integer, otherwise your script will compare anw to rnd as text strings (and text strings beginning with 1 are always small).  add the following code before you do your comparisons:
              set anw to anw as integer
    also, your script will be cleaner if you use the 'else' command in your if statement:
              if anw < rnd then
                      display dialog "Too Small!" buttons {"OK"} default button 1
              else if anw > rnd then
                      display dialog "Too Big!" buttons {"OK"} default button 1
              else
                      display dialog "Correct!" buttons {"OK"} default button 1
                      return
              end if

  • Random Number Question

    while (true) {
    randomInt = (int) (Math.random() * 100);
    System.out.println(randomInt);
    I try to create random number from 0 -100. However, it always randomize to the same few integers. Why this happens?

    Math.random() uses the current time in milliseconds to
    form random numbers. So you need to have a delay in
    there before getting the next random number or you'll
    generate random numbers too fast, and end up with the
    same number(s).I don't think that's right. According to the docs:
    "When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression
    new java.util.Random
    This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else"

  • Another random number question

    Say I only want values between 0 and 1
    i.e 0.32, 0.56, 0.98
    Using the Math.random() function
    does the seed go in the ()'s like Math.random(1)
    Will that work?
    In the previous posting the num2 acted as the seed

    To summarize:
    1st option: Use Math.random() to get a float between .0 and 1.0 without the possibility to set the seed
    2nd option: Create a new generator with
    java.util.Random gen=new java.util.Random()or
    java.util.Random gen=new java.util.Random(longValueHere)if you want to set the seed, and use gen.nextFloat() to get a float between .0 and 1.0.

  • Invoking command prompt & executing a java class from one more java class

    Hi,
    I have a problem with my application. I need to develop an editor which compiles and interpretes java programmes. I am develoopping it in Java (Swing and pure Java). I have no problem in compiling a java programme from my editor. But while execuing if any body writes a programme which has console input the system hangs. I am using Runtime.exec() method to call command prompt of Win'2000. My editor is working fine for the programmes written without console input in my editor. I want the same type of input acceptance as JCreator / Vim editors accept.
    How can i achieve this? Please give me some source code help for my requirement.

    When you create a Process object from executing a command you can grab it's input and output streams. Using these, and a text area, you can create a "virtual terminal" for your user to work with their console programs. The rest is just details :)

  • Multiple Random Number Generators

    I'm writing a program to simulate the tossing of two coins: a nickel and a dime. I want each coin to have its own independently generated set of outcomes. At the core of my logic is a call to one of two random number generators.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#random() says that "...it may reduce contention for each thread to have its own pseudorandom-number generator." It also makes reference to Random.nextDouble.
    If the first call to random() creates the random number generator, and any subsequent calls to random() supply the next number in the series, what code do I use to setup multiple generators? I want each coin to have its own series.
    What is the need for nextDouble()? Should I be using nextDouble() or random() to get subsequent numbers from these generators?
    Thanks for you help.
    Jim

    Random rnd1 = new Random(7);
    Random rnd2 = new Random(17);Unfortunately, the close seed states will make for
    very closely related sequences from each.And you base that statement on what?Close seeds make for close sequences with lcprng's.
    It's less obvious for these:
    // First ten calls to nextInt()
    -1156638823
    -1149713343
    -1552468968
    -876354855
    -1077308326
    -1299783908
    41356089
    -1761252264
    1495978761
    356293784
    2107132509
    1723477387
    -441191359
    -789258487
    -1105573998
    -46827465
    -1253369595
    190636124
    -1850488227
    -672335679But that's because the generator is 48 bits.
    If you look at sequential seeds you get really bad results...
    // first 50 seeds, [0, 50), one call to nextInt
    0  -1155484576
    1  -1155869325
    2  -1154715079
    3  -1155099828
    4  -1157023572
    5  -1157408321
    6  -1156254074
    7  -1156638823
    8  -1158562568
    9  -1158947317
    10 -1157793070
    11 -1158177819
    12 -1160101563
    13 -1160486312
    14 -1159332065
    15 -1159716814
    16 -1149328594
    17 -1149713343
    18 -1148559096
    19 -1148943845
    20 -1150867590
    21 -1151252339
    22 -1150098092
    23 -1150482841
    24 -1152406585
    25 -1152791334
    26 -1151637087
    27 -1152021836
    28 -1153945581
    29 -1154330330
    30 -1153176083
    31 -1153560832
    32 -1167796541
    33 -1168181290
    34 -1167027043
    35 -1167411792
    36 -1169335537
    37 -1169720286
    38 -1168566039
    39 -1168950788
    40 -1170874532
    41 -1171259281
    42 -1170105035
    43 -1170489784
    44 -1172413528
    45 -1172798277
    46 -1171644030
    47 -1172028779
    48 -1161640559
    49 -1162025308

  • Also Question about create Random number

    What's the best way to create random number in main method, which will allow the number (random) to be stored into content of queue. I was thinking somewhere along the road, is this the appropriate way to handle this?
    import java.util.*;
    public static void main(String[] args)
            Queue q=new Queue();
    Random random = new Random ();
            for(int i=0;i<12;i++)
               q.add(random);
              

    Close, but not quite. That will add the same random number number generator (no random numbers) to the queue 20 times.
    Look at the methods in the Random class to find the one that suits your needs for using the generator (the Random) to generate a random number.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html

  • One more generics question

    One more dumbshit generics question...
    Is there a way to do this without the warnings or the @SuppressWarnings({"unchecked"})
       * Returns the index of the last occurrence of the specified element in this
       * list, or -1 if this list does not contain the element.
      //@SuppressWarnings({"unchecked"})
      public int lastIndexOf(Object object) {
        int i = 0;
        int last = -1;
        for(Node<E> node=this.head.next; node!=null; node=node.next) {
          if (node.item.equals((E) object)) {
            last = i;
          i++;
        return(last);
    produces the warning
    C:\Java\home\src\linkedlist\LinkedList.java:313: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: E
          if (node.item.equals((E) object)) {
                                   ^... remembering that List specifies +public int lastIndexOf(Object object);+ as taking a raw Object, not E element, as I would have expected.
    Thanx all. Keith.
    PS: Crossposted from the tail of http://forum.java.sun.com/thread.jspa?messageID=10225418&#10225418
    which nobody has answered, I presume because the thread is marked as "answered".

    I'm not sure you understood or if I made myself clear. Or perhaps I'm missing a vital detail in your implementation.
    I'm talking about the cast to E in this line:if (node.item.equals((E) object)) {Object.equals() takes a parameter of type Object. So the cast to E is superfluous. That cast is what's causing the warning. You remove the cast => no more warning => you can remove the SuppressWarnings annotation.
    Unless your E's have an overloaded equals() that takes an argument of type E. In that case you'll have to live with it.

  • Credit card number change, your company can not charge , so , what can I do ?because I buy one year plan , but the plan stop already  ,I can not change the credit card details.So, I need to buy one more year or can continous the paln with changing the cre

    credit card number change, your company can not charge , so , what can I do ?because I buy one year plan ,
    but the plan stop already  ,I can not change the credit card details.
    So, I need to buy one more year or can continous the paln with changing the credit number?

    Hello pen pang,
    if your Photoshop is a part of Creative Cloud you can use "Manage your membership and payments|Creative Cloud" at
    http://helpx.adobe.com/x-productkb/policy-pricing/membership-subscription-troubleshooting- creative-cloud.html >>>
    Payment & credit card >>> Help changing the credit card on your account >>> from there see what hints are listed.
    On the other hand I'm sure that you can use the recommended procedure with a "normal" PS too.
    If necessary and for further questions click through http://helpx.adobe.com/contact.html and if "open" please use the chat, I had the best experiences. I quote from Adobe's employee Preran: The chat button is activated as soon as there is an agent available to help.
    If you need these explanations in another language, please use "Change" at the end/bottom of the website from above
    Good luck!
    Hans-Günter

  • I just downloaded and instaled firefox 4. Now, everytime I institute a command I get a po[p-up from Java script that tells me to uninstal set. I cannot go on untin I press ok and then I am good for one more command and it starts with the pop-up again.

    I'm not even sure if this is an extension or plug-in and all I can tell you is what I have already stated. I can only make one command at a time and after each one I get a pop-up from Java script that says uninstal set. I must depress ok to move on, but only for one more command and it starts over again. This also happened when I tried to instal firefox 4 a couple months ago and I deleted the program and went back to an earlier version.

    Mail troubleshooting - Yosemite
    Troubleshooting sending and receiving email messages
    Troubleshooting sending email messages
    SMTP servers keep going offline

  • A simple question on random number generation?

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

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

  • One more question.

    Hey again. I am probably going to go get my iMactoday or tomorrow. But I have one more question. I am aware that Macs are pretty much prone to viruses. But!!! When I download a version of Windows on Bootcamp, will I still have the amazing security, or will it be viruses like owning a PC? Thank you very much!

    HI,
    *"I am aware that Macs are pretty much prone to viruses."*
    Just the opposite. Windows users are the one's vulnerable to a virus.
    You will need anti virus software on the Windows partition.
    Carolyn

  • One more question..hehe :)

    I have one more question..sorry! How do I change the information in my google search (the description). I can't find it anywhere. Thanks

    and...
    i was also wondering if it is possible to change the title of my website when i search for it @ google & yahoo. you know how when you search for anything and it has the first line of blue hyper linked text? how do i change that on my website. is it the title (the one by the blue dot) or the first page? thanks!

  • One more question about "snap to" points in audio objects

    sorry, one more question people.............. is there a way to set a "snap to" point in an audio region? Can I have logic set a point, or an "anchor" within an audio region that would coincide with the cursor. Once I get the cursor to a bar or a beat, is there a command that would allow a "snap to" point to be created in an audio object? That way I could clean up any "noise" or "chatter" at the beginning of an audio bounce or any audio object, and still have no problem pasting it all over my arrangement. I'm sure it's in here somewhere, but can't find it in the manual..
    thanks again!!!

    The anchor point in an audio region can be moved to wherever you want it to be. Let's say you recorded a loud piano bass note and afterwards you trimmed the file so that the attack of this sound happens right at the beginning of the audio region. Your anchor point will now coincide with the begnning of that region. This means that you can place that audio at, say, bar 37 and it's guaranteed that the attack of that sound will play exactly at bar 37. In this case anchor point = position of audio region in the Arrange Window.
    Even though you haven't played a MIDI note into the song in order to place this audio region, an "event" is generated for this sound which can be viewed in a special version of the Event Editor which shows the position of all audio regions in the arrangement. Access this by simply clicking on a blank area of the Arrange window and then opening the Event Editor.
    So let's say this sound is positioned at bar 37. Open the Event Editor (as described above) and you'll see an event at 37 1 1 1 and the name of that audio region to its right. In this case, the event's position = the start of the sound file = the position of the anchor within that sound file. If you changed the position of that event to 38, or 109, or 3, that audio region will be "triggered" at any of those positions. That sound will always "attack" on a downbeat.
    Now let's say you reversed that pinao note in order to create a dramatic swell into a section of your song. (Open the sample editor and use the Reverse function). At this point, the anchor point is still positioned at the beginning of the file! Play back the sequence (from our bar 37) and the audio will play back from bar 37, only backwards this time; the peak of that piano note will be at some point later than 37.
    So let's say you wanted to position this sound so that it hits exactly on the downbeat of bar 37. How do you do it? Well, you could always slide the audio file in the Arrange Window and try to line up the attack of the audio waveform with the downbeat of bar 37, but there's an easier way...
    Open the sample editor and move the anchor point to the end of the file, coinciding with the peak of the waveform (the piano's attack is now at the end because we reversed the audio). Next, close the sample editor window, click on a blank area in the Arrange Window and open the Event Editor. You'll see that this audio region is still positioned at bar 37, but the actual beginning of the sound file now starts before bar 37. Now when you play back, Logic will start playing that sound file before bar 37, but the audio's peak will be lined up at bar 37.

Maybe you are looking for

  • Unexpected reboot of Norestart servers.

    Some servers which are marked as "not to be rebooted" are getting restarted in their maintenance window. No packages or patches were pushed or installed on these servers.. I saw similar issues on tech net but this ques is unanswered In the event view

  • Oracle 9.2.0.6 patch set

    After installation and post installation done I still have OWM module as 9.2.0.1 as shown in sqlplus with this query. select comp_id, version, status from dba_registry; How do I update this module to 9.2.0.6 because one of my supplier request this ve

  • FCP serial number recovery.

    I have had a major hardware fault, and have had to buy a new laptop!!! I have recovered my data from Time Machine, but all my serials for FCP don't seem to have transferred, and the ap won't run! Luckily I have access to the old laptops HDD (via and

  • Having some trouble here

    ok, i tried this, yet does not seem to want to work. I am trying to write a java program that calculates 1/2 - 2/4 + 3/6 - 4/16 + ((-1) ^ (n+1))(n/2^n) ok, here is what i have so far: package project6; import javax.swing.JOptionPane; public class Pro

  • Windows 8.1 - Error Installing Netflix : 0x80073cf0 Error

    I am not able to install Netflix App. from the store. I am able to install other apps, its just this one which errors out. I get the error 0x80073cf0 when i try to install Netflix. I tried the option to: - Stop windows update serivce - rename c:\wind