I was looking for an algorithm for sorting an array in a custom way but I didn’t succeed in finding the proper solution to my problem. I’ll describe the code in Django-like syntax but it’s not necessary to limit a solution only for Django.
Let’s suppose I have the following models (classes):
class Website(models.Model):
...
class Offer(models.Model):
website = models.ForeignKey(Website, on_delete=models.CASCADE)
...
And let’s suppose I have the following instances:
- Offer 1 -> Website A
- Offer 2 -> Website B
- Offer 3 -> Website B
- Offer 4 -> Website B
- Offer 5 -> Website C
- Offer 6 -> Website A
- Offer 7 -> Website A
- Offer 8 -> Website C
This instances form a sequence (array):
sequence = [Offer 1, Offer 2, Offer 3, Offer 4, Offer 5, Offer 6, Offer 7, Offer 8]
I need to sort the sequence in the way where Offers with the same Website cannot stand one after another nevertheless the original order should stay as same as possible.
So the sorted sequence should look this way:
sequence = [Offer 1, Offer 2, Offer 5, Offer 3, Offer 6, Offer 4, Offer 7, Offer 8]
Positive Examples:
- Website A, Website B, Website A, Website C, Website A
- Website A, Website B, Website C, Website B, Website C
- Website A, Website B, Website A, Website B, Website A
Negative Examples:
- Website A, Website B, Website B, Website A, Website B, …
- Website B, Website C, Website A, Website A, Website B, …
- Website B, Website C, Website A, Website C, Website C, …
Thanks for any suggestion.
This should work:
This is a generator that will try and yield elements in order, but if the next element equals the last element yielded, it will skip it. If it gets to the end of the list and there is no way to yield something that doesn’t equal the previous, it just yields it anyway.
Here’s an example of it working on a list of numbers:
This prints: