Last active
November 10, 2023 20:51
-
-
Save theoknock/6990117f62ba11dae88dca1b14a26370 to your computer and use it in GitHub Desktop.
Provides a way to generate a sequence of numbers that increments and wraps around upon reaching a specified maximum value. This functionality can be particularly useful in scenarios where you need a cyclic counter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Generally, the code defines a closure that encapsulates a counter with the capability to reset itself after reaching a specified maximum value. It could be used in scenarios where a controlled repeatable series of integer values is needed. For instance, this functionality could be useful for: | |
// | |
//Generating unique identifiers that reset after reaching a maximum to avoid overflow or to keep values within a certain range. | |
//Implementing a circular buffer where the insertion point wraps around to the beginning after reaching the end. | |
//Creating sequences for animations or simulations where values need to restart after hitting a limit. | |
//Pacing of events where each event triggers the next, and after a certain number, the system resets. | |
//Gaming logic for turn-based games where player turns cycle through a fixed number of players. | |
//Cycling through a fixed set of resources or states in an application. | |
//In essence, it's a generator for a cyclical sequence of integers within a defined range from 0 up to, but not including, the maximum value specified. | |
func makeIncrementerWithReset(maximumValue: Int) -> ((Int) -> [Int]) { | |
var counter = 0 | |
let counter_max = maximumValue | |
func incrementCounter(count: Int) -> [Int] { | |
var numbersArray = [Int](repeating: 0, count: count) | |
for index in (0 ..< count) { | |
numbersArray[index] = counter | |
counter += 1 | |
if counter == counter_max { | |
counter = 0 | |
} | |
} | |
return numbersArray | |
} | |
return incrementCounter | |
} | |
let incrementer = makeIncrementerWithReset(maximumValue: 10) | |
for number in incrementer(6) { | |
print(number) | |
} | |
print("\n-------------------------\n") | |
for number in incrementer(7) { | |
print(number) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment