Notifications
Clear all

[Closed] Sorting Multidimensional Arrays

Hello everyone!

I need some help with Maxscript, the situation is the following:

I have a multidimensional array which has strings, integers, booleans and so on in different sub-arrays.

For example:
multidim = #(#(“John”,“Paul”,“Sam”,“Andy”),#(1,2,3,4),#(true,true,false,false)

I would like to sort the multidimensional array by names keeping the original structure. In this case I would like see the following:

multidim = #(#(“Andy”,“John”,“Paul”,“Sam”),#(4,1,2,3),#(false,true,true,false)

I would really appreciate any help, thank you!

5 Replies

May I ask a mod to move my thread to 3DSmax/Maxscript area? I’m new here, I guess I posted my question in the wrong place, sorry. Thank you!

Hi,

You could create an index array based on the 1st array sort something like:


 MyArray= #(#("John","Paul","Sam","Andy"),#(1,2,3,4),#(true,true,false,false))
 -- Make a copy of the 'Names' array 
 tmpArray=Deepcopy MyArray[1]
 sort tmpArray
 -- Create the sorted Index array
 SortedIndexArray = for i in tmpArray collect (findItem MyArray[1] i)
 -- Copy the original array
 tmpArray=Deepcopy MyArray
 -- re-order the elements of the copy accordin g to the original 
 for j=1 to MyArray.count do
 (
  for i =1 to SortedIndexArray.count do
  tmpArray[j][i]=MyArray[j][SortedIndexArray[i]]
 )
 -- copy the sorted array back to original
 MyArray=tmpArray

This can be done with QSORT() too:


  
(	
	fn compareFN v1 v2 valArray: =
	(
	if valArray[v1] > valArray[v2] then 1 else -1
	)

	multidim = #(#("John","Paul","Sam","Andy"),#(1,2,3,4),#(true,true,false,false))

	indexArray = for i = 1 to multidim[1].count collect i
	qsort indexArray compareFN valArray:multidim[1]

	newArray = for j in multidim collect 
		for i in indexArray collect j[i]

	newArray 
)
  
  --> #(#("Andy", "John", "Paul", "Sam"), #(4, 1, 2, 3), #(false, true, true, false))
  

      ...
      	newArray = for j in multidim collect 
      		for i in indexArray collect j[i]
      ...
        

Snappy!

@Vicky, I suppose it must go without saying, though, that if at all possible, it would be better to structure your data as records in the first place? i.e.

struct person (name,number,isSomethingBoolean)

which would leave much less room for error / spaghetti , if the code depending on it is of more than trivial length. But you probably have good reasons for doing it this way.

Thank you guys!! You helped me greatly!