Shoutbox

Coding: swapping items in a row - Printable Version

-Shoutbox (https://shoutbox.menthix.net)
+-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58)
+--- Forum: Skype & Technology (/forumdisplay.php?fid=9)
+---- Forum: Tech Talk (/forumdisplay.php?fid=17)
+----- Thread: Coding: swapping items in a row (/showthread.php?tid=28511)

Coding: swapping items in a row by KeyStorm on 07-11-2004 at 06:25 PM

A challenging logic test for all you coders out there:

I need for the next version of KSMAS a system to be able to swap images.
For every image there is a list of other available slots either filled or not with which to swap current image (/item).

Now I need a system (probably recursive) to swap all files as the user wants and troubleshoot any weird combination (more than one pointing to a slot, etc.).

So we have an array of images:
12345

and if we want to swap item 2 with item 5, the returned swap-array would be:
15345

and that would set up the images-array as follows:

15342

got my point? Good!

It's possible that it's rather simple, but I'm stuck atm.

So, please, help me if you have any clue.

Thanks. :)


RE: Coding: swapping items in a row by fluffy_lobster on 07-11-2004 at 06:30 PM

code:
function swap($arr,$key1,$key2)
{
$foo = $arr[$key1];
$arr[$key1] = $arr[$key2];
$arr[$key2] = $foo;

return $arr;
}

That's how I'd do it... I'd say that's fairly simple too.
RE: Coding: swapping items in a row by KeyStorm on 07-11-2004 at 08:48 PM

Yeah, well.
That's obviously the simple way to swap 2 items, but problems appear when for example:

1- We have a "bouncing-swap" where the target item should be swapped with a third one and so on. E.g. swap 2 with 5 and 5 with 3.

2- We have several swaps targeting the same slot: swapping 2 with 5, 4 with 5 and 1 with 5, what would mean: swap 2 with 5,  5 with 4 and 4 with 1 (back to problem nr. 1).

Tbh, Lobster, I could've done that, I'm not that n00b, you know ;)