Unique Random Values
OK, firstly, I am a Java n00b. I am not creating a program, just editing some source, but I need some help. What I need, are 5 different variables, each with a random value (integer) between 1 and 5 (inclusive), but, I don't want to variables to have the same value. The outcomes I'm looking for could be as follows:
t = 4
i = 3
g1 = 5
g2 = 1
y = 2
and then the next time the code is run I might get:
t = 1
i = 5
g1 = 4
g2 = 2
y = 3
Each variable has a random value (integer) between 1 and 5 (inclusive), but no 2 variables have the same value.
Here is what I tried:
Random rand = new Random();
int t = (rand.nextInt(5) + 1);
int i = (rand.nextInt(5) + 1);
int g1 = (rand.nextInt(5) + 1);
int g2 = (rand.nextInt(5) + 1);
int y = (rand.nextInt(5) + 1);
// While i is the same as t, make i a new random integer between 1 and 5. Yes? Or no...?
do {
i = (rand.nextInt(5) +1);
} while (i == t);
do {
g1 = (rand.nextInt(5) +1);
} while (g1 == t);
do {
g1 = (rand.nextInt(5) +1);
} while (g1 == i);
do {
g2 = (rand.nextInt(5) +1);
} while (g2 == t);
do {
g2 = (rand.nextInt(5) +1);
} while (g2 == i);
do {
g2 = (rand.nextInt(5) +1);
} while (g2 == g1);
do {
y = (rand.nextInt(5) +1);
} while (y == t);
do {
y = (rand.nextInt(5) +1);
} while (y == i);
do {
y = (rand.nextInt(5) +1);
} while (y == g1);
do {
y = (rand.nextInt(5) +1);
} while (y == g2);But when I use the variables in the next part of the program, sometimes it works, but sometimes 2 of them are the same. Sometimes even 4...
Can someone help me please?
Thinking about it now though, I would like to learnproperly. What is a good Java guide that starts from
scratch?
I think the Core Java books, by Cay Horstmann, are a
great way to start learning Java. I refered to his
books constantly durning college:
http://www.amazon.com/exec/obidos/tg/detail/-/013148202
/qid=1096410169/sr=1-1/ref=sr_1_1/104-3324308-3016709?v
glance&s=books
Sun's basic Java tutorial
Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
Bruce Eckel's Thinking in Java (Available online.)
Joshua Bloch's Effective Java
Bert Bates and Kathy Sierra's Head First Java.
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 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()); -
FYI, time to give back. I have received a number of excellent
responses from this forum, so here is one that might help someone
else.
I had found and modified the code below to generate a random
value (letters and numbers) to use as a member ID. With it you can
set the length of the generated value, as well as the content
(numbers, capital letters, lower case letters, even special
symbols). I chose a subset of capital letters along with 0-9 so the
result contained more numbers.I don't get it?! Why not just use something like
#createUUID()#, which is also apparently meant to be unique
everytime.
If you don't like the format of createUUID you can always run
a couple of functions over it to alter it a bit, like taking out
some of the dashes, or making it longer etc.
Maybe I'm missin the point...it's late here!! Me =
sleepy. -
How can i get the random values from database?
Hi,
i want to get random values from database.
I try my best find no solution
plz give solution in either sql query or java method.
thanks in advance.try this:
Give a numeric row-id to each row of database.
say (1-100) for 100 rows
In the program use random function to get random number between 0 and 1. this value u multiply with 100(or total number of rows) and take integer value of it . u then perform sql query to select the a row which matches randomly genarated value with row-id assigned to each row of database
madhu -
Selecting random values from an array based on a condition
Hi All,
I have a small glitch here. hope you guys can help me out.
I have an evenly spaced integer array as X[ ] = {1,2,3, ....150}. and I need to create a new array which selects 5 random values from X [ ] , but with a condition that these random values should have a difference of atleast 25 between them.
for example res [ ] = {2,60,37,110,130}
res [ ] = {10,40,109,132,75}
I have been thinking of looping thru the X [ ], and selecting randomly but things look tricky once I sit down to write an algorithm to do it.
Can anyone think of an approach to do this, any help will be greatly appreciated ...For your interest, here is my attempt.
import java.util.Random;
public class TestDemo {
public static void main(String[] args) throws Exception {
for (int n = 0; n < 10; n++) {
System.out.println(toString(getValues(5, 25, 150)));
private final static Random RAND = new Random();
public static int[] getValues(int num, int spread, int max) {
if (num * spread >= max) {
throw new IllegalArgumentException("Cannot produce " + num + " spread " + spread + " less than or equals to " + max);
int[] nums = new int[num];
int max2 = max - (num - 1) * spread - 1;
// generate random offsets totally less than max2
for (int j = 0; j < num; j++) {
int next = RAND.nextInt(max2);
// favour smaller numbers.
if (max2 > spread/2)
next = RAND.nextInt(next+1);
nums[j] = next;
max2 -= next;
// shuffle the offsets.
for (int j = num; j > 1; j--) {
swap(nums, j - 1, RAND.nextInt(j));
// add the spread of 25 each.
for (int j = 1; j < num; j++) {
nums[j] += nums[j-1] + spread;
return nums;
private static void swap(int[] arr, int i, int j) {
int tmp = arr;
arr[i] = arr[j];
arr[j] = tmp;
public static String toString(int[] nums) {
StringBuffer sb = new StringBuffer(nums.length * 4);
sb.append("[ ");
for (int j = 0; j < nums.length; j++) {
if (j > 0) {
sb.append(", ");
sb.append(nums[j]);
sb.append(" ]");
return sb.toString(); -
Finding unique minimum value from a set of values
Hi.
I have numbers in three columns - H, P, X
I need to compare numbers in each row and find out the lowest value and find out if there is a unique lowest value.
For example, in row 2
H2=2, P2=5.4, X2=2. In this row, both H2 and X2 have the lowest number, 2. Hence, the lowest number is not unique. I want to fill cells H2 and X2 in Yellow and cell P2 in Red.
In row 3,
H3=2, P3=5.4, X3=4. In this row, H3 has the lowest unique number, 2. I want to fill cell H3 in Green and cells P3 and X3 in Red.
Green = lowest and unique
Yellow = lowest but not unique
Red = Not the lowest
I can use the MIN function to find the least number but I do not know how to identify the unique lowest number if available.
Thanks for your help.Select for example H2:H100. I will assume that the active cell within the selection is in row 2.
Color the cells yellow (this will be the default)
On the Home tab of the ribbon, click Conditional Formatting > New Rule...
Select 'Use a formula to determine which cells to format'.
Enter the formula
=OR($H2>$P2,$H2>$X2)
Click Format...
Activate the Fill tab and select red.
Click OK, then OK again.
On the Home tab of the ribbon, click Conditional Formatting > New Rule...
Select 'Use a formula to determine which cells to format'.
Enter the formula
=AND($H2<$P2,$H2<$X2)
Click Format...
Activate the Fill tab and select green.
Click OK, then OK again.
The formulas for columns P and X are similar, switching the roles of the three cells.
Regards, Hans Vogelaar (http://www.eileenslounge.com) -
Need ABAP code to make unique hierarchy values - Request prompt help
hi
<removed>
I am new to SAP. Please help me in the following
I require an ABAP code for the following scenario
I have a simple hieraarchy. The hierarchy is
SEG -> fam -> clas -> comm
The values of the seg , fam, cla, com......all will be charecter values
But in some cases the values will be NOT_KNOWN
If the values are NOT_KNOWN i need to change them as NOT_KNOWN_1, NOT_KNOWN_2...like that unique charecter values
should be replaced for NOT_KNOWN
Example
SEG->FAM->CLA ->COM
Clothing -> Mens wear -> Designer garments -> NOT_KNOWN
Construction -> equipments -> machinery->NOT_KNOWN
Computers -> Laptops -> Imported -> NOT_KNOWN
-> desktops ->flat monitors -> Indian
-> imported -> NOT_KNOWN->
NOT_KNOWN -> baggages
This should be changed to
SEG->FAM->CLA ->COM
Clothing -> Mens wear -> Designer garments -> NOT_KNOWN_1
Construction -> equipments -> machinery->NOT_KNOWN_2
Computers -> Laptops -> Imported -> NOT_KNOWN_3
-> desktops ->flat monitors -> Indian
-> imported
-> NOT_KNOWN_4 ->
NOT_KNOWN_5 -> baggages
This is to make them unique nodes to upload them in hiereachy
Data is coming from database tables and i was not supposed to do anything in database and the incomin
data needs to finetuned like this to update them in cube
So I like to have some coding which will enable this to work in the start routine
If start routine is not the right option, where else we can do coding
<removed>
Regards
KCdata : w_suff_n(8) type n,
w_suff_c(8).
loop at data_package.
if data_package-<fieldval> = 'NOT_KNOWN'.
w_suff_n = w_suff_n + 1. w_suff_c = w_suff_n.
shift w_suff_c left deleting leading '0'.
concatenate data_package-<fieldval> w_suff_c into data_package-<fieldval>.
modify data_package.
endif.
endloop.
*Change <fieldval> in the above to the actual field name. -
Weighted random value (1-10) e.g.3 will be 50 % of records
Hello,
i need to generate random values into my table. For the simplification, lets say that i need to generate values in range from 1 to 10. For this there is a lot of ways.
e.g. UPDATE test_number SET random_value = round (dbms_random.value (1,10))
But what I need is something like weighted random values. I need random values to be inserted into column, but I need e.g. 3 to be inserted more times than other values e.g. if i have 100 rows i want to have 3 in 50 random rows
Do you have any idea how to achieve it?
Thanks a lot for any help or reply !Hi,
You can do something like this:
WITH got_p_num AS
SELECT LEVEL AS id
, FLOOR (dbms_random.value (1, 19)) AS p_num
FROM dual
CONNECT BY LEVEL <= 10
SELECT id
, p_num
, CASE
WHEN p_num < 3 THEN p_num
WHEN p_num < 12 THEN 3
ELSE p_num - 8
END AS r_num
FROM got_p_num
ORDER BY r_num
;If you want the number 3 to appear on half of the rows; that means that, out of 18 random numbers, you expect 3 to occur 9 times, and the other numbers to appear once each. The query above generates random integers in the range 1 through 18 inclusive, and calls this number p_num. The CASE statement maps p_num to what you really want, a n integer between 1 and 10, with 3 occurring 9/18 (= 1/2) of the time.
Instead of using a CASE expression, you might want to create a table, that has one row for every number that can be in the output, and the probability of picking that number. You could then join to that table to convert the raw random number to the id that you want.
Edited by: Frank Kulash on Oct 6, 2011 3:36 PM -
Hi there!
just a little question:
I want to insert into a table random values between -2 and 2, which shoul differ for every row. When I'm writing
FOR n IN nodes LOOP
FOR EACH n2 IN nodes2 LOOP
IF (n2.layer_ = n.layer_ +1) THEN
INSERT INTO nn2_links (lfdnr, sourceid, destid, weight, delta_weight, Zone_)
VALUES (lfdnr#, n.nodeid, n2.nodeid, dbms_random.value(-2,2), 0, Zone#);
lfdnr# := lfdnr# +1;
END if;
END LOOP;
END LOOP; I'll get the same value for all records fullfilling the IF-criteria in the middle. What can I do? Must I write another loop?
greetings
~MelOP states that she / he would like to have distinct values for every row but instead gets the same value for all rows.
To OP:
Sorry mel, not much help. Can't see the error in your script.
When I put a anonymous block together, it runs smoothly:
SQL> set serveroutput on
SQL> declare
2 outn number;
3 cnt number;
4 begin
5 cnt := 1;
6 while cnt <=10 loop
7 select dbms_random.value(-2,2) into outn from dual;
8 dbms_output.put_line('Wert: '|| to_char(outn));
9 cnt := cnt + 1;
10 end loop;
11 end;
12 /
Wert: 1,94760933757912513703045869459081746304
Wert: ,1850733416444459069798272966494986884
Wert: -1,28557676353717597230879638125649445416
Wert: -,20789721958144010481059709280045566588
Wert: -1,46550435548323732535026606603236048092
Wert: -1,48594688953909777344516402506798302304
Wert: -,2162809554864053530960985675499170964
Wert: 1,71049071188915501435899411045229762652
Wert: ,53354523369664937673204584890644358732
Wert: -,96917849158672171927090500710866039384
PL/SQL-Prozedur wurde erfolgreich abgeschlossen.
SQL> -
Hi
I made an add-on that makes stock transfers via DI API. The add-on has been running for two months with more than 10,000 stock transfers with almost no problems.
The company that is using the add-on have all their products managed by serial/batch numbers.
But just with one transfer Im getting the error in the stock transfer Add() method:
"Unique field value does not match the system serial number [(----)29-52]"
And I tried to debug it without success, I checked that the system serial numbers exists in the origin warehouse and are available. And I really can't find where is the problem.
If somebody knows what this error means, please let me know.
Thanks in advance,
Regards,
AllanHi János, thanks for your answer.
I found what was the problem, it was not exactly what you told me, but you gave me some insights to found the problem.
The thing is that Im using UDT's to store the information of stock transfers (before creating a real SAP stock transfer), because of the funcionality of the add-on. After some user have done some steps or validations, the add-on actually does the real SAP stock transfer.
The problem here was that my tables had some InternalSerial for some Item, for example the serial A-234, and before the real SAP stock transfer was made, they changed the serial from A-234 to A234 (in the serial number management). So the add-on was trying to create the transfer with the serial A-234, but the serial A-234 no longer exists.
I have to create a validation that if they change the serial number for an item, I have to change it in my UDT's.
On the other hand, Im not sure, but I think that I read before that you made a Warehouse Management add-on. This add-on that Im working now is a kind of warehouse management.
Im having a lot of headaches because the poor accessibility to the user fields in the OSRI and OIBT tables. Im sure that you have faced problems with this. If you have any tips or advices about this it would be greatly appreciated.
Thanks again,
Regards
Allan -
Get a random value out of a query result
I have a query:
select id
from class_schedule
where id not in (
select distinct(event_id) from trainer_schedule)I want to pick up a random value from this query result and assign it to a varible e.g. randomID.
please helphere is the example
SQL> SELECT empno,ename
2 FROM (
3 SELECT empno,ename
4 FROM EMP
5 ORDER BY dbms_random.VALUE)
6 WHERE ROWNUM = 1;
7876 ADAMS
SQL> /
7566 JONES
SQL> /
7900 JAMES
SQL> /
7844 TURNER
SQL> -
Select statement for JDBC receiver synch scenario for capturing random value from ECC portal
Dear Experts,
I am working on ECC <----> SAP-PO 7.31 <----> JDBC synchronous scenario. I am clear about the config part except the Select statement. I will be
capturing 2 random values from the portal i.e. VendId and VendName in ECC to get the vendor details like Vendor Country, Vendor Status, Vendor Contact , Vendor Address etc from JDBC vendor table/view VENDETAIL.
What would be the select statement to capture the random values for ECC portal? My select statement would look some thing like this..
Select f1,f2,f3,f4 from table VENDETAIL where key1 = "VendId" and "VendName"
Please suggest if the above select statement works for the above scenario...
Regards
RebeccaHi Rebecca,
Your statement should work fine.
Please see the statement we use below.
SELECT eT_cashier, eT_proc_yn, eT_proc_date FROM eTest WHERE eb_proc_yn = 'N'
Just remember to update the change indicator so that you dont duplicate your records.
UPDATE eTest SET eb_proc_yn = 'Y' WHERE eb_proc_yn = 'N'.
Regards,
Jannus Botha -
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();
} -
Build array from random values via ethernet
Am trying to save data that comes from ehternet ((random values (modbus protocol)) in an array.
I am using an index array.....but all the values are the same!! How can I sort them??
It functions correctly with a for loop with random numbers build.......but it doesn't work with the data from ethernet.
Can someone please help me??
Attachments:
Data.vi 16 KBchendel wrote:
Am trying to save data that comes from ehternet ((random values (modbus protocol)) in an array.
I am using an index array.....but all the values are the same!!
You just read the same shared variable 100 times within a few nanoseconds. Apparently, the variable gets modified less often on the other end.
chendel wrote:
How can I sort them??
If all array values are the same, they are already sorted.
You need to rethink your code. maybe you can make the shared variable an array and write the entire random array on the other end, the read it out once.
LabVIEW Champion . Do more with less code and in less time . -
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?
Maybe you are looking for
-
Is there a way to create a line consisting in two different lines?
Like the lines that appears in maps: some are single lines (black stroke) but there are others that are f.e. a yellow line with other red thinner line inside. Can someone tell me how to do that? i'm drawing a map and it would be so much better if I
-
How do I get flagged email on iOS7 to also flag in Outlook?
After upgrading to iOS7, whenever I flag an email in my Outlook account on the phone, it no longer also flags the email in MS Outlook on my laptop. Is there an additional setting to enable this or, if not, where can I submit a bug to Apple? With all
-
HELP ! : PODCAST SUBSCRIPTIONS LISTED TWICE AFTER LIBRARY RESTORE
I have restored my entire itunes library onto my new computer. When I restore my podcast subscriptions by drag and dropping the 'Podcasts' playlist over to the library a number of the subscriptions get listed twice. How do I get all of the podcast ep
-
I have been trying to upgrade my HP F4180 to windows 7 but no mater which way I try it loads everything but when I connect the USB cable to the printer I get a error on HP Deskjet F4100 series. The rest of the files are ok. I sent for a new disk and
-
Referring external DLLs in WPF crashing Application
I have used following 3 SQL Server (Version SQL Server 2008 R2) DLLs in a WPF project: Microsoft.SqlServer.ConnectionInfo Microsoft.SqlServer.Management.Sdk.Sfc Microsoft.SqlServer.Smo Project works fine on the machine on which it was developed. Howe