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 & HelpSyntax Questions › how to randomize an array of strings
Page Index Toggle Pages: 1
how to randomize an array of strings (Read 1075 times)
how to randomize an array of strings
Nov 9th, 2006, 5:53pm
 
Is there an easy way to randomize an array of strings?

I tried myStringArray.randomizeArray();

Re: how to randomize an array of strings
Reply #1 - Nov 9th, 2006, 6:39pm
 
It's not too hard to randomise the array, but you have to do it manually.

This is one way, it's not very efficient, but easy to see how it works (and will be fine with reasonable sized arrays)

It may also have bugs as I don't have time to check it at the moment, but it at least shows a machanism for doing what you need.

Code:
String[] myText;
// fill myText however you need...

String[] randText=new String[0];
int num=myText.length;
for(int i=0;i<num;i++)
{
int id=(int)random(0,myText.length);
//pick an element of myText at random;

randText=append(randText,myText[i]);
//add it onto the end of randText;

//now we need to remove that element from myText
if(id==0) //special case #1
myText=subset(myText,1,myText.length);
else if(id==myText.length-1) //special case #2
myText=contract(myText,myText.length-1);
else // general case
{
String[] start=subset(myText,0,id);
String[] end=subset(myText,id+1,myText.length);
myText=concat(start,end);
}
}
Re: how to randomize an array of strings
Reply #2 - Nov 9th, 2006, 6:56pm
 
The easiest method is to use an ArrayList. It's like an normal array but it's an object version (I know arrays are objects but we generally consider them apart from objects and primitives).
Code:

ArrayList blah;

void setup(){
// An ArrayList is an object version of an array - more powerful
blah = new ArrayList();
// Our Strings have to wrapped in an object
// A StringBuffer is the standard object wrapper for Strings
// Use it when you manipulate Strings - it's fast and will save you memory
blah.add(new StringBuffer("bob"));
blah.add(new StringBuffer("dave"));
blah.add(new StringBuffer("charly"));
blah.add(new StringBuffer("joe"));

}

void draw(){}

void mousePressed(){
// Now you've used an ArrayList you can use Collections for a little magic...
Collections.shuffle(blah);
for(int i = 0; i < blah.size(); i++){
StringBuffer temp = (StringBuffer)blah.get(i);
println(temp.toString());
}
println();
}


Java documentation on ArrayList

Java documentation on Collections

Edit:

Oops - simultaneous post! Not trying to upstage you John, just took a while to read the reference docs.
Page Index Toggle Pages: 1