We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › mixing an array
Page Index Toggle Pages: 1
mixing an array (Read 881 times)
mixing an array
May 7th, 2009, 4:19am
 
hi, I try to mix the elements of a simple array, Is there a special function(can be for a String also).
Example:
int[] a=new int{1,2,3,4,5,6,7,8,9};
a...
print(result);
result: 3  5 1 2 7 4 9 6 8
Re: mixing an array
Reply #1 - May 7th, 2009, 7:32am
 
See Fisher–Yates shuffle, there is a sample Java implementation...
Re: mixing an array
Reply #2 - May 8th, 2009, 2:15pm
 
Thank you, nice algorithm, I'll use it in my program. I think, it means that there is no any standard function to do this shuffle. )
Re: mixing an array
Reply #3 - May 9th, 2009, 1:51am
 
I haven't seen one in Processing (might be handy though) nor in Java, the latter would need to provide a shuffle class to avoid depending on a given random generation implementation.
Re: mixing an array
Reply #4 - May 9th, 2009, 4:39am
 
java's Collections has a shuffle method. but by the time you've added the code to initialise the List (not an array) and the code to unbox from Integers to ints you may as well have written the half a dozen lines of the shuffle yourself.

Code:

ArrayList l = new ArrayList();

void setup() {
// add elements
for (int i = 1 ; i <= 9 ; i++) {
l.add(i);
}
// shuffle
Collections.shuffle(l);
// convert to array (assuming you need an array)
Integer[] a = new Integer[10];
a = (Integer[])l.toArray(a);
// print
for (int i = 0 ; i < 9 ; i++) {
println("[" + i + "]: " + a[i]); // these are Integers not ints
}
}


there is also an Arrays.toList() (to do the initial conversion from array to a list) but that seems to require java's generics (List<Integer>...) and i can't get it to work in processing (in the 5 minutes i tried it for)
Page Index Toggle Pages: 1