Exceptions in random()

Hello. Recently, I’ve been working on a sketch in which I need to line up circles in a random order. Basically, I have an array with all the x-coordinates of the circles, and I have a for loop in setup to display enough circles. The problem is that if I say this:

function setup() {
	var xArray = [100, 225, 350, 475, 500]
	for (i = 0; i < xArray.length; i++) {
		fill(50*i)
		circle(xArray[floor(random(0, xArray.length))], 200, 50)
	}
}

…then the random() function can and does repeat itself — instead of getting my circles in a line with a random shade of gray, they’re frequently on top of each other. I don’t know of a “random() except” function, and I’m guessing it doesn’t exist in such a simple form. I’d very much appreciate it if anyone more skilled than me could show me a workaround or some other solution.

Thanks! :slight_smile:

1 Like

When I encounter a problem like this, I try to think about how I would do this without a computer. If I was given a list of 10 numbers, how would I create another list from those 10 numbers in a random order?

If I think about that, I might shuffle the numbers I’m given. Or I might remove the numbers as I select them. Or I might check if I’ve already used a number before selecting it.

Try to write out what you would do using your own words, not code. When you have that written out, then you can think about implementing it with code.

Good luck!

4 Likes

p5js.org/reference/#/p5/shuffle

1 Like