COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### Is there a better way to do this? 87480

• Email
• Follow

```I want to pick six unique numbers between 1 and 49 100 times.
I thought that rather than do some sort of fancy checking before
adding a picked random number into an array that I would just keep
picking 6 numbers until they are all unique.

Here is my code

<SSCCE>
import java.util.Random;
public class PickSix {
public static void main(String[] args) {
int [] sixUniqueNumbers = new int[6];
for (int count=0;count<=100;count++ ) {
boolean allUnique = false;
while ( ! allUnique)
{
int [] sixNumbers = new int[6];
for (int i = 0;i<=5;i++)
{
Random generator = new Random();
int t= generator.nextInt(49) + 1;
sixNumbers[i] = t;
}
allUnique = testUnique(sixNumbers);
if (allUnique == true)
sixUniqueNumbers = sixNumbers;
}
for (int i=0;i<=5;i++)
System.out.print(sixUniqueNumbers[i] + " ");
System.out.println("");

}
}
public static boolean testUnique(int [] numberList)
{
boolean gotCha = true;
for (int i=0;i<=4;i++)
{
for (int j=i+1;j<=5;j++) {
if (numberList[i] == numberList[j]) {
gotCha = false;
break;
}
}
}
return gotCha;
}
}
</SSCCE>

If I were to switch it to use the Integer type objects and an Array
List, would it be easier to determine the uniqueness of the ArrayList.

If I had to pick 100 numbers between 1 and 3000 100 times, it might
get a little CPU intensive, so I'd like to have something better.
Eventually what I want to do is pick 6 numbers between 1 and 49 one
million times and then count the frequency of each number.

```
 0
Reply printdude1968 (152) 4/15/2007 2:34:08 AM

See related articles to this posting

```printdude1968@gmail.com wrote:
>I want to pick six unique numbers between 1 and 49 100 times.
...
>If I were to switch it to use the Integer type objects and an Array
>List, would it be easier to determine the uniqueness of the ArrayList.

I am not quite sure whether you mean the ArrayList to
be the source 'pool' of all numbers, or the resulting set of
random numbers.

>If I had to pick 100 numbers between 1 and 3000 100 times, it might
>get a little CPU intensive, so I'd like to have something better.

Sure could.  That is why I would recommend using an ArrayList
for the pool of all numbers, and removing each one as it is chosen.

--
Andrew Thompson
http://www.athompson.info/andrew/

Message posted via http://www.javakb.com

```
 0

```<printdude1968@gmail.com> wrote in message
>I want to pick six unique numbers between 1 and 49 100 times.
> I thought that rather than do some sort of fancy checking before
> adding a picked random number into an array that I would just keep
> picking 6 numbers until they are all unique.

You could create a array of type boolean with array indexes 0 to 49 (just
don't use 0).
Each time you pick a number consider it an array index,
if that array element is false then
setthe array element to true.

```
 0

```printdude1968@gmail.com wrote:
....
> Eventually what I want to do is pick 6 numbers between 1 and 49 one
> million times and then count the frequency of each number.
>

There is a standard algorithm for shuffling an array, the Fisher-Yates
java.util.Collections contains a Java implementation.

1. Initialize an array with the numbers from 1 to 49.

2. Do the first 6 iterations of a Fisher-Yates shuffle.

3. Depending on how it is implemented, either the first 6 or the last 6
elements are in their final positions, and are 6 elements chosen at
random from the array. Copy those elements as your selection.

Without reinitializing, repeat steps 2 and 3 another 999,999 times.

Patricia
```
 0

```Hal seems to have a good idea. Pulling Integers out of an
ArrayList<Integer> would be nice, but then you'd have to initialize
that entire list before you can start.

A complete method for the boolean form might be as follows:

/**
* Randomly picks 'valCount' unique numbers between 0 and 'maxVal'-1.
*
* @param maxVal
*            highest possible random number
* @param valCount
*            number of random numbers to pick.
* @return an int[] of the values picked.
*/
public static int[] pickRandomValues(int maxVal,int valCount)
{
boolean[] v = new boolean[maxVal];
java.util.Arrays.fill(v, true);
int[] numbers = new int[valCount];
int foo = valCount;
int index;
while(foo > 0)
{
index = (int)(Math.random()*maxVal);
if( v[index] )
{
v[index] = false;
foo -= 1;
}
}
index = 0;
for(int i = 0; i < maxVal && index < numbers.length; i += 1)
{
if( !v[i] )
{
numbers[index] = i;
index += 1;
}
}
return numbers;
}

```
 0

```Patricia Shanahan wrote:
> printdude1968@gmail.com wrote:
> ...
>> Eventually what I want to do is pick 6 numbers between 1 and 49 one
>> million times and then count the frequency of each number.
>>
>
> There is a standard algorithm for shuffling an array, the Fisher-Yates
> java.util.Collections contains a Java implementation.
>
Wow! Great. Thanks for the link. Robert Sedgewick, one of my
all time favorite authors has a new book..
>
> Patricia

```
 0

```<printdude1968@gmail.com> wrote in message news:1176604448.052994.90580@l77g2000hsb.googlegroups.com...
|I want to pick six unique numbers between 1 and 49 100 times.
| I thought that rather than do some sort of fancy checking before
| adding a picked random number into an array that I would just keep
| picking 6 numbers until they are all unique.

As long as you are selecting a small enough subset of your range, 12.2% in this case,
you should not have to discard too many of your sets, so that may be ok for your purposes.
It's not the best practice to discard output sets from (pseudo)random number generators,
because you may disturb the random distribution of your results.  Again, I don't think you'll
have much of a problem in this case.

I would prefer to model the number set 1-49 in a List, with an ArrayList implementation.  As each
number is chosen (by index, from a decreasing range), I would remove it from the List and append it
in my output list.  After each set of 6 numbers has been collected, put them back at the end of the
ArrayList (addAll method), and process the next set of numbers.

This method will work equally well with higher percentages of the set being selected, without unnecessarily
disturbing the pseudorandom sequence or throwing away unsuitablr selection sets.

| Here is my code
|
| <SSCCE>
| import java.util.Random;
| public class PickSix {
| public static void main(String[] args) {
| int [] sixUniqueNumbers = new int[6];
| for (int count=0;count<=100;count++ ) {
| boolean allUnique = false;
| while ( ! allUnique)
| {
| int [] sixNumbers = new int[6];
| for (int i = 0;i<=5;i++)
| {
| Random generator = new Random();
| int t= generator.nextInt(49) + 1;
| sixNumbers[i] = t;
| }
| allUnique = testUnique(sixNumbers);
| if (allUnique == true)
| sixUniqueNumbers = sixNumbers;
| }
| for (int i=0;i<=5;i++)
| System.out.print(sixUniqueNumbers[i] + " ");
| System.out.println("");
|
| }
| }
| public static boolean testUnique(int [] numberList)
| {
| boolean gotCha = true;
| for (int i=0;i<=4;i++)
| {
| for (int j=i+1;j<=5;j++) {
| if (numberList[i] == numberList[j]) {
| gotCha = false;
| break;
| }
| }
| }
| return gotCha;
| }
| }
| </SSCCE>
|
| If I were to switch it to use the Integer type objects and an Array
| List, would it be easier to determine the uniqueness of the ArrayList.
|
| If I had to pick 100 numbers between 1 and 3000 100 times, it might
| get a little CPU intensive, so I'd like to have something better.
| Eventually what I want to do is pick 6 numbers between 1 and 49 one
| million times and then count the frequency of each number.
|

```
 0

6 Replies
287 Views

Similar Articles

12/12/2013 10:14:39 AM
page loaded in 155401 ms. (0)

Similar Artilces:

Parsing Binary Structures; Is there a better way / What is your way?
Hi List, On several occasions I have needed (and build) a parser that reads a binary piece of data with custom structure. For example (bogus one): BE +---------+---------+-------------+-------------+------+--------+ | Version | Command | Instruction | Data Length | Data | Filler | +---------+---------+-------------+-------------+------+--------+ Version: 6 bits Command: 4 bits Instruction: 5 bits Data Length: 5 bits Data: 0-31 bits Filler: filling 0 bits to make the packet dividable by 8 what I usually do is read the packet in binary mode, convert the output to a concatenated 'binary ...

Is there a better way to do this?
Ok I have a bit of a messy problem, and I can code this solution but I'm hoping someone here can help me find a bit more elegant way to do this. basically I have a table in in the DB (postgresql) that looks something like this: Table - logdata codes time =========================================== TXD 01:00 code three 01:00 RTX 01:10 code four 01:10 PXD 02:00 code six 02:00 TXD 01:45 code five code one 01:45 TXD 03:00 code five code six 03:00 TXD 04:00 code nine 04:00 .... .... As you can see from the times the idea is that there is a three letter code type and a code...

Is there a better way to do this?
Hi, I wrote a python script that uses pysvn to export projects from an svn repo I have. The repo has hundreds of projects in it with a directory structure that is pretty uniform however it's not exactly uniform because of the capitalization. I.e.: \root \project English \Stuff \Stuff 2 \Project Spanish \Stuff 3=20 \Stuff 4 My svn repo is case sensitive so if I try to get \root\project Spanish\Stuff 3 I get an error. Fixing the capitalization is not an option for me. My initial idea was to make a list of all the different ways "project...

Is there a better way to do this?
Hello, I am now trying to count the total lines of code of all source files in a given directory. And I use the following script: find ./ \( -name .svn -prune \) -or \( ! -type d -print \) | tr '\n' ' ' | xargs wc -l I am sure this works well but I want to know is there a better way to achieve this? Thanks in advance! Regards! Bo 2007-10-05, 17:13(+08), Bo Yang: > Hello, > I am now trying to count the total lines of code of all source files > in a given directory. And I use the following script: > > find ./ \( -name .svn -prune \) -or \( ! -ty...

a better way of doing this
Given that, srl and psim's dimension is not same, is there a better way of doing this ? do i=1,nasite do j=1,nrsite k=map(i,j) do n=1,lorbit do m=1,lorbit psin(n,k)=psin(n,k)+srl(n,m,j)*psim(m,i) enddo end do end do end do To be more precious, is dprod *THE* way of doing this? and is DPROD thread safe? or is it better to thread it by hand? rudra <bnrj.rudra@gmail.com> wrote: > Given that, srl and psim's dimension is not same, is there a better > way of doing this ? > do i=1,nasite > do j=1,nrsite > k=map(i...

is there a better way?
Problem: You have a list of unknown length, such as this: list = [X,X,X,O,O,O,O]. You want to extract all and only the X's. You know the X's are all up front and you know that the item after the last X is an O, or that the list ends with an X. There are never O's between X's. I have been using something like this: _____________________ while list[0] != O: storage.append(list[0]) list.pop(0) if len(list) == 0: break _____________________ But this seems ugly to me, and using "while" give me the heebies. Is there a better approach? hope this ...

Is there a better way to do this...
Hello All, I'm trying to find a more elegant solution to the following. Given three x,y data points, (x(1), y(1)), (x(2), y(2)) and (x(3), y(3)) , I would like to replace one of these points with values from a new point, (xo,yo) where the one replaced has the largest difference in x coordinate (i.e. the largest |xo-x(k)| value, where k=1, 2 or 3). My current (brute force) solution is: if abs(xo-x(1))<abs(xo-x(2)) if abs(xo-x(2))<abs(xo-x(3)) %1 & 2 are nearest x(3)=xo; y(3)=yo; else % 1 &...

which way is better ?
u(x, y) is an unknown function, I need to compute u(x, y) at each time step t1 < t2 < t3 < ... < tk; The domain is discretized as x1 < x2 < x3 < ... < xm and y1 < y2 < y3 < ... < yn; I have the following code: for t1 : tk for x1 : xm for y1 : yn group 1; group 2; end end end In group 1, I have to compute 300 parameters, which will be used in group 2. BUT all of the 300 parameters do NOT depend on time t. So, another option is to move group 1 out of the loop for time t. However, this...

Is there a better way?
I am relativly new to MySql so I may be doing this wrong. On a site I am working on I have a table called block that looks like this: primary key (auto inc) owner id (key to account table) blocked id (key to account table) Where owner id and blocked id are keys into an account table. The table has indexes on both the owner id and blocked id fields. This table is used for users to block contact from other users. For example if user id #1 didn't want to be contacted by user id #2 then there would be an entry in the table where owner id = 1, and blocked id = 2. For a user to see all the u...

is there a better way...
.... or more elegant way to code this in lisp? here's what I have: ;; Haskell code ;; ;; roots :: (Float, Float, Float) -> (Float, Float) ;; roots (a, b,c) = ;; if d < 0 then ;; error "sorry" ;; else ;; (x1, x2) where ;; x1 = e + sqrt d / f ;; x2 = e - sqrt d / f ;; d = b * b - 4 * a * c ;; e = -b / f ;; f = 2 * a (defun roots (a b c) (let* ((f #'(lambda () (* 2 a))) (d #'(lambda () (- (* b b) (* 4 a c)))) (e #'(lambda () (/ (- b) (funcall f)))) ...

Is there a better way?
FM6 WINXP I have a calc field that counts down how many days left until zero based on a given time period. For example: if I give the customer 30 days from today to complete a project the calc field starts a 30 and counts backwards everyday, 30,,,29,,,28,,,27...etc, until it gets to zero. Or if I give the customer 5 days it does the same. 5...4...3..., until zero. This is triggered at opening of the database, since I don't leave it open 24/7. What I need is a more elegant way to write this calc? Can anyone help? Below is the calc. Case( Status( CurrentDate) = Offenses line item::Date, Da...

Which way is better?
int n; int *p1; p1 = &n; or int *p, *p1; p = new int; p1 = p; The above two ways to assign pointer p1, which one is better? Jack * junw2000@gmail.com: > int n; > int *p1; > p1 = &n; > > or > > int *p, *p1; > p = new int; > p1 = p; > > The above two ways to assign pointer p1, which one is better? I only see one way demonstrated above, using "=". Additionally, without requirements the phrase "better" is meaningless. Cheers, & hth., - Alf -- A: Because it messes up the order in which people normally read text. Q: Why ...

A Better Way?
Is there a better way (less code, less convoluted, etc.) to access the last character of a string variable than this?: if(str2.at(str2.length()-1) != '/') str2 +="/"; On 3/8/2013 4:21 PM, Mike Copeland wrote: > Is there a better way (less code, less convoluted, etc.) to access > the last character of a string variable than this?: > > if(str2.at(str2.length()-1) != '/') str2 +="/"; > Try 'back' member function: if (str2.back() != '/') str2 += '/'; And, RTFM. V -- I do not...

better way to do this?
I have an array that looks like this: my_array = [["Jane", "Smith"], ["Bob", "Jones", 1960]] I want to copy each element of my_array into a another object (in this case, a Gtk::TreeIter). I'm currently doing something like this: tree_store = Gtk::TreeStore.new(String, String, Integer) my_array.each do |person| count = 0 row = tree_store.append(nil) person.each do |attribute| row[count] = attrib count = count + 1 end end So, for each attribute that's in my_array, I want to copy it into the appropriate row element. ...

Is there a better way to do this? #2
I recently had code which needed to work with the same structure twice, once using the . nomenclature and once with an index into a hash. i.e. in one case I had entries=@log.entry which I would interrogate with: entries.timings.connect.first_byte or alternatively entries.XmlSimple(in_file) which I would interrogate with: entries['timings']['connect']['first_byte']. Rather than write two blocks for code, one for the in-memory, I decided to override the base structure that XmlSimple used, but I found out that it was Hash. So the following was what I came up with: ...

Idiom -- is there a better way?
Hi .. I am doing indirect dispatch, something like: class Foo def bar(fn) eval "self.#{fn}" end end class Bar < Foo def blah puts "blah here" end end f = Bar.new f.bar("blah") It works however I am sure there must be a nicer way of doing the bar(fn) stuff. Any ideas? TIA, -mark. > class Foo > def bar(fn) > eval "self.#{fn}" > end > end > > ...nicer way of doing the bar(fn) stuff. Any ideas? > Replace eval "self.#{fn}" with method(fn).call On Wed, ...

Is there a better way to achieve this ?
Hello, I have the following requierement: 3 ints (a, b, limit). The sum of 'a' and 'b' shouldn't be bigger than limit otherwise 'a' should be adjusted so that the sum of 'a' and 'b' is equal to 'limit'. Basically this can be written in C like this: int a, b, limit; /* some code that setup the 3 variables */ if (a < 0 || b < 0) goto end; if (a + b > b) /* test for overflow (correct with GCC but not portable) */ goto end; if (a + b > limit) a -= a + b - limit; if (a <...

better ways for debugging?
hi all, im in the process of designing and implementing a digital system on a spartan 3 FPGA. apart from the FPGA, im using two static RAM's and a CMOS image sensor for this design. Compared with other digital systems, this design is fairly simple. But im facing lot of trouble when it comes to debugging . Currently im using Chipscope pro for debugging, but the hassle of updating the connections and lack of block RAM for signal storage has forced me to investigate other possibilities for debugging. Since the design involves a CMOS sensor and a RAM, i cant do a full system simulation either...

There must be a better way
Below is part of a script which shows the changes made to permit the script to run on either Python 2.7 or Python 3.2. I was surprised to see that the CSV next method is no longer available. Suggestions welcome. Colin W. def main(): global inData, inFile if ver == '2': headerLine= inData.next() else: # Python version 3.3 inFile.close() inFile= open('Don Wall April 18 2013.csv', 'r', newline= '') inData= csv.reader(inFile) headerLine= inData.__next__() On Sat, Apr 20, 2013 at 4:...

There must be a better way.
Say I have a string, and it may contain newlines, like so: "foo bar baz" I want to take this string and indent each line over by n spaces. If n were 4, I would get this: " foo bar baz" My solution is kind of fugly, and this seems, generically, like the sort of thing FORMAT was designed to do in a reasonably straightforward manner, but I couldn't really figure it out from the CLHS. The solution I came up with ended a bit more general than I'd initially intended, just because the way things broke down into individual functions made the generality so eas...