views:

494

answers:

2

I've got an html table thus:

up | dn
[ ]  Item 1
[x]  Item 2
[ ]  Item 3
[ ]  Item 4
[x]  Item 5
[ ]  Item 6
[ ]  Item 7

If 2 & 5 are checked and I click up, the result is:

up | dn
[x]  Item 2
[x]  Item 5
[ ]  Item 1
[ ]  Item 3
[ ]  Item 4
[ ]  Item 6
[ ]  Item 7

If I click dn, the result is:

up | dn
[ ]  Item 1
[ ]  Item 3
[ ]  Item 4
[ ]  Item 6
[x]  Item 2
[x]  Item 5
[ ]  Item 7

In other words, the items are grouped in the chosen direction, and then moved one row in that direction. Anyone have a good algorithm for this? I'm sure I can write something without much difficulty, but it seems like the kind of thing that should be "out there"....

A: 

This looks like a multi-keyed sorting task. You could use something like jQuery UI's Sortable interface. Your sort condition would be something like: a.selected <=> b.selected && a.index <=> b.index.

Disregard: You want to use the Fisher Yates Shuffle algorithm.

spoulson
perhaps I'm not reading that carefully enough, but it seems to be about reordering in a random way, which is not what I'm asking about.
sprugman
I see. I updated my answer.
spoulson
+2  A: 

I think I'm leaning toward a cut-and-paste approach, since the js frameworks make moving pieces of DOM around relatively easy.

  • get checked items' rows
  • get index of {top}-most checked item
  • remove rows & insert them into table at {index-1}
  • (of course top might be bottom, and index-1 is more complex depending on direction and whether or not we're at the extreme end already)
sprugman
This is the exact algorithm I was about to suggest. Way to go.
Seb