Home Technical Talk

Maxscript/Code question: Find all potential swaps within an array

polycounter lvl 15
Offline / Send Message
leslievdb polycounter lvl 15
I have 4 points and their respective positions, i want to be able to calculate each potential combination of swaps i can make with those points.

so the first part would be something like this
vertexamount = 4
 
swaparr = #()
for i=1 to vertexamount do
(
        for i2=1 to vertexamount do
        (
                if finditem swaparr [i,i2] == 0 and finditem swaparr [i2,i]  == 0 and i != i2 then
                (                      
                        append swaparr [i,i2]
                )
        )
       
)
the output of this is an array containing all of the potential swaps between those points
[1,2]
[1,3]
[1,4]
[2,3]
[2,4]
[3,4]

but now for each one of those swaps i want to be able to swap the other points so you'd get something like this

[1,2]
[1,3]
[1,4]
[2,3]
[2,4]
[3,4]

[1,2][1,3]
[1,2][1,4]
[1,2][2,3]
[1,2][2,4]
[1,2][3,4]

[1,3][1,2]
[1,3][1,4]
[1,3][2,3]
[1,3][2,4]
[1,3][3,4]
etc...
and then go even further where you'd end up getting things like this
[1,2][1,3][1,4][2,3]

i can't seem to figure out how to get this in a nice function where i'd eventually could get every possible combination for more points as well

EDIT: nvm i didn't realize this could keep on going so i don't have much use for it

Replies

  • Swordslayer
    Options
    Offline / Send Message
    Swordslayer interpolator
    Why not use permutations here? You would get all the unique point configurations (of course with growing number of points it won't be as useful as the number of arrangements here is N factorial):
    fn permutations elems =
    (
        if elems.count == 1 then #(elems)
        else
        (
            local result = #()
            for elem in elems do
            (
                local rest = for e in elems where e != elem collect e
                local restPerm = permutations rest
                join result (for perm in restPerm collect join #(elem) perm)
            )
            result
        )
    )
    
    permutations #(1, 2, 3, 4)
    
Sign In or Register to comment.