LaserBeak
LaserBeak

Reputation: 3285

Algorithm for sorting questions that have been re-arranged, knowing new position and old position

Say I have a bunch of question fields and users can rearrange them and send to the server the new position and old position of the question(s) that have had their position altered and the server will then use this data to update all the effected questions position/number value in the database. As stated I am only sending back the new position and old position of the question(s) that have been moved and not of those effected before or after it etc. So that calculation will have to be done at the server.

So lets say I have questions numbered.

1 2 3 4 5 6 7 8

If I rearrange them as such

8 1 2 3 4 5 6 7

Then all values between the new position for (question 8), which is now 1 and old position (8) will need to be updated, with 1 - 7 getting a +1 and 8 being changed to 1. This is of course a simplified scenario, the questions can be rearranged to a much greater complexity where effected ranges will overlap and other ranges terminate within other ranges etc. So the required increments and decrements will be combined. Sounds like a fairly common scenario so if someone can put up an example, preferably in c# would be great.

Upvotes: 0

Views: 144

Answers (3)

Jose Paul
Jose Paul

Reputation: 11

Something along the lines of the answers above: Can you just add a 'position' property to the question object (independent of it's position in the list)? The user changes this property when they rearrange. Then you can just do a ListOfQuestions.OrderBy(q => q.Position)?

This just

Upvotes: 1

rro
rro

Reputation: 619

An alternative would be to: 1. Create your fixed size list/collection (Collection A) 2. Put the questions with modified positions on the new positions/index 3. Iterate through original question collection and placing the unmoved questions in the empty positions of the new collection (Collection A). Update question indexes based on their positions in the new collection.

Crude I know.

Upvotes: 0

Sam
Sam

Reputation: 11

This looks to me like you're trying to simply do random insertions and removals of a collection.

If that is the case, a Linked List is a good option for that. A linked list essentially has a head node(first node) and each node has a next attribute, which references another list.

that way, if you want to remove a node you can just make that node's parent node point to that node's child, and if you want to insert a node you can do the reverse.

c# has a built-in linked list class that you might want to check out

Upvotes: 0

Related Questions