In general, the easiest way to implement logic is to use the modulo operator,%. Get to know this operator; It is very useful for situations where it helps. There are several ways to write the actual code to distribute letters, whether to use arrays or not, as you wish, etc., but this short expression should give you an idea:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".IndexOf(letter) % partitionCount
This expression gives an index based on the zero value of the section in which to capitalize the letter. The string is just shown for convenience, but may be an array or some other way of representing the alphabet. You can iterate over the alphabet using logic similar to the one above to choose where to place each letter. Before you could put the logic: inside the loop, in the method, etc.
There is nothing magical about modular arithmetic; it just โwraps aroundโ after reaching the set of available numbers. The simple context in which we all meet this is separation; the% operator, in fact, just gives the remainder of the division. Now that you understand what the% operator does, you can easily write your own code to do the same in any language.
Combining all this, you can write a utility, class, or extension method like this โ pay attention to% to calculate the remainder, and this simple integer division discards it:
/// <summary> /// Returns partition sized which are as close as possible to equal while using the indicated total size available, with any extra distributed to the front /// </summary> /// <param name="totalSize">The total number of elements to partition</param> /// <param name="partitionCount">The number of partitions to size</param> /// <param name="remainderAtFront">If true, any remainder will be distributed linearly starting at the beginning; if false, backwards from the end</param> /// <returns>An int[] containing the partition sizes</returns> public static int[] GetEqualizedPartitionSizes(int totalSize, int partitionCount, bool remainderAtFront = true) { if (totalSize < 1) throw new ArgumentException("Cannot partition a non-positive number (" + totalSize + ")"); else if (partitionCount < 1) throw new ArgumentException("Invalid partition count (" + partitionCount + ")"); else if (totalSize < partitionCount) throw new ArgumentException("Cannot partition " + totalSize + " elements into " + partitionCount + " partitions"); int[] partitionSizes = new int[partitionCount]; int basePartitionSize = totalSize / partitionCount; int remainder = totalSize % partitionCount; int remainderPartitionSize = basePartitionSize + 1; int x; if (remainderAtFront) { for (x = 0; x < remainder; x++) partitionSizes[x] = remainderPartitionSize; for (x = remainder; x < partitionCount; x++) partitionSizes[x] = basePartitionSize; } else { for (x = 0; x < partitionCount - remainder; x++) partitionSizes[x] = basePartitionSize; for (x = partitionCount - remainder; x < partitionCount; x++) partitionSizes[x] = remainderPartitionSize; } return partitionSizes; }
source share