Swapping two items in a list reliably?

I need a block that can do that. Could someone help?

You mean swap two items with different items in a list? Or do you mean reordering them?

I could help you make a block for that.

Here's how I made it


https://snap.berkeley.edu/snap/snap.html#present:Username=ego-lay_atman-bay&ProjectName=swap%20items

Can you explain why yours is more complex than the Brian's one; is it because of allowing for randomness or something else makes it more complex?

Ok, so here's what the script does

[scratchblocks]
set [list v] to ([id v] of (list) :: operators)
[/scratchblocks]
This is to create a copy of the list so I'm not modifying the original one. If the block was a command block, then I wouldn't do this.

[scratchblocks]
if <(1::variables) =[random]> ::control
set [1 v] to (pick random (1) to ([length v] of (list) :: list)
[/scratchblocks]
This is to make the random option working. Can be removed if you don't want this. If I didn't do this, all the values would be mixed up, and then you might lose an item instead of swapping it. I also did this because all other list blocks with an item number value has options for 1, random, and last.

[scratchblocks]
set [1 v] to (list (1::variables) (item (1::variables) of (list)) @delInput @addInput::list)
[/scratchblocks]
This is essentially just setting a temporary variable to the item value. I just didn't want to bother with script vars.

[scratchblocks]
replace item (item (1 v) of (1::variables)) of (list) with (item (2 v) of (2::variables)
[/scratchblocks]
This is where the actual swapping part is. It just replaces the first item with the sencond item value, and vice versa.

Does this help you understand how mine works?

It was not just setting it to the item value, but setting it to a new list, which has confused me, I guess, where the new list is made of the index value and the item at that index value.

As a non-math person, I had to think through your clever trick to understand it.

I like it now.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.