Saturday, 18 January 2014

Zaps new stairwalker algorithm in beta

I've changed the stairwalker algorithm to improve how it handles things when there aren't very many items returned by the Zazzle search.

The item that is to be emitted is given by the day it is in the month multiplied by 2 and then minus 1 if it is in the morning. This gives a range of 1 (morning of the 1st of the month) to 62 (the afternoon of the 31st on a 31 day month).

What if there aren't enough items to select from?

Well, if there aren't enough items available then we have to cycle through the ones that are, as the mornings and afternoons roll by.

To cycle through the available items, we need to start again at the beginning when we run out. Well, there's a calculator button for that on some calculators called MOD. What it does is gives you the remainder after dividing one number by another. The trouble is, it gives you answers that cycle like this: 1, 2, 3, 0, 1, 2, 3, 0, 1... (try it starting at 1 and going up to 9 when dividing by 4 and you'll see).
Let us call the answer to that original sum above, OriginalChoice and the number of items available we'll call Count. So our starting point is:
  • OriginalChoice MOD Count
Say Count is 4. Remember, on the first of the month in the morning, OriginalChoice will be 1 and in the afternoon it will be 2 and so on...
1 MOD 4 gives a remainder of 1
2 MOD 4 gives a remainder of 2
3 MOD 4 gives a reminder of 3
4 MOD 4 gives a reminder of 0
5 MOD 4 gives a remainder of 1
6 MOD 4 gives a reminder of 2
7 MOD 4 gives a reminder of 3
etc.

The trouble is we're cycling 1,2,3,0... and we actually want 1,2,3,4,1,2,3,4 etc

We can deal with that by subtracting 1 before doing the MOD and then adding it back after:
(1-1) MOD 4 gives a remainder of 0, add the 1 back again, giving 1
(2-1) MOD 4 gives a remainder of 1, add the 1 back again, giving 2
(3-1) MOD 4 gives a remainder of 2, add the 1 back again, giving 3
(4-1) MOD 4 gives a remainder of 3, add the 1 back again, giving 4
(5-1) MOD 4 gives a remainder of 0, add the 1 back again, giving 1
(6-1) MOD 4 gives a remainder of 1, add the 1 back again, giving 2
(7-1) MOD 4 gives a remainder of 2, add the 1 back again, giving 3
etc

So in summary,
  • ((OriginalChoice-1) MOD Count)+1
is the new stairwalker algorithm.

When there are more items available than needed we never cycle, we just step through them in sequence as the mornings and afternoons roll by.

Note that on the last day of a 31 day month we need 62 items to prevent cycling, if there were only 61 items then the algorithm would cycle round and pick the first.


comments, likes, +1s, tweets are always welcome! :)

No comments:

Post a Comment

Comment moderation is switched on. Please wait till I've had a chance to review your comment and publish it. Thanks!