This special kind of sequence has some perks, let’s check them: This object is a Sequence whose elements are produced via repeated applications of closure to some mutable state, that is our result. Next in this case is an escaping closure which means if you mutate the state inside the closure it will also mutate the state outside the closure.Īlso, this function definition is exactly what we need to build our Numberphile algorithm because the algorithm takes the output of the previous computations as an input for the next ones, which looks like a lot with recursive functions, but recursion is not the exercise today.Īnd the last part is the return of this function which is the UnfoldSequence object. This is the function that we will be using in this article to implement the algorithm described in the Numberphile video.įunction returns a sequence formed from repeated lazy applications of next to a mutable state. Let’s start checking how the sequence function is declared and dive in all its parts. Let’s explore this sequence generator function. Needless to say, if you are using this logic throughout the code, probably is better you encapsulate that in a proper type. This is very handy when you don’t want to create a whole type that conforms to Sequence and create your own IteratorProtocol conformance. The function sequence is part of the Swift Standard Library more specifically in the collections library and it enables you to create a sequence out of any object in Swift. When the number is less than 100 you can already guess because it is just the multiple of 7 until 14.Īnd you can reproduce that algorithm with just one Swift function that creates UnfoldSequences for you.Add that number to the quotient, which would lead us to 43(quotient) + 20( reminder times 5) which is equal to 63.Pick the reminder and multiply by 5, resulting in 20.In this case, 43 is the quotient and 4 is the reminder. For example, the number 434 would be split into 43 and 4. Divide the number by 10 splitting it into two parts.This involves you mutating the original number until it becomes small enough to discover by yourself if is divisible by seven or not.īelow check the algorithm proposed in the video with the number 434 as an example: James Grime explains a cool trick to know if a big number is divisible by seven. Number % 7 = 0 ? print("Is divisible!") : print("Not Divisible!")īut that would be too easy, right? Where’s the fun?Īs I was commenting earlier in the Numberphile video Dr.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |