Shuffle an array of integers.

P

pieter_hordijk

Hi all,

this is my first post ever in a ng so bare with me.

As a school assignment I need to create the game Lingo.
Untill now it all goes well.

But now i found i (simple) problem.

I have an array of 25 integers and I want to shuffle the integers in
the array.

Offcourse i've searched NG's before I came here to ask, but all with
little result.

I know most of you people won't help (in a way of giving the code) to
students, so that they won't learn anything from it.

But i've come so far (I think :p) now, that im asking you please tell
what is wrong with following code:

// for Collections
import java.util.*;

public class Ballen extends JFrame {

// the array
private static int[] Ballenbak =
{

// even getallen
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36,
38, 40,
42, 44, 46, 48, 50

};

// shuffle integers
Collections.shuffle(Ballenbak);
}

The error I get is the following:
cannot find symbol; symbol : method shuffle(int[]), location: class
java.util.Collections

Can someone please tell me what I'm doing wrong?

Thanks in advance.
 
P

pieter_hordijk

I've also tried the following:

Collections.shuffle(Arrays.asList(Ballenbak));

This won't work either, I get following error:
asList(java.lang.Object[]) in java.util.Arrays cannot be applied to
(int[])
 
S

Steve W. Jackson

Hi all,

this is my first post ever in a ng so bare with me.

As a school assignment I need to create the game Lingo.
Untill now it all goes well.

But now i found i (simple) problem.

I have an array of 25 integers and I want to shuffle the integers in
the array.

Offcourse i've searched NG's before I came here to ask, but all with
little result.

I know most of you people won't help (in a way of giving the code) to
students, so that they won't learn anything from it.

But i've come so far (I think :p) now, that im asking you please tell
what is wrong with following code:

// for Collections
import java.util.*;

public class Ballen extends JFrame {

// the array
private static int[] Ballenbak =
{

// even getallen
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36,
38, 40,
42, 44, 46, 48, 50

};

// shuffle integers
Collections.shuffle(Ballenbak);
}

The error I get is the following:
cannot find symbol; symbol : method shuffle(int[]), location: class
java.util.Collections

Can someone please tell me what I'm doing wrong?

Thanks in advance.

As the error message says, Collections has no method named "shuffle"
that takes an array of int as its parameter. In your subsequent
message, you say you tried using Arrays.asList() to convert your array
to a List, so you're clearly aware of the shuffle method requiring a
List as its parameter. But the asList method takes an array of Object,
and int is a primitive type rather than an Object, so an int array will
not work there either.

So perhaps you don't want to use an array of a primitive type...

= Steve =
 
P

Patricia Shanahan

I have an array of 25 integers and I want to shuffle the integers in
the array. ....
The error I get is the following:
cannot find symbol; symbol : method shuffle(int[]), location: class
java.util.Collections
....

The shuffle method in Collections only applies to a List,
not an array. You can find out about things like this by
using the API javadocs, which are on Sun's web site, but I
recommend downloading a copy for quick access.

You have some options:

1. Switch to using a List of Integer references, at least
for the shuffle. This is probably the simplest.

2. Search in Google etc. for an existing Java implementation
of int[] shuffling. I don't know whether this is permitted
or not for your execise. You may be required to write all
the code yourself.

3. Write an int[] shuffle. This will be easier to get right
if you have access to an algorithms reference. If so, look
for "Fisher-Yates shuffle". The shuffle in
java.util.Collections is an example of this method.

If you do this, be careful, there are a lot of ways to get
it wrong.

Patricia
 
P

pieter_hordijk

Thanks both for your reply.

Using your comments and my own common sense it does work now.

However I don't know if it's a clean or a ugly way to do it, but it
works :)

Changes:
I changed the type of Ballenbak array from int to String.
I added a list list_ballen and filled it with the elements of Ballenbak
array.
Now Collections.shuffle() works with the list_ballen list.

// for Collections
import java.util.*;


public class Ballen extends JFrame {

// declare list
List list_ballen = new ArrayList(25);

// the array
String[] Ballenbak =
{

// even getallen
"2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24",
"26", "28", "30", "32", "34", "36",
"38", "40",
"42", "44", "46", "48", "50"
};

//fill list with array elements
for (int j = 0; j < Ballenbak.length; j++) {
list_ballen.add(Ballenbak[j]);
}


// shuffle integers
Collections.shuffle(list_ballen)­;

}

If someone knows a better way of doing this, please let me know. I
always want to learn more.

Thanks for helping this student out. And making my first posting in a
NG a success. :)
 
S

Steve W. Jackson

Thanks both for your reply.

Using your comments and my own common sense it does work now.

However I don't know if it's a clean or a ugly way to do it, but it
works :)

Changes:
I changed the type of Ballenbak array from int to String.
I added a list list ballen and filled it with the elements of Ballenbak
array.
Now Collections.shuffle() works with the list ballen list.

// for Collections
import java.util.*;


public class Ballen extends JFrame {

// declare list
List list ballen = new ArrayList(25);

// the array
String[] Ballenbak =
{

// even getallen
"2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24",
"26", "28", "30", "32", "34", "36",
"38", "40",
"42", "44", "46", "48", "50"
};

//fill list with array elements
for (int j = 0; j < Ballenbak.length; j++) {
list ballen.add(Ballenbak[j]);
}


// shuffle integers
Collections.shuffle(list ballen)­;

}

If someone knows a better way of doing this, please let me know. I
always want to learn more.

Thanks for helping this student out. And making my first posting in a
NG a success. :)

A couple of quick thoughts to aid your future progression... :)

As a matter of convention, Java code should be written such that class
names begin with an uppercase letter, while variable names should begin
with lowercase letters. So, while it's not wrong to code this way, it's
not in keeping with the convention which virtually all Java coders use.

Secondly, I'm reasonably sure that the shuffle probably relies on the
natural order of the items in the list. You'll learn this the hard way
sooner or later, and it would no doubt matter much more if you were
doing a sort than a shuffle, but the natural ordering of strings is such
that "12" is before "2". Remember, these are not numbers, so the
comparison begins at left and the first character "1" is earlier in the
ordering than the "2", so that string precedes the other. Just FYI.

Lotsa luck.

= Steve =
 
E

Eric Sosman

Steve said:
[...]

Secondly, I'm reasonably sure that the shuffle probably relies on the
natural order of the items in the list. [...]

How could that be so? Two counter-arguments:

1) The Javadoc for shuffle() claim it produces each
possible permutation with approximately equal likelihood
("approximately" being a nod to possible imperfections in
the source of random numbers). If it relied on the items'
natural order that would mean that the order influenced
the choice of permutations -- and if that were the case,
shuffle() could not even begin to make its claim.

2) The Javadoc does not specify that the List must
contain objects that implement Comparable, much less that
they be mutually comparable.

... and, of course, you could try it yourself. Build
a List that contains an Integer, a String, a JFrame, a
HashMap, a `null' reference, BigInteger.ZERO, and System.err,
and try to shuffle() it. If shuffle() relied on a natural
ordering between these disparate elements, you'd find out
about it in short order ;-)
 
B

Big Jim

you might want to check out the java.lang.Integer class

Thanks both for your reply.

Using your comments and my own common sense it does work now.

However I don't know if it's a clean or a ugly way to do it, but it
works :)

Changes:
I changed the type of Ballenbak array from int to String.
I added a list list_ballen and filled it with the elements of Ballenbak
array.
Now Collections.shuffle() works with the list_ballen list.

// for Collections
import java.util.*;


public class Ballen extends JFrame {

// declare list
List list_ballen = new ArrayList(25);

// the array
String[] Ballenbak =
{

// even getallen
"2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24",
"26", "28", "30", "32", "34", "36",
"38", "40",
"42", "44", "46", "48", "50"
};

//fill list with array elements
for (int j = 0; j < Ballenbak.length; j++) {
list_ballen.add(Ballenbak[j]);
}


// shuffle integers
Collections.shuffle(list_ballen)­;

}

If someone knows a better way of doing this, please let me know. I
always want to learn more.

Thanks for helping this student out. And making my first posting in a
NG a success. :)
 
K

klynn47

You might try something like this.

int position1 = (int)(Ballenbak.length*Math.random());
int position2 = position1;

while (position2 == position1)
position2 = (int)(Ballenbak.length*Math.random());

int temp = Ballenbak[position1];
Ballenbak[position1] = Ballenback[position2];
Ballenbak[position2] = temp;

Then put this in a loop that runs about 100 times.
 
A

Abhijat Vatsyayan

Secondly, I'm reasonably sure that the shuffle probably relies on the
natural order of the items in the list. You'll learn this the hard way
sooner or later, and it would no doubt matter much more if you were
doing a sort than a shuffle, but the natural ordering of strings is such
that "12" is before "2". Remember, these are not numbers, so the
comparison begins at left and the first character "1" is earlier in the
ordering than the "2", so that string precedes the other. Just FYI.

1.4 uses instance of Random to generate indices and swaps element
positions based on these random indices. I could be wrong but I don't see
why it will use "Natural Ordering" of the elements. It does use the natural
ordering of the element positions to shuffle.
 
G

googmeister

You might try something like this.
int position1 = (int)(Ballenbak.length*Math.ra ndom());
int position2 = position1;

while (position2 == position1)
position2 = (int)(Ballenbak.length*Math.ra ndom());

int temp = Ballenbak[position1];
Ballenbak[position1] = Ballenback[position2];
Ballenbak[position2] = temp;

Then put this in a loop that runs about 100 times.

This is a complete hack and a terrible idea. What
makes you think the result will be uniformly
shuffled?
 
S

Steve W. Jackson

Eric Sosman said:
Steve said:
[...]

Secondly, I'm reasonably sure that the shuffle probably relies on the
natural order of the items in the list. [...]

How could that be so? Two counter-arguments:

1) The Javadoc for shuffle() claim it produces each
possible permutation with approximately equal likelihood
("approximately" being a nod to possible imperfections in
the source of random numbers). If it relied on the items'
natural order that would mean that the order influenced
the choice of permutations -- and if that were the case,
shuffle() could not even begin to make its claim.

2) The Javadoc does not specify that the List must
contain objects that implement Comparable, much less that
they be mutually comparable.

... and, of course, you could try it yourself. Build
a List that contains an Integer, a String, a JFrame, a
HashMap, a `null' reference, BigInteger.ZERO, and System.err,
and try to shuffle() it. If shuffle() relied on a natural
ordering between these disparate elements, you'd find out
about it in short order ;-)

My mistake. I was thinking of a way to introduce the idea of string
ordering being different from number ordering and fell into a really bad
(and incorrect) example.

= Steve =
 
L

Lee Ryman

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


Something I came up with for a somewhat similar situation (It was
actually used to generate test data for various sorting algorithms for a
uni course). Be aware that its probably O(n), but it works, and for what
I was doing, the actual data-generation was not time-critical. You
should be able to adapt this to produce your desired array. There is a
lot of unnecessary guff in there for the sake of a certain stupid tutor
that could never understand/accept how things worked. (indents are 2
spaces to hopefully prevent wrapping)...


/**
<p>Generates an array of integer values ranging from 1 to
the requested size of the array inclusive. The order of values
is random and every value is unique.</p>

<p>Note that due to the use of assertions this class must be compiled
and run under a JVM version 1.4 or above.</p>
*/
class RandomGenerator implements TestDataGenerator {

public int[] generate (int size) {
int[] testArray = new int[size];

/*
In order to generate an array of unique, randomly-ordered integers
we fill a source array with numbers from 1 to the desired size of
the test array, then pick indexes at random, placing their value
into the test array. To ensure uniqueness picked numbers are
'cancelled out' by overwriting them with numbers which have not
yet been picked, and reducing the effective range of indexes which
values can be picked from.
*/
int[] sourceArray = new int[size];
for (int i = 0; i < size; i++) {
sourceArray = (i + 1);
}

Random random = new Random();

int generated = 0;
for (int i = 0; i < size; i++) {
int randomPosition = random.nextInt(size - generated) + generated;
testArray = sourceArray[randomPosition];
sourceArray[randomPosition] = sourceArray[generated];
generated++;
}

assert (checkArray(testArray)); // test all values exist in array

return (testArray);
}

private static boolean checkArray (int[] data) {
long sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data;
}
long expected = (data.length*(data.length+1)/2);
return (expected == sum);
}

public String getDescription () {
return ("Random-ordered");
}
}



Regards,

Lee
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (MingW32)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iEYEARECAAYFAkJt0igACgkQhbcFpQga0LAk2QCbBBFQxVDBxke2w0LHbURBIwPv
7kwAnjORrLqCVa2FHsmEZkUtwOwNTGcQ
=SE1M
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top