Notifications
Clear all

[Closed] Randomize selection array

Hi guys,
I an amateur in maxscript, trying to write a script to make traffic cars using path constraint.
the script does 2 things. make all selected cars orientation “follow” the path, and randomize the car’s position by “percentage”. This is what I have :

arr = selection as array
lastpos = 0
for i in (arr) do 
(
	i.pos.controller.Path_Constraint.controller.follow = on
	i.pos.controller.Path_Constraint.controller.percent = lastpos  + (random 0.5 3)
	lastpos = i.pos.controller.Path_Constraint.controller.percent
)

But there is a problem. the cars are in 7 colors but there is hundreds copy of them. my script makes a lot of the same color cars in a row. I think it is because of the selection array order. So I am looking for a way to randomize the selection array before doing the job.

Please help. Thanks.

3 Replies
fn shuffleIndexes count seedvalue: = 
(
	if seedvalue != unsupplied do seed seedvalue
	list = #() 	
	list.count = count
	for k = 1 to count do 
	(
		i = random 1 k
		list[k] = list[i]
		list[i] = k
	)
	list
)

arr = selection as array
shuffled_arr = for k in (shuffleIndexes arr.count seedvalue:1) collect arr[k]

As far as I remember, the first person to show this MXS shuffle implementation was the biddle … so that’s his credit.

slight variation

(
	fn random_shuffle arr seeding: = 
	(
		if seeding != unsupplied do seed seeding;
		for i = 1 to arr.count - 1 do 
		(
			j = random (i+1) arr.count;
			swap arr[i] arr[j];
		)	
	)
	
	
	arr = selection as array
	random_shuffle arr
	arr			
)

or

    fn random_shuffle arr seeding: = 
	(
		if seeding != unsupplied do seed seeding;
		for i = 1 to arr.count do 
		(
			j = random 1 arr.count;
			swap arr[i] arr[j];
		)	
	)

It works perfectly. Thank a lot KLVNK and denisT.