OK, I think you don't get the point of my code.
Take my urn() function and add it after that code:
Code:int[] balls;
final int BALL_NB = 10;
int num = BALL_NB;
void setup() {
size(400, 400);
frameRate(10);
}
void draw() {
int x = urn();
print(x + " ");
}
If I understood correctly your need, it should do what you want.
Quote:what I dislike is that it isn't more self-contained as a function
Indeed, but in Java, a function cannot retain persistent data between calls, unlike C/C++ (with static variables).
You guessed right about making a class: that's the way to have persistent data along with methods to work on it.
You don't know that, but so called global variables in Processing are actually fields of a hidden class: you are already using a class!
But let's do one explicitly. That isn't hard, really.
Code:final int BALL_NB = 20;
URN urn = new URN(BALL_NB);
void setup() {
size(400, 400);
frameRate(10);
}
void draw() {
int x = urn.get();
print(x + " ");
if (urn.isExhausted())
{
println(""); // New line
}
}
class URN
{
private int[] balls;
private int ballNb = 10; // Default value
private int num; // Set at 0 by default
static final int LARGE_PRIME = 444443;
// The constructor: same name as class, no return type
public URN(int bn)
{
ballNb = bn;
generateArray();
}
public int get()
{
if (num == ballNb)
{
num = 0;
generateArray();
}
return balls[num++];
}
public boolean isExhausted()
{
return num == ballNb;
}
public int getNum()
{
return num;
}
// Private: only the class can use it
private void generateArray()
{
balls = new int[ballNb]; // initialize or clear the array
int index = int(random(0, ballNb));
for (int i = 0; i < ballNb; i++)
{
index = (index + LARGE_PRIME) % ballNb;
balls[index] = i;
}
}
}
Your shuffle algorithm wasn't working (unfinished?), so I replaced it with a well known one.
Not perfect: with a same starting point, you get the same sequence. Can be spiced up by taking also a random large prime number...