I am working on the software for a machine that will automatically trim toenails, so that users can simply put their feet in it and run it instead of having to manually do it by biting them or using nail clippers.
A sizeable percentage of our potential user base will likely be Jewish, and, evidently, there is a tradition about not trimming toenails (or fingernails) in sequential order
There seems to be dissenting opinion on the precise application of this tradition, but we think that the following rules are sufficient to accomodate people whose religious practices prohibit cutting toenails in order:
- No two adjacent toenails should be cut consecutively
- The cutting sequence on the left foot should not match the sequence on the right foot
- The cutting sequence on two consecutive runs should not be the same. The sequences shouldn’t be easily predictable, so hardcoding an alternating sequence does not work.
This is how we have decided to number the toes:
5 4 3 2 1 1 2 3 4 5
Left foot Right foot
I have written code to solve the problem, but the algorithm used is sub-optimal: in fact, the worst case performance is O(∞). The way it works is comparable to bogosort. Here is a pseudocode simplification of the actual code used:
function GenerateRandomSequence
sequence = Array[5]
foreach (item in sequence)
item = RandomNumberBetween(1,5)
return sequence
function GetToenailCuttingOrder
while (true)
sequence = GenerateRandomSequence()
if (!AllItemsAreUnique(sequence))
continue
if (NoTwoAdjacentItemsHaveConsecutiveNumbers(sequence))
return sequence
do
leftFootSequence = GetToenailCuttingOrder()
rightFootSequence = GetToenailCuttingOrder()
until (leftFootSequence != rightFootSequence &&
leftFootSequence != leftFootSequenceFromLastRun &&
rightFootSequence != rightFootSequenceFromLastRun)
Basically, it generates random sequences and checks if they meet the criteria. If it doesn’t meet the criteria, it starts over. It doesn’t take a ridiculously long amount of time, but it is very unpredictable.
I realize that the way I am currently doing it is pretty terrible, but I’m having trouble coming up with a better way. Can any of you suggest a more elegant and performant algorithm?
You could generate all possible toenail cutting sequences with no restrictions, and then filter out all sequences that violate the jewish rule. Luckily, humans only have five toes per foot*, so there are only 5! = 120 unrestricted sequences.
Python example:
To enforce your “no repeats of the same sequence” rule, you can just choose four of the above sequences, and use them alternately. The only catch here is that if you count the two big toes as “consecutive”, then you can’t choose two sequences that end and begin with 1, respectively.
*You may want to make a numberOfToesPerFoot variable, so you can easily change it later if any of your clients turn out to have less toes than you expect, or more.