Generating N-digit random number??
Hi All,
I need to generate N-digit random number, anyone can help me?
Thx in advance b4...
import java.util.*;
public class Try{
public static void main(String []args){
for(int i=0;i<100;i++){
System.out.println((int)(Math.random() * 10));
}Yes I saw the casting, no problem with it, but I did used it alot to generate me number between a range of 1 - 9
and if you want a range of 1 - 10, i just put a
1+(int)(Math.random() * 10)
Similar Messages
-
Hi,
Can any one help me to generate 8 digit unique random number, i have code some thing like
new Random().nextInt(100000000) + 1, but it generating 7 digit random number some times.
please give me the solution
thanks,
pvmkpvmk wrote:
Is there any alternate logic to generate 8 digit random numberAs already implied
if you want random numbers in the range [10000000;99999999]
generate random numbers in the range [0;90000000[ and add 10000000 -
I need to create a 17 digit random number to be used as a primary field in a database. They must all be unique. First, what is the best way to create a 17 digit random number, and second, how do I make sure it is unique?
I have a servlet that is parsing an email distribution
list and creating multiple users. For each user I
need to create a user id in the form of
"ID87890988909099900" that is unique. I do not know
how I would get Access to do this for me.Wow, you must have a lot of users. There aren't that many ants on earth.
Seriously, if the ID will always start with ID, then can't you just leave it off the key and add it when the ID is displayed? -
Hi All,
While running my application,I want to generate 3digit random number.
Is there any pre defined function.If not please suggest me some idea to get the same
Thanks in advanceSQL> EXEC DBMS_RANDOM.VALUE(100,999)
BEGIN DBMS_RANDOM.VALUE(100,999); END;
FOUT in regel 1:
.ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'VALUE'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
SQL> select dbms_random.value(100,999) from dual;
DBMS_RANDOM.VALUE(100,999)
338,5994241488838095483116070509848701
1 rij is geselecteerd.
SQL> select trunc(dbms_random.value(100,1000)) from dual;
TRUNC(DBMS_RANDOM.VALUE(100,1000))
918
1 rij is geselecteerd.Regards,
Rob. -
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... -
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 BabbThanks 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()); -
Hi guys,
i would like to have a text layer that changes it´s 4-digit number everytime it´s duplicated.
I found an expression that basically does that, but it also includes other values like "@" and "%".
s = "0" + Math.floor(random(10000));
while (s.length < 4) s = "0" + s;
The solution must be simple, I just really suck at expressions
Thanks for the help.
Cheers,
BjörnHi Dan,
i copied it to a new project now and it works as well (should have done that earlier, sry. Still weird ).
Now it generates a new numer every frame. Is there a way to keep the randomly genreated number over time?
Thanks for you help! -
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? -
Generate Random Number By sequence
How to generate random 4 digit random number using sequence or any other method. Please suggest
4 digit random numbers can be obtained by:
SQL> SELECT TRUNC(DBMS_RANDOM.VALUE(1000,9999)) FROM DUAL;
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
4002
SQL> /
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
4748
SQL> /
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
8328
SQL> /
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
3667
SQL> /
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
7464
SQL> /
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
4893
SQL> /
TRUNC(DBMS_RANDOM.VALUE(1000,9999))
4961In mine case there is no repetition using Oracle 11.2.0.1 on Windows XP.
Regards
Girish Sharma -
Generate Random number-Dynamic.
Guys,
I'm looking for a pl\sql block to generate a 10 digit random number.
Could someone help me out?
Also, is there anyway to make it dynamic?..ie.If i pass 4 to the procedure\function, it should generate a 4 digit number..Thoughts please?
Regards,
BhagatPlease read about [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_random.htm#sthref4646]DBMS_RANDOM in the manual.
-
Random number in range generator plz help!
hey hope someone can help me out, im sure its an easy one:
var tstArray:Array = new Array(1,2,3);
for (var a:uint=0; a<tstArray.length; a++)
var x:Number = Math.floor((Math.random()*tstArray[a]));
trace(x);
tstArray.splice(a,1);
i have this code but it doesnt do exectply what i want it to do. Im trying to generate a signle random number per click between 1 and 3 and when all numbers have been used up, remove this click listener.
if u can help it'll be much appriciated
thx paveluse:
var fp1:farm_part1=new farm_part1();
and any time you want to randomize an array use:
var tstArray:Array = fp1.randomizeF([1,2,3]);
package
*/import flash.utils.Timer;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.*;
import flash.media.Sound;
import flash.events.TimerEvent;
import flash.media.SoundChannel;
import flash.media.SoundTransform;*/
public class farm_Part1
public function randomizeF(a:Array):Array
{a.shuffle();
return a;
///////////////////////////// change nothing below /////////////////////////////////////////
function shuffle(a:Array)
var p:int;
var t:*;
var ivar:int;
for (ivar = a.length-1; ivar>=0; ivar--)
p=Math.floor((ivar+1)*Math.random());
t = a[ivar];
a[ivar] = a[p];
a[p] = t;
}//randomAnimal
}//class
}//package -
UDF to generate 4-Digit Positive Random Number
Hi,
I want to generate 4-Digit Positive Random Number in the Mapping for a field. Could anyone please provide Inputs or a UDF.
Regards,
VarunThis is the UDF I have Used
java.util.Random randomNumber;
String TransactionId = "" ;
randomNumber = new Random();
long longNumber = randomNumber.nextLong();
if (longNumber < 0)
longNumber = longNumber * (-1);
longNumber += 10000;
TransactionId = (String.valueOf(longNumber)).substring(0, 4);
return TransactionId ;
Thanks everyone for your Inputs -
How to generate a random number with at least 6 digits?
Hi all,
All is in the question. :-)
I would like to generate a random number but the function "random
number" in Labview isn't accurate enough.
Do you know an algorithm to generate a random number of 6 or more
digit?
Thanks,
PFHi PF,
It's simple. Use 2 random number functions in the same process. Now you
should have 2 distinct random numbers that have the same accuracy. Let's say
LV gives accuracy up to the thousandth (0.XXX), now if you divide one number
by 1000 and then add to the other number you should then have something like
0.XXXXXX. Actually, LV random number function can give up to about 17 digits
(decimal). If you are looking for more digits (>17 digits), the idea above
may not work, then the last thing you may want try is to generate two or
three random numbers then convert all these decimal numbers to fractional
strings chop off the 0 and dot then concatinate them together. After all
it's still a random number. How many digits do you want to get? Make sure
the indicators acce
pt that many digits?
Good luck
Louis.
P-F wrote in message
news:[email protected]..
> Hi all,
>
> All is in the question. :-)
>
> I would like to generate a random number but the function "random
> number" in Labview isn't accurate enough.
>
> Do you know an algorithm to generate a random number of 6 or more
> digit?
>
> Thanks,
>
> PF -
How to generate a random number within a specified tolerance and control that tolerance.
I am trying to simulate data without using a DAQ device by using a random number generator and I want to be able to control the "range" of the random number generated though. On the front pannel, the user would be able to input a nominal number, and the random number generator would generate numbers within plus or minus .003 of that nominal number. The data would then be plotted on a graph. Anyone know how to do this? Or if it's even possible?
Just for information sake, the random number is supposed to look like thickness measurements, that's why I want to simulate plus and minus .003 because the data could be thinner or thicker than the nominal.
Thanks in advance!!
Solved!
Go to Solution.You can create a random number with a gaussian probability profile using two equal distributed (0...1) random numbers and applying the Box Muller transform.
I wrote one many years ago, her it is. (LabVIEW 8.0).
Message Edited by altenbach on 04-12-2010 09:13 PM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
BoxMuller.vi 10 KB -
Is there any way to generate random number in CPO
Requirement : -
> I want to generate a random number from set of 1-9 numbers .is there any way in cpo ?
Thanks
SivaI created a process that uses 3 steps, all of which happen inside the engine rather than having to span out to a script, so it runs a lot faster.
Technically, it's pseudo-random...
Predefine Output Variable "Random Number" as type "Numeric"
Step 1: Format Date
Format string: fffffff
(that's seven lower-case letters "f")
Original date: [Process.Start Time]
Step 2: Format Date
Format string: ff\0\0\0\0\0
Original date: [Process Start Time]
Step 3: Set Variable
Variable to update: [Process.Variables.Output.Random Number]
New value: ([Workflow.Format Date.Formatted Date]-[Workflow.Format Date (2).Formatted Date])/100000
This returns a basically random number between 0 and 1 (so you can mulitply it by your maximum value) based on the numeric fraction of a second of the start time of the process.
Maybe you are looking for
-
How can I get the infoset name by giving the name of a program of a query?
How can I get the infoset name by giving the name of a program of a SAP Query? Regards, Subho
-
Help required... web services
hello...!!! How can I use MySql db for webservices? do I need to set context variables in deploytool? which string I'll need then? Also, I want to work my web service behind the firewall. I want to use jax-rpc tech. But I have no firewall environment
-
What is DTrace? in a nutshell?
G'Day Folks, It's great to see Sun making this open source, however I imagine many new people will wander to this forum to figure out what DTrace is. So lets discuss it. I'd describe DTrace as a mix of, .... 1. truss, struss, apptrace .... 2. mdb -p,
-
Time machine doesn't show backups
So I my logic board died and I decided to reformat my computer after it was repaired just for a fresh start. My time machine has all the backups, however, when I tried to restore from it, i opened up time machine to see that NOTHING was there. I set
-
There is no option to import e-mail from Windows Live Mail, *.eml files.
I have all the *.eml files exported to a folder and just need to install. What software addresses importing Windows Live Mail, *.eml files