PDA

View Full Version : Sorting Multidimensional Arrays


VickyG24
02-06-2009, 08:30 PM
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!

VickyG24
02-07-2009, 08:09 PM
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!

Zbuffer
02-08-2009, 01:49 PM
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

Bobo
02-08-2009, 03:57 PM
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))

drdubosc
02-08-2009, 06:28 PM
...
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.

VickyG24
02-09-2009, 01:38 AM
Thank you guys!! You helped me greatly!

CGTalk Moderation
02-09-2009, 01:38 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.