├── LICENSE
├── README.md
├── advanced-sorting
└── AdvancedSorting.playground
│ ├── Pages
│ ├── Merge Sort.xcplaygroundpage
│ │ └── Contents.swift
│ └── Quick Sort.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Sources
│ ├── ArrayExtension.swift
│ └── BenchTimer.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── algorithm-power
├── EquilibriumIndex.playground
│ ├── Contents.swift
│ ├── Sources
│ │ ├── ArrayExtension.swift
│ │ └── BenchTimer.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ │ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
├── FindTwoSum.playground
│ ├── Contents.swift
│ ├── Sources
│ │ ├── ArrayExtension.swift
│ │ └── BenchTimer.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ │ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
└── Sum(N).playground
│ ├── Contents.swift
│ ├── Sources
│ └── BenchTimer.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── assignments
├── FizzBuzz.playground
│ ├── Contents.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ │ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
├── Stack.playground
│ ├── Contents.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ │ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
└── stack.png
├── basic-data-structures
└── BasicDataStructures.playground
│ ├── Pages
│ ├── BalancingParentheses.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ └── Stack.swift
│ ├── Deque.xcplaygroundpage
│ │ └── Contents.swift
│ ├── MaxSlidingWindow-FirstTry.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ └── Deque.swift
│ ├── MaxSlidingWindowUsingDeque.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ └── Deque.swift
│ ├── MinMax.xcplaygroundpage
│ │ └── Contents.swift
│ ├── PrinterQueue.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ └── Queue.swift
│ ├── Queue.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Stack.xcplaygroundpage
│ │ └── Contents.swift
│ └── Tuple.xcplaygroundpage
│ │ └── Contents.swift
│ ├── contents.xcplayground
│ ├── playground.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcuserdata
│ │ └── knyisztor.xcuserdatad
│ │ └── UserInterfaceState.xcuserstate
│ └── xcuserdata
│ └── knyisztor.xcuserdatad
│ └── xcschemes
│ └── xcschememanagement.plist
├── basic-sorting
└── BasicSorting.playground
│ ├── Pages
│ ├── Bubble Sort.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Insertion Sort.xcplaygroundpage
│ │ └── Contents.swift
│ └── Selection Sort.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Sources
│ ├── ArrayExtension.swift
│ ├── BenchTimer.swift
│ └── SortingAlgorithms.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── big-o
└── Big-O.playground
│ ├── Pages
│ ├── Constant Time.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ ├── ArrayExtension.swift
│ │ │ └── DictionaryExtension.swift
│ ├── Linear Time.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ └── ArrayExtension.swift
│ └── Quadratic Time.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ └── Matrix.swift
│ ├── Sources
│ └── BenchTimer.swift
│ ├── contents.xcplayground
│ ├── playground.xcworkspace
│ ├── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
│ └── xcuserdata
│ │ └── knyisztor.xcuserdatad
│ │ └── UserInterfaceState.xcuserstate
│ └── xcuserdata
│ └── knyisztor.xcuserdatad
│ └── xcschemes
│ └── xcschememanagement.plist
├── collections
└── SwiftCollectionTypes.playground
│ ├── Pages
│ ├── The Array.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── Sources
│ │ │ └── ArrayExtension.swift
│ ├── The Dictionary.xcplaygroundpage
│ │ └── Contents.swift
│ ├── The Hashable Protocol.xcplaygroundpage
│ │ └── Contents.swift
│ └── The Set.xcplaygroundpage
│ │ └── Contents.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── generics
└── Generics.playground
│ ├── Pages
│ ├── Generic Functions.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Generic Types.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Pair Without Generics.xcplaygroundpage
│ │ └── Contents.swift
│ └── isEqual() Without Generics.xcplaygroundpage
│ │ └── Contents.swift
│ ├── contents.xcplayground
│ └── playground.xcworkspace
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
└── recursion
└── Recursion.playground
├── Pages
├── Factorial with BigInt.xcplaygroundpage
│ ├── Contents.swift
│ └── Sources
│ │ └── BigInt.swift
├── Factorial.xcplaygroundpage
│ └── Contents.swift
├── Infinite Recursion.xcplaygroundpage
│ └── Contents.swift
└── Node.xcplaygroundpage
│ ├── Contents.swift
│ └── timeline.xctimeline
├── contents.xcplayground
└── playground.xcworkspace
└── xcshareddata
└── IDEWorkspaceChecks.plist
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Algorithms and Data Structures in Swift 5
2 | ## Source Code
3 |
4 | The course is available on Udemy. **[CLICK HERE TO GET the course at a friendly price](https://www.udemy.com/course/introduction-to-algorithms-in-swift/?referralCode=B4C0C713F3E9132FE38A)**
5 | OR use this link: https://www.udemy.com/course/introduction-to-algorithms-in-swift/?referralCode=B4C0C713F3E9132FE38A
6 |
7 | 
8 |
9 | The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
10 |
11 | Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)** | My courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[LinkedIn Learning](https://www.linkedin.com/learning/instructors/karoly-nyisztor?u=2125562)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**. | Website **[www.leakka.com](http://www.leakka.com)**
12 |
13 | ***
14 | 
15 |
--------------------------------------------------------------------------------
/advanced-sorting/AdvancedSorting.playground/Pages/Merge Sort.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Merge Sort
9 | //: The merge sort is a fast divide-an-conquer algorithm.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 |
19 | func mergeSort(_ input: [Int]) -> [Int] {
20 | guard input.count > 1 else {
21 | return input
22 | }
23 |
24 | let splitIndex = input.count / 2
25 | let leftArray = mergeSort(Array(input[0.. [Int] {
32 | var sorted = [Int]()
33 |
34 | var leftIndex = 0
35 | var rightIndex = 0
36 |
37 | while leftIndex < leftPart.count && rightIndex < rightPart.count {
38 | if leftPart[leftIndex] < rightPart[rightIndex] {
39 | sorted.append(leftPart[leftIndex])
40 | leftIndex += 1
41 | } else if leftPart[leftIndex] > rightPart[rightIndex] {
42 | sorted.append(rightPart[rightIndex])
43 | rightIndex += 1
44 | } else {
45 | sorted.append(leftPart[leftIndex])
46 | leftIndex += 1
47 | sorted.append(rightPart[rightIndex])
48 | rightIndex += 1
49 | }
50 | }
51 |
52 | if leftIndex < leftPart.count {
53 | sorted.append(contentsOf: leftPart[leftIndex.. [Int] {
20 | guard input.count > 1 else {
21 | return input
22 | }
23 |
24 | let pivotIndex = input.count / 2
25 | let pivot = input[pivotIndex]
26 |
27 | let less = input.filter {$0 < pivot}
28 | let equal = input.filter {$0 == pivot}
29 | let greater = input.filter {$0 > pivot}
30 |
31 | return qsort(less) + equal + qsort(greater)
32 | }
33 | //: Test
34 | let array = Array.generateRandom(size: 20)
35 | print("The unsorted array:\n\(array)")
36 | let sorted = qsort(array)
37 |
38 | print("Sorted with quick sort:\n\(sorted)")
39 | //: [Previous: Merge Sort](@previous)
40 |
--------------------------------------------------------------------------------
/advanced-sorting/AdvancedSorting.playground/Sources/ArrayExtension.swift:
--------------------------------------------------------------------------------
1 | /// Generates random arrays of given size
2 | ///
3 | /// - Parameters:
4 | /// - size: size of the resulting array
5 | /// - Returns: array with random elements
6 | public extension Array where Element == Int {
7 | static func generateRandom(size: Int) -> [Int] {
8 | guard size > 0 else {
9 | return [Int]()
10 | }
11 | return Array(0.. Void) -> CFTimeInterval {
10 | let runCount = 10
11 | var executionTimes: Double = 0
12 | for _ in 0..= 1000 ? String(Int(self)) + "s"
29 | : self >= 1 ? String(format: "%.3gs", self)
30 | : self >= 1e-3 ? String(format: "%.3gms", self * 1e3)
31 | : self >= 1e-6 ? String(format: "%.3gµs", self * 1e6)
32 | : self < 1e-9 ? "0s"
33 | : String(format: "%.3gns", self * 1e9)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/advanced-sorting/AdvancedSorting.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/advanced-sorting/AdvancedSorting.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/algorithm-power/EquilibriumIndex.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Equilibrium Index
9 | //: An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 | import Foundation
17 |
18 | //: - Callout(First Attempt):
19 | //: O(n^2)
20 | func equilibrium(_ numbers: [Int]) -> [Int]? {
21 | guard numbers.count > 1 else {
22 | return nil
23 | }
24 |
25 | var indices = [Int]()
26 |
27 | var left = 0
28 | var right = 0
29 |
30 | let count = numbers.count
31 |
32 | for i in 0.. [Int]? {
55 | var indices = [Int]()
56 |
57 | var leftSum = 0
58 | var sum = numbers.reduce(0, +)
59 | let count = numbers.count
60 |
61 | for i in 0.. [Int] {
5 | var result = [Int](repeating: 0, count:size)
6 |
7 | for i in 0.. Void) -> CFTimeInterval {
10 | let runCount = 10
11 | var executionTimes: Double = 0
12 | for _ in 0..= 1000 ? String(Int(self)) + "s"
29 | : self >= 1 ? String(format: "%.3gs", self)
30 | : self >= 1e-3 ? String(format: "%.3gms", self * 1e3)
31 | : self >= 1e-6 ? String(format: "%.3gµs", self * 1e6)
32 | : self < 1e-9 ? "0s"
33 | : String(format: "%.3gns", self * 1e9)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithm-power/EquilibriumIndex.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/algorithm-power/EquilibriumIndex.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/algorithm-power/FindTwoSum.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Pair Matching
9 | //: Write a function that, given an array and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return nil.
10 | //: For example, findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12) should return any of the following tuples of indices:
11 | //:
12 | //: 1, 4 (3 + 9 = 12)
13 | //: 2, 3 (5 + 7 = 12)
14 | //: 3, 2 (7 + 5 = 12)
15 | //: 4, 1 (9 + 3 = 12)
16 | //:
17 | //: - Callout(Interested in Swift programming?):
18 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
19 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
20 | //: Website **[www.leakka.com](http://www.leakka.com)**
21 | //: ---
22 | import Foundation
23 | //: - Callout(TwoSum):
24 | //: O(n^2) running time
25 | func findTwoSum(_ array: [Int], target: Int) -> (Int, Int)? {
26 | guard array.count > 1 else {
27 | return nil
28 | }
29 |
30 | for i in 0.. (Int, Int)? {
55 | guard array.count > 1 else {
56 | return nil
57 | }
58 |
59 | var diffs = Dictionary()
60 |
61 | for i in 0.. [Int] {
5 | guard size > 0 else {
6 | return [Int]()
7 | }
8 | return Array(0.. Void) -> CFTimeInterval {
10 | let runCount = 10
11 | var executionTimes: Double = 0
12 | for _ in 0..= 1000 ? String(Int(self)) + "s"
29 | : self >= 1 ? String(format: "%.3gs", self)
30 | : self >= 1e-3 ? String(format: "%.3gms", self * 1e3)
31 | : self >= 1e-6 ? String(format: "%.3gµs", self * 1e6)
32 | : self < 1e-9 ? "0s"
33 | : String(format: "%.3gns", self * 1e9)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithm-power/FindTwoSum.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/algorithm-power/FindTwoSum.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/algorithm-power/Sum(N).playground/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Sum(N)
9 | //: Sums up the first N natural numbers
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | //: - Callout(Brute-force):
18 | //: Just for demonstration purposes, *don't* use it in real code!
19 | func sum(_ n: UInt) -> UInt {
20 | var result: UInt = 0
21 | for i in 1...n {
22 | result += i
23 | }
24 | return result
25 | }
26 |
27 | let step = 100
28 |
29 | var execTime: Double
30 | for i in 1...10 {
31 | execTime = BenchTimer.measureBlock {
32 | _ = sum(UInt(i*step))
33 | }
34 | print("Average sum(n) execution time for \(i*step) elements: \(execTime.formattedTime)")
35 | }
36 |
37 | //: - Callout(Optimized Sum):
38 | //: Sums up the first N natural numbers using the triangle numbers formula
39 | /// see https://en.wikipedia.org/wiki/Triangular_number
40 | func sumOptimized(_ n: UInt) -> UInt {
41 | return n * (n + 1) / 2
42 | }
43 |
44 | //: sum(n) vs. sumOptimized(n)
45 | print("\nsum() vs. sumOptimized()")
46 |
47 | var sumTime, sumOptimizedTime: Double
48 |
49 | for i in 1...10 {
50 | // Measure sum() function performance
51 | sumTime = BenchTimer.measureBlock {
52 | _ = sum(UInt(i*step))
53 | }
54 | // Measure sumOptimized() function performance
55 | sumOptimizedTime = BenchTimer.measureBlock {
56 | _ = sumOptimized(UInt(i*step))
57 | }
58 | print("- \(i*step) elements: \n\t sum(n) \t\t\t \(sumTime.formattedTime) \n\t sumOptimized(n) \t \(sumOptimizedTime.formattedTime)")
59 | }
60 |
--------------------------------------------------------------------------------
/algorithm-power/Sum(N).playground/Sources/BenchTimer.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | //: Utility class used for performance measurements
4 | import QuartzCore
5 |
6 | import XCTest
7 | public class BenchTimer: XCTestCase {
8 | // @inline(__always) optimizes for speed by telling the compiler to always inline the method, if possible
9 | @inline(__always) public static func measureBlock(closure: () -> Void) -> CFTimeInterval {
10 | let runCount = 10
11 | var executionTimes: Double = 0
12 | for _ in 0..= 1000 ? String(Int(self)) + "s"
29 | : self >= 1 ? String(format: "%.3gs", self)
30 | : self >= 1e-3 ? String(format: "%.3gms", self * 1e3)
31 | : self >= 1e-6 ? String(format: "%.3gµs", self * 1e6)
32 | : self < 1e-9 ? "0s"
33 | : String(format: "%.3gns", self * 1e9)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithm-power/Sum(N).playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/algorithm-power/Sum(N).playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/assignments/FizzBuzz.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Assignment
9 | //: The Fizz-Buzz Algorithm
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 | import Foundation
17 |
18 | func fizzBuzz(_ turns: Int) -> String {
19 | var strings = [String](repeating: "", count: turns)
20 |
21 | for index in 1...turns {
22 | if index % 15 == 0 {
23 | strings[index - 1] = "FizzBuzz"
24 | }
25 | else if index % 3 == 0 {
26 | strings[index - 1] = "Fizz"
27 | }
28 | else if index % 5 == 0 {
29 | strings[index - 1] = "Buzz"
30 | }
31 | else {
32 | strings[index - 1] = String(index)
33 | }
34 | }
35 |
36 | let result = strings.joined(separator: ", ")
37 | return result
38 | }
39 |
40 | //: Test
41 | let turns = 15
42 | let fb = fizzBuzz(turns)
43 | print(fb)
44 |
--------------------------------------------------------------------------------
/assignments/FizzBuzz.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/assignments/FizzBuzz.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/assignments/Stack.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Assignment
9 | //: An Array-based Generic Stack Implementation
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 | import Foundation
17 |
18 |
19 | struct Stack {
20 | private var elements = [T]()
21 |
22 | mutating func push(_ element: T) {
23 | elements.append(element)
24 | }
25 |
26 | mutating func pop() -> T? {
27 | return elements.popLast()
28 | }
29 |
30 | func peek() -> T? {
31 | return elements.last
32 | }
33 |
34 | var count: Int {
35 | return elements.count
36 | }
37 |
38 | var isEmpty: Bool {
39 | return elements.isEmpty
40 | }
41 | }
42 | //: Test
43 | var intStack = Stack()
44 |
45 | intStack.push(1)
46 | print("push() ->", intStack)
47 | print("Stack size: \(intStack.count)")
48 |
49 | intStack.push(2)
50 | print("push() ->", intStack)
51 | print("Stack size: \(intStack.count)")
52 |
53 | intStack.push(3)
54 | print("push() ->", intStack)
55 | print("Stack size: \(intStack.count)")
56 |
57 | print("peek() ->", intStack.peek() ?? "Stack is empty")
58 | print("Stack size: \(intStack.count)")
59 |
60 | print("pop() ->", intStack.pop() ?? "Stack is empty")
61 | print("Stack size: \(intStack.count)")
62 |
63 | print("pop() ->", intStack.pop() ?? "Stack is empty")
64 | print("Stack size: \(intStack.count)")
65 |
66 | print("pop() ->", intStack.pop() ?? "Stack is empty")
67 | print("Stack size: \(intStack.count)")
68 |
69 | intStack.pop()
70 | print(intStack)
71 | print("Stack size: \(intStack.count)")
72 |
73 |
--------------------------------------------------------------------------------
/assignments/Stack.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/assignments/Stack.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/assignments/stack.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nyisztor/swift-algorithms/fbfb5d60177c4f69124376d2aa9b21676ef04fa9/assignments/stack.png
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/BalancingParentheses.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | func isBalanced(expression: String) -> Bool {
2 | var stack = Stack()
3 |
4 | for character in expression {
5 | if character == "(" {
6 | stack.push(character)
7 | } else if character == ")" {
8 | if stack.isEmpty {
9 | return false
10 | } else {
11 | stack.pop()
12 | }
13 | }
14 | }
15 | return stack.isEmpty
16 | }
17 |
18 |
19 | let expr1 = "(1 + 2) * (3 + 4)"
20 | let expr2 = "(1 + 2 * (3 + 4)"
21 |
22 | print("\(expr1) is \(isBalanced(expression: expr1) ? "balanced" : "not balanced")" )
23 | print("\(expr2) is \(isBalanced(expression: expr2) ? "balanced" : "not balanced")" )
24 |
25 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/BalancingParentheses.xcplaygroundpage/Sources/Stack.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public struct Stack {
4 | private var storage: [Element] = []
5 |
6 | public init() {}
7 |
8 | public mutating func push(_ element: Element) {
9 | storage.append(element)
10 | }
11 |
12 | public mutating func pop() -> Element? {
13 | storage.isEmpty ? nil : storage.removeLast()
14 | }
15 |
16 | public var peek: Element? {
17 | storage.last
18 | }
19 |
20 | public var isEmpty: Bool {
21 | storage.isEmpty
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/Deque.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public struct Deque {
4 | private var storage: [Element] = []
5 |
6 | // Create an empty deque
7 | public init() {}
8 |
9 | // Insert an element at the front of the deque
10 | public mutating func enqueueFront(_ element: Element) {
11 | storage.insert(element, at: 0)
12 | }
13 |
14 | // Add an element to the end of the deque
15 | public mutating func enqueueBack(_ element: Element) {
16 | storage.append(element)
17 | }
18 |
19 | // Remove the element from the front of the deque and return it
20 | public mutating func dequeueFront() -> Element? {
21 | storage.isEmpty ? nil : storage.removeFirst()
22 | }
23 |
24 | // Remove the element from the end of the deque and return it
25 | public mutating func dequeueBack() -> Element? {
26 | storage.isEmpty ? nil : storage.removeLast()
27 | }
28 |
29 | // Check if the deque is empty
30 | public var isEmpty: Bool {
31 | storage.isEmpty
32 | }
33 |
34 | // Return the element at the front of the deque without removing it
35 | public var peekFront: Element? {
36 | storage.first
37 | }
38 |
39 | // Return the element at the back of the deque without removing it
40 | public var peekBack: Element? {
41 | storage.last
42 | }
43 | }
44 |
45 | extension Deque: CustomStringConvertible {
46 | public var description: String {
47 | storage.description
48 | }
49 | }
50 |
51 | // Usage example
52 | var deque = Deque()
53 |
54 | deque.enqueueFront(1)
55 | deque.enqueueFront(2)
56 | deque.enqueueBack(3)
57 | deque.enqueueBack(4)
58 |
59 | print(deque) // prints "[2, 1, 3, 4]"
60 |
61 | let emptyWarning = "Deque is empty"
62 |
63 | print(deque.dequeueFront() ?? emptyWarning) // prints "2"
64 | print(deque.dequeueBack() ?? emptyWarning) // print "4"
65 |
66 | print(deque) // prints "[1, 3]"
67 |
68 | print(deque.peekFront ?? emptyWarning) // prints "1"
69 | print(deque.peekBack ?? emptyWarning) // prints "3"
70 |
71 | print(deque) // prints "[1, 3]"
72 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/MaxSlidingWindow-FirstTry.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | // Time complexity O(n * k)
4 | func findSlidingWindowMax(_ numbers: [Int], windowSize: Int) -> [Int] {
5 | var result = [Int]()
6 |
7 | guard numbers.isEmpty == false,
8 | windowSize >= 1,
9 | windowSize <= numbers.count else {
10 | return result
11 | }
12 |
13 | switch (windowSize) {
14 | case 1:
15 | result = numbers
16 | case numbers.count:
17 | if let max = numbers.max() {
18 | result = [max]
19 | }
20 | default:
21 | for i in 0...numbers.count - windowSize {
22 | let window = Array(numbers[i.. {
4 | private var storage: [Element] = []
5 |
6 | // Create an empty deque
7 | public init() {}
8 |
9 | // Insert an element at the front of the deque
10 | public mutating func enqueueFront(_ element: Element) {
11 | storage.insert(element, at: 0)
12 | }
13 |
14 | // Add an element to the end of the deque
15 | public mutating func enqueueBack(_ element: Element) {
16 | storage.append(element)
17 | }
18 |
19 | // Remove the element from the front of the deque and return it
20 | public mutating func dequeueFront() -> Element? {
21 | storage.isEmpty ? nil : storage.removeFirst()
22 | }
23 |
24 | // Remove the element from the end of the deque and return it
25 | public mutating func dequeueBack() -> Element? {
26 | storage.isEmpty ? nil : storage.removeLast()
27 | }
28 |
29 | // Check if the deque is empty
30 | public var isEmpty: Bool {
31 | storage.isEmpty
32 | }
33 |
34 | // Return the element at the front of the deque without removing it
35 | public var peekFront: Element? {
36 | storage.first
37 | }
38 |
39 | // Return the element at the back of the deque without removing it
40 | public var peekBack: Element? {
41 | storage.last
42 | }
43 | }
44 |
45 | extension Deque: CustomStringConvertible {
46 | public var description: String {
47 | storage.description
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/MaxSlidingWindowUsingDeque.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | // Time complexity O(n)
3 | func findSlidingWindowMax(_ numbers: [Int], windowSize: Int) -> [Int] {
4 | var deque = Deque()
5 | var result = [Int]()
6 |
7 | guard numbers.isEmpty == false,
8 | windowSize >= 1,
9 | windowSize <= numbers.count else {
10 | return result
11 | }
12 |
13 | switch (windowSize) {
14 | case 1:
15 | result = numbers
16 | case numbers.count:
17 | if let max = numbers.max() {
18 | result = [max]
19 | }
20 | default:
21 | for i in 0..= last {
23 | deque.dequeueBack()
24 | }
25 |
26 | deque.enqueueBack(numbers[i])
27 |
28 | let windowStartIndex = i - windowSize + 1
29 | // check if a complete window has formed
30 | if windowStartIndex >= 0 {
31 | if let maxElement = deque.peekFront {
32 | result.append(maxElement)
33 |
34 | if numbers[windowStartIndex] == maxElement {
35 | deque.dequeueFront()
36 | }
37 | }
38 | }
39 | }
40 | }
41 | return result
42 | }
43 |
44 | let inputArray = [1, 3, -1, -3, 5, 3, 6, 7]
45 |
46 | let result = findSlidingWindowMax(inputArray, windowSize: 3)
47 | print(result)
48 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/MaxSlidingWindowUsingDeque.xcplaygroundpage/Sources/Deque.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public struct Deque {
4 | private var storage: [Element] = []
5 |
6 | // Create an empty deque
7 | public init() {}
8 |
9 | // Insert an element at the front of the deque
10 | public mutating func enqueueFront(_ element: Element) {
11 | storage.insert(element, at: 0)
12 | }
13 |
14 | // Add an element to the end of the deque
15 | public mutating func enqueueBack(_ element: Element) {
16 | storage.append(element)
17 | }
18 |
19 | // Remove the element from the front of the deque and return it
20 | public mutating func dequeueFront() -> Element? {
21 | storage.isEmpty ? nil : storage.removeFirst()
22 | }
23 |
24 | // Remove the element from the end of the deque and return it
25 | public mutating func dequeueBack() -> Element? {
26 | storage.isEmpty ? nil : storage.removeLast()
27 | }
28 |
29 | // Check if the deque is empty
30 | public var isEmpty: Bool {
31 | storage.isEmpty
32 | }
33 |
34 | // Return the element at the front of the deque without removing it
35 | public var peekFront: Element? {
36 | storage.first
37 | }
38 |
39 | // Return the element at the back of the deque without removing it
40 | public var peekBack: Element? {
41 | storage.last
42 | }
43 | }
44 |
45 | extension Deque: CustomStringConvertible {
46 | public var description: String {
47 | storage.description
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/MinMax.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | // MinMax
2 | import Foundation
3 | /*
4 | // Uses a custom struct to represent the result
5 | struct MinMax {
6 | var min: Int
7 | var max: Int
8 | }
9 |
10 | func minMax(of numbers: [Int]) -> MinMax? {
11 | guard let min = numbers.min(), let max = numbers.max() else {
12 | return nil
13 | }
14 | return MinMax(min: min, max: max)
15 | }
16 |
17 | let numbers = [10, 5, 2, 7, 1, 9]
18 | if let result = minMax(of: numbers) {
19 | print("\nInput: \(numbers) \n\tMinimum: \(result.min) \n\tMaximum: \(result.max)")
20 | }*/
21 |
22 | /*
23 | // Uses an array to represent the result
24 | func minMax(of numbers: [Int]) -> [Int]? {
25 | guard let min = numbers.min(), let max = numbers.max() else {
26 | return nil
27 | }
28 | return [min, max]
29 | }
30 |
31 | let numbers = [10, 5, 2, 7, 1, 9]
32 | if let result = minMax(of: numbers) {
33 | print("\nInput: \(numbers) \n\tMinimum: \(result[0]) \n\tMaximum: \(result[1])")
34 | }*/
35 |
36 | func minMax(of numbers: [Int]) -> (min: Int, max: Int)? {
37 | guard let min = numbers.min(), let max = numbers.max() else {
38 | return nil
39 | }
40 | return (min, max)
41 | }
42 |
43 | let numbers = [10, 5, 2, 7, 1, 9]
44 | if let result = minMax(of: numbers) {
45 | print("\nInput: \(numbers) \n\tMinimum: \(result.min) \n\tMaximum: \(result.max)")
46 | }
47 |
48 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/PrinterQueue.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | struct PrintJob {
2 | let documentName: String
3 | let numberOfPages: Int
4 | }
5 |
6 | var printQueue = Queue()
7 |
8 | printQueue.enqueue(PrintJob(documentName: "Document A", numberOfPages: 10))
9 | printQueue.enqueue(PrintJob(documentName: "Document B", numberOfPages: 5))
10 | printQueue.enqueue(PrintJob(documentName: "Document C", numberOfPages: 15))
11 |
12 | func process(job: PrintJob) {
13 | print("Printing \(job.documentName) with \(job.numberOfPages) pages")
14 | }
15 |
16 | while !printQueue.isEmpty {
17 | if let printJob = printQueue.dequeue() {
18 | process(job: printJob)
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/PrinterQueue.xcplaygroundpage/Sources/Queue.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public struct Queue {
4 | private var storage: [Element] = []
5 |
6 | // Create an empty queue
7 | public init() {}
8 |
9 | // Add an element to the end of the queue
10 | public mutating func enqueue(_ element: Element) {
11 | storage.append(element)
12 | }
13 |
14 | // Remove the element from the front of the queue and return it
15 | public mutating func dequeue() -> Element? {
16 | storage.isEmpty ? nil : storage.removeFirst()
17 | }
18 |
19 | // Return the element at the front of the queue without removing it
20 | public var peek: Element? {
21 | storage.first
22 | }
23 |
24 | // Check if the queue is empty
25 | public var isEmpty: Bool {
26 | storage.isEmpty
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/Queue.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public struct Queue {
4 | private var storage: [Element] = []
5 |
6 | // Create an empty queue
7 | public init() {}
8 |
9 | // Add an element to the end of the queue
10 | public mutating func enqueue(_ element: Element) {
11 | storage.append(element)
12 | }
13 |
14 | // Remove the element from the front of the queue and return it
15 | public mutating func dequeue() -> Element? {
16 | storage.isEmpty ? nil : storage.removeFirst()
17 | }
18 |
19 | // Return the element at the front of the queue without removing it
20 | public var peek: Element? {
21 | storage.first
22 | }
23 |
24 | // Check if the queue is empty
25 | public var isEmpty: Bool {
26 | storage.isEmpty
27 | }
28 | }
29 |
30 | // Usage example
31 | var queue = Queue()
32 | queue.enqueue(10)
33 | queue.enqueue(20)
34 | queue.enqueue(30)
35 |
36 | print(queue.peek ?? "Queue is empty")
37 |
38 | while let element = queue.dequeue() {
39 | print(element)
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/Stack.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | public struct Stack {
2 | private var storage: [Element] = []
3 |
4 | public init() {}
5 |
6 | public mutating func push(_ element: Element) {
7 | storage.append(element)
8 | }
9 |
10 | public mutating func pop() -> Element? {
11 | storage.isEmpty ? nil : storage.removeLast()
12 | }
13 |
14 | public var peek: Element? {
15 | storage.last
16 | }
17 |
18 | public var isEmpty: Bool {
19 | storage.isEmpty
20 | }
21 | }
22 |
23 | // Usage examples
24 | var intStack = Stack()
25 |
26 | intStack.push(5)
27 | intStack.push(10)
28 |
29 |
30 | let emptyMessage = "Stack is empty"
31 | print(intStack.peek ?? emptyMessage)
32 | print(intStack.pop() ?? emptyMessage)
33 | print(intStack.pop() ?? emptyMessage)
34 | print(intStack.isEmpty)
35 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/Pages/Tuple.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | // The Tuple
2 | var coordinates = (x: 3, y: 5, z: -1)
3 |
4 | var nameAndAge = (name: "Alice", age: 28)
5 |
6 | var httpStatus = (code: 404, description: (brief: "Not Found", verbose: "The requested page can't be found on the website server."))
7 |
8 | let thirdElement = coordinates.2
9 |
10 | let (x, y, z) = coordinates
11 | print("x: \(x)\ny: \(y)\nz: \(z)")
12 |
13 | let (name, _) = nameAndAge
14 | print("Name: \(name)")
15 |
16 | let code = httpStatus.code
17 | let longDescription = httpStatus.description.verbose
18 |
19 | nameAndAge.age = 29
20 |
21 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/playground.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/playground.xcworkspace/xcuserdata/knyisztor.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nyisztor/swift-algorithms/fbfb5d60177c4f69124376d2aa9b21676ef04fa9/basic-data-structures/BasicDataStructures.playground/playground.xcworkspace/xcuserdata/knyisztor.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/basic-data-structures/BasicDataStructures.playground/xcuserdata/knyisztor.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | BasicDataStructures (Playground).xcscheme
8 |
9 | isShown
10 |
11 | orderHint
12 | 0
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/basic-sorting/BasicSorting.playground/Pages/Bubble Sort.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Bubble Sort
9 | //: The Bubble Sort algorithm works by repeatedly evaluating adjacent items and swapping their position if they are in the wrong order.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: Bubble Sort - Sorting Random Arrays
19 | // Warmup
20 | var warmupArray = Array(repeating: 0, count: 100)
21 | _ = BenchTimer.measureBlock {
22 | _ = warmupArray.bubbleSorted()
23 | }
24 |
25 | print("Average bubble sort execution time for shuffled array")
26 | print("-----------------------------------------------------")
27 |
28 | let arraySizes = [5, 10, 100]
29 | var sortedArray = [Int]()
30 |
31 | // generate arrays and measure method call
32 | for size in arraySizes {
33 | let array = Array.generateRandom(size: size)
34 |
35 | let execTime = BenchTimer.measureBlock {
36 | sortedArray = array.bubbleSorted()
37 | }
38 |
39 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
40 | }
41 |
42 | //: Bubble Sort - Sorting Ordered Arrays
43 | print("\nAverage bubble sort execution time for already sorted array")
44 | print("-----------------------------------------------------------")
45 |
46 | for size in arraySizes {
47 | let array = Array(0.. %@", array.count, execTime.formattedTime))
54 | }
55 |
56 | //: Bubble Sort - Sorting Reverse Ordered Arrays
57 | print("\nAverage bubble sort execution time for reverse ordered array")
58 | print("------------------------------------------------------------")
59 |
60 | for size in arraySizes {
61 | let array = Array(0.. %@", array.count, execTime.formattedTime))
68 | }
69 | //: Bubble Sort vs. Selection Sort vs. Insertion Sort with Shuffled Array
70 | print("\nBubble Sort vs. Insertion Sort vs. Selection Sort with shuffled arrays")
71 | print("----------------------------------------------------------------------")
72 |
73 | for size in arraySizes {
74 | let array = Array.generateRandom(size: size)
75 | let bubbleSortTime = BenchTimer.measureBlock {
76 | sortedArray = array.bubbleSorted()
77 | }
78 | print("\nSize \(array.count)")
79 | print(String(format: "\tBubble sort -> %@", bubbleSortTime.formattedTime))
80 |
81 | let insertionSortTime = BenchTimer.measureBlock {
82 | sortedArray = array.insertionSorted()
83 | }
84 | print(String(format: "\tInsertion sort -> %@", insertionSortTime.formattedTime))
85 |
86 | let selectionSortTime = BenchTimer.measureBlock {
87 | sortedArray = array.selectionSorted()
88 | }
89 | print(String(format: "\tSelection sort -> %@", selectionSortTime.formattedTime))
90 | }
91 | //: [Previous: Insertion Sort](@previous)
92 |
--------------------------------------------------------------------------------
/basic-sorting/BasicSorting.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Insertion Sort
9 | //: Insertion sort is a basic sorting algorithm, which works by analyzing each element and inserting it into its proper place, while larger elements move one position to the right.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 | import Foundation
17 | import XCTest
18 | //: Insertion Sort - Sorting Random Arrays
19 | // Warmup
20 | var warmupArray = Array(repeating: 0, count: 100)
21 | _ = BenchTimer.measureBlock {
22 | _ = warmupArray.insertionSorted()
23 | }
24 |
25 | print("Average insertion sort execution time for shuffled array")
26 | print("--------------------------------------------------------")
27 |
28 | let arraySizes = [5, 10, 100]
29 | var sortedArray = [Int]()
30 |
31 | // generate arrays and measure method call
32 | for size in arraySizes {
33 | let array = Array.generateRandom(size: size)
34 |
35 | let execTime = BenchTimer.measureBlock {
36 | sortedArray = array.insertionSorted()
37 | }
38 |
39 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
40 | }
41 | //: Insertion Sort - Sorting Ordered Arrays
42 | print("\nAverage insertion sort execution time for already sorted array")
43 | print("--------------------------------------------------------------")
44 |
45 | for size in arraySizes {
46 | let array = Array(0.. %@", array.count, execTime.formattedTime))
53 | }
54 | //: Insertion Sort - Sorting Reverse Ordered Arrays
55 | print("\nAverage insertion sort execution time for reverse ordered array")
56 | print("---------------------------------------------------------------")
57 |
58 | for size in arraySizes {
59 | let array = Array(0.. %@", array.count, execTime.formattedTime))
66 | }
67 | //: Selection Sort vs. Insertion Sort with Shuffled Array
68 | print("\nInsertion Sort vs. Selection Sort with shuffled arrays")
69 | print("------------------------------------------------------")
70 |
71 | for size in arraySizes {
72 | let array = Array.generateRandom(size: size)
73 |
74 | print("\nSize \(array.count)")
75 | let insertionSortTime = BenchTimer.measureBlock {
76 | sortedArray = array.insertionSorted()
77 | }
78 | print(String(format: "\tInsertion sort -> %@", insertionSortTime.formattedTime))
79 |
80 | let selectionSortTime = BenchTimer.measureBlock {
81 | sortedArray = array.selectionSorted()
82 | }
83 | print(String(format: "\tSelection sort -> %@", selectionSortTime.formattedTime))
84 | }
85 | //: [Previous: Selection Sort](@previous) | [Next: Bubble Sort](@next)
86 |
--------------------------------------------------------------------------------
/basic-sorting/BasicSorting.playground/Pages/Selection Sort.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Selection Sort
9 | //: We'll start the study of basic sorting algorithms with the selection sort algorithm.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 |
19 | //: Selection Sort - Sorting Random Arrays
20 | // Warmup
21 | var warmupArray = Array(repeating: 0, count: 100)
22 | _ = BenchTimer.measureBlock {
23 | _ = warmupArray.selectionSorted()
24 | }
25 |
26 |
27 | print("Average selection sort execution time for shuffled array")
28 | print("--------------------------------------------------------")
29 |
30 | let arraySizes = [5, 10, 100]
31 | var sortedArray = [Int]()
32 |
33 | // generate arrays and measure method call
34 | for size in arraySizes {
35 | let array = Array.generateRandom(size: size)
36 |
37 | let execTime = BenchTimer.measureBlock {
38 | sortedArray = array.selectionSorted()
39 | }
40 |
41 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
42 | }
43 | //: Selection Sort - Sorting Ordered Arrays
44 | print("\nAverage selection sort execution time for already sorted array")
45 | print("--------------------------------------------------------------")
46 |
47 | for size in arraySizes {
48 | let array = Array(0.. %@", array.count, execTime.formattedTime))
55 | }
56 | //: Selection Sort - Sorting Reverse Ordered Arrays
57 | print("\nAverage selection sort execution time for reverse ordered array")
58 | print("---------------------------------------------------------------")
59 |
60 | for size in arraySizes {
61 | let array = Array(0.. %@", array.count, execTime.formattedTime))
68 | }
69 | //: [Next: Insertion Sort](@next)
70 |
--------------------------------------------------------------------------------
/basic-sorting/BasicSorting.playground/Sources/ArrayExtension.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | /// Generates random arrays of given size
4 | ///
5 | /// - Parameters:
6 | /// - size: size of the resulting array
7 | /// - Returns: array with random elements
8 | public extension Array where Element == Int {
9 | static func generateRandom(size: Int) -> [Int] {
10 | guard size > 0 else {
11 | return [Int]()
12 | }
13 | return Array(0.. Void) -> CFTimeInterval {
10 | let runCount = 10
11 | var executionTimes: Double = 0
12 | for _ in 0..= 1000 ? String(Int(self)) + "s"
29 | : self >= 1 ? String(format: "%.3gs", self)
30 | : self >= 1e-3 ? String(format: "%.3gms", self * 1e3)
31 | : self >= 1e-6 ? String(format: "%.3gµs", self * 1e6)
32 | : self < 1e-9 ? "0s"
33 | : String(format: "%.3gns", self * 1e9)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/basic-sorting/BasicSorting.playground/Sources/SortingAlgorithms.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public extension Array where Element == Int {
4 | @inline(__always) func selectionSorted() -> Array {
5 | guard count > 1 else {
6 | return self
7 | }
8 |
9 | var result = self
10 | for index in 0..<(result.count - 1) {
11 | var indexLowest = index
12 |
13 | for forwardIndex in (index + 1).. Array {
27 | guard count > 1 else {
28 | return self
29 | }
30 |
31 | var result = self
32 |
33 | for sortedIndex in 1.. 0 && temp < result[backIndex - 1] {
38 | result[backIndex] = result[backIndex - 1]
39 | backIndex -= 1
40 | }
41 | result[backIndex] = temp
42 | }
43 | return result
44 | }
45 |
46 |
47 | @inline(__always) func bubbleSorted() -> Array {
48 | guard count > 1 else {
49 | return self
50 | }
51 |
52 | var result = self
53 | var isSwapped = false
54 |
55 | repeat {
56 | isSwapped = false
57 | for index in 1..
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/basic-sorting/BasicSorting.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/Pages/Constant Time.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Constant Time - O(1)
9 | //: Demo to demonstrate constant time complexity
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 |
19 | //: Array Element Check - O(1)
20 |
21 | // Warmup
22 | var warmupArray = Array(repeating: 0, count: 100)
23 | _ = BenchTimer.measureBlock {
24 | _ = warmupArray.startsWithZero()
25 | }
26 |
27 |
28 | print("Average check first element execution time for an array")
29 | print("-------------------------------------------------------")
30 |
31 | let arraySizes = [10, 100, 1000, 10000, 100000]
32 |
33 | // generate arrays and measure method call
34 | for size in arraySizes {
35 | let array = Array(repeating: 0, count: size)
36 |
37 | let execTime = BenchTimer.measureBlock {
38 | _ = array.startsWithZero()
39 | }
40 |
41 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
42 | }
43 | //: Dictionary Search - O(1)
44 | print("\nAverage element lookup time in a dictionary")
45 | print("---------------------------------------------")
46 |
47 | let dictSizes = [100, 1000, 100000]
48 |
49 | // generate dictionaries and measure lookup
50 | for size in dictSizes {
51 | let dictionary = Dictionary.generate(size: size)
52 | let randomKey = String(Int.random(in: 0.. %@", dictionary.count, execTime.formattedTime))
59 | }
60 | //: [Next: Linear Time](@next)
61 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/Pages/Constant Time.xcplaygroundpage/Sources/ArrayExtension.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public extension Array where Element == Int {
4 | // Checks if the first element in an array of integers is 0
5 | func startsWithZero() -> Bool {
6 | guard self.isEmpty == false else {
7 | return false
8 | }
9 | return self.first == 0 ? true : false
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/Pages/Constant Time.xcplaygroundpage/Sources/DictionaryExtension.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | // Generates dictionaries of given size in the form ["0": 0, "1": 1, ... "1000": 1000]
4 | public extension Dictionary where Key == String, Value == Int {
5 | static func generate(size: Int) -> [String: Int] {
6 | var result = [String: Int]()
7 | guard size > 0 else {
8 | return result
9 | }
10 |
11 | let values = Array(0..(repeating: 0, count: 100)
22 | _ = BenchTimer.measureBlock {
23 | _ = warmupArray.sum()
24 | }
25 |
26 | print("\nAverage execution time for array sum using a loop")
27 | print("---------------------------------------------------")
28 |
29 | //let arraySizes = [10, 100, 1000, 10000]
30 | let arraySizes = [100, 10000, 100000]
31 |
32 | // generate arrays and measure method call
33 | for size in arraySizes {
34 | let array = Array.generateRandom(size: size)
35 |
36 | let execTime = BenchTimer.measureBlock {
37 | _ = array.sum()
38 | }
39 |
40 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
41 | }
42 | // Using reduce()
43 | print("\nAverage execution time for array sum using reduce()")
44 | print("---------------------------------------------------")
45 |
46 | for size in arraySizes {
47 | let array = Array.generateRandom(size: size)
48 |
49 | let execTime = BenchTimer.measureBlock {
50 | // The first argument passed to reduce() is the initial value, in this case 0.
51 | // The second argument tells how it should combine that 0 with each item in the array, which means it will sum up all the elements
52 | _ = array.reduce(0, +)
53 | }
54 |
55 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
56 | }
57 | //: Count odd/even - O(n)
58 | print("\nAverage execution time for counting the number of odd and even elements in a list")
59 | print("---------------------------------------------------------------------------------")
60 |
61 | for size in arraySizes {
62 | let array = Array.generateRandom(size: size)
63 |
64 | let execTime = BenchTimer.measureBlock {
65 | _ = array.countOddEven()
66 | }
67 |
68 | print(String(format: "Size %d -> %@", array.count, execTime.formattedTime))
69 | }
70 | //: [Previous: Constant Time](@previous) | [Next: Quadratic Time](@next)
71 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/Pages/Linear Time.xcplaygroundpage/Sources/ArrayExtension.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | /// Generates random arrays of given size
4 | ///
5 | /// - Parameters:
6 | /// - size: size of the resulting array
7 | /// - Returns: array with random elements
8 | public extension Array where Element == Int {
9 | static func generateRandom(size: Int) -> [Int] {
10 | guard size > 0 else {
11 | return [Int]()
12 | }
13 | return Array(0.. Int {
18 | var result = 0
19 | for i in 0.. (even: UInt, odd: UInt) {
27 | var even: UInt = 0
28 | var odd: UInt = 0
29 |
30 | for elem in self {
31 | if elem % 2 == 0 {
32 | even += 1
33 | } else {
34 | odd += 1
35 | }
36 | }
37 | return (even, odd)
38 | }
39 |
40 | /*
41 | static func generateRandom2(size: Int) -> [Int] {
42 | guard size > 0 else {
43 | return [Int]()
44 | }
45 | var result = Array(repeating: 0, count: size)
46 | for index in 0.. [Int] {
53 | guard size > 0 else {
54 | return [Int]()
55 | }
56 |
57 | let result = Array(repeating: 0, count: size)
58 | return result.map{_ in Int.random(in: 0.. [Int] {
21 | guard size > 0 else {
22 | return [Int]()
23 | }
24 |
25 | var table = [Int]()
26 | let array = [Int](1...size)
27 |
28 | for row in 0.. [Int] {
40 | guard size > 0 else {
41 | return [Int]()
42 | }
43 | // Performance optimization:
44 | // - initialize the table to its max capacity
45 | // - assign by index instead of calling append() to add elements
46 | var table = [Int](repeating: 0, count: size * size)
47 | let array = [Int](1...size)
48 |
49 | for row in 0.. [[Int]] {
60 | // initialize the table to its max size
61 | var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
62 | let array = [Int](1...size)
63 |
64 | for row in 0.. Matrix {
75 | // initialize the table to its max size
76 | var table = Matrix(rows: size, columns: size, repeating: 0)
77 | //var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
78 | let array = [Int](1...size)
79 |
80 | for row in 0.. %@", size, execTime.formattedTime))
103 | }
104 |
105 | print("\nAverage execution time for multiplication table optimized")
106 | print("---------------------------------------------------------")
107 |
108 | for i in 0.. %@", size, execTime.formattedTime))
115 | }
116 |
117 | print("\nAverage execution time for multiplication table with 2D array")
118 | print("-------------------------------------------------------------")
119 |
120 | for i in 0.. %@", size, execTime.formattedTime))
127 | }
128 |
129 | print("\nAverage execution time for multiplication table with custom Matrix")
130 | print("------------------------------------------------------------------")
131 |
132 | for i in 0.. %@", size, execTime.formattedTime))
139 | }
140 | //: [Previous: Linear Time](@previous)
141 |
142 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/Pages/Quadratic Time.xcplaygroundpage/Sources/Matrix.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | public struct Matrix {
4 | let rows: Int, columns: Int
5 | var grid: [E]
6 |
7 | public init(rows: Int, columns: Int, repeating: E) {
8 | self.rows = rows
9 | self.columns = columns
10 | grid = Array(repeating: repeating, count: rows * columns)
11 | }
12 |
13 | public func isValidIndex(row: Int, column: Int) -> Bool {
14 | return row >= 0 && row < rows && column >= 0 && column < columns
15 | }
16 |
17 | public subscript(row: Int, column: Int) -> E {
18 | get {
19 | assert(isValidIndex(row: row, column: column), "Index out of range")
20 | return grid[(row * columns) + column]
21 | }
22 | set {
23 | assert(isValidIndex(row: row, column: column), "Index out of range")
24 | grid[(row * columns) + column] = newValue
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/Sources/BenchTimer.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | //: Utility class used for performance measurements
4 | import QuartzCore
5 |
6 | public final class BenchTimer {
7 | // @inline(__always) optimizes for speed by telling the compiler to always inline the method, if possible
8 | @inline(__always) public static func measureBlock(executionCount: UInt = 10, closure: () -> Void) -> CFTimeInterval {
9 | var executionTimes: Double = 0
10 | for _ in 0..= 1000 ? String(Int(self)) + "s"
27 | : self >= 1 ? String(format: "%.3gs", self)
28 | : self >= 1e-3 ? String(format: "%.3gms", self * 1e3)
29 | : self >= 1e-6 ? String(format: "%.3gµs", self * 1e6)
30 | : self < 1e-9 ? "0s"
31 | : String(format: "%.3gns", self * 1e9)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/big-o/Big-O.playground/playground.xcworkspace/xcuserdata/knyisztor.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nyisztor/swift-algorithms/fbfb5d60177c4f69124376d2aa9b21676ef04fa9/big-o/Big-O.playground/playground.xcworkspace/xcuserdata/knyisztor.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/big-o/Big-O.playground/xcuserdata/knyisztor.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | Big-O (Playground).xcscheme
8 |
9 | isShown
10 |
11 | orderHint
12 | 0
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/Pages/The Array.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## The Array
9 | //: Let's take a closer look at the Swift Array
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 |
19 | //: - Callout(Arrays):
20 | //: Ordered sequence of non-unique elements
21 |
22 | let numbers: Array = [1, 2, 5, 3, 1, 2]
23 |
24 | let numbers1: [Int] = [1, 2, 5, 3, 1, 2] // shorthand form - preferred!
25 |
26 | //: - Callout(Type Inference):
27 | //: Swift's type inference engine can work out the type of the array
28 |
29 | let numbers2 = [1, 2, 5, 3, 1, 2] // Swift infers the Int type
30 |
31 | let doubles = [1.0, 2.0, 5.0, 3.0, 1.0, 2.0] // Array of Double
32 |
33 | // Exolicitely specify Float, otherwise will be Double
34 | let floats: [Float] = [1.0, 2.0, 5.0] // Array of Float
35 |
36 | print(numbers)
37 | // Output: [0, 2, 1, 3, 1, 42]
38 | // 0 1 2 3 4 5
39 | // [0, 2, 1, 3, 1, 42]
40 |
41 | //: - Callout(Array Indices):
42 | //: We can iterate through the array and print the indices using the Array index(of:) and forEach(_:) instance methods
43 | for value in numbers {
44 | if let index = numbers.firstIndex(of: value) {
45 | print("Index of \(value) is \(index)")
46 | }
47 | }
48 |
49 | numbers.forEach { value in
50 | if let index = numbers.firstIndex(of: value) {
51 | print("Index of \(value) is \(index)")
52 | }
53 | }
54 |
55 | //: - Callout(Accessing the Array):
56 | //: Access by index and using first and last accessors
57 | let second = numbers[1] // dangerous, we haven't checked whether the index is valid!
58 |
59 | let emptyArray = [Int]()
60 | let first = emptyArray.first // returns nil
61 | let last = emptyArray.last // returns nil
62 |
63 |
64 | //: - Callout(Index Bounds Check):
65 | //: Prevent crashes by checking whether the index is within bounds
66 |
67 | let index = 1
68 | // check index
69 | if index >= 0,
70 | index < numbers.count {
71 | let t = numbers[index]
72 | print(t)
73 | }
74 |
75 | // using indices.contains
76 | if numbers.indices.contains(index) {
77 | let t = numbers[index]
78 | print(t)
79 | }
80 |
81 | let t = emptyArray[safe: index]
82 | print(t ?? "no value at index \(index)")
83 | //: - Callout(Mutable Arrays):
84 | //: Assign the array to a variable to allow changes after creating it
85 | var mutableNumbers = [1, 2, 5, 3, 1, 2]
86 | mutableNumbers.append(11)
87 | print(mutableNumbers)
88 | // Output: [1, 2, 5, 3, 1, 2, 11]
89 | mutableNumbers.insert(42, at: 4)
90 | print(mutableNumbers)
91 | // Output: [1, 2, 5, 3, 42, 1, 2, 11]
92 |
93 | mutableNumbers.remove(at: 1)
94 | print(mutableNumbers)
95 | // Output: [1, 5, 3, 42, 1, 2, 11]
96 |
97 | mutableNumbers.removeAll()
98 | print(mutableNumbers)
99 | // Output: []
100 |
101 | // removeAll()
102 | mutableNumbers = [1, 2, 5, 3, 1, 2]
103 | mutableNumbers.removeAll()
104 | print("Array count: \(mutableNumbers.count) capacity: \(mutableNumbers.capacity)")
105 | // Output: Array count: 0 capacity: 0
106 |
107 | // removeAll(keepingCapacity: true)
108 | mutableNumbers = [1, 2, 5, 3, 1, 2]
109 | mutableNumbers.removeAll(keepingCapacity: true)
110 | print("Array count: \(mutableNumbers.count) capacity: \(mutableNumbers.capacity)")
111 | // Output: Array count: 0 capacity: 6
112 |
113 | // Commenting out this line will crash the demo: "fatal error: can't remove first element from an empty collection"
114 | // mutableNumbers.removeFirst()
115 |
116 | mutableNumbers = [1, 2, 5, 3, 1, 2]
117 | let wasFirst = mutableNumbers.removeFirst()
118 | print(mutableNumbers)
119 | // Output: [2, 5, 3, 1, 2]
120 |
121 | let wasLast = mutableNumbers.removeLast()
122 | print(mutableNumbers)
123 | // Output: [2, 5, 3, 1]
124 |
125 | //: [Previous: Generic Functions](@previous) | [Next: The Set](@next)
126 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/Pages/The Array.xcplaygroundpage/Sources/ArrayExtension.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | // Array extension for index bounds check
4 | public extension Array where Element == Int {
5 | subscript (safe index: Index) -> Element? {
6 | return indices.contains(index) ? self[index] : nil
7 | }
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/Pages/The Dictionary.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## The Dictionary
9 | //: The Swift Dictionary
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: - Callout(Dictionaries):
19 | //: Key-value pairs
20 | // Specify the key and the value type to create an empty dictionary
21 | var dayOfWeek = Dictionary()
22 |
23 | // Using the initializer syntax
24 | var dayOfWeek2 = [Int: String]()
25 |
26 | // Using dictionary literals
27 | var dayOfWeek3: [Int: String] = [0: "Sun", 1: "Mon", 2: "Tue"]
28 |
29 | // Type inference in action - Swift can infer the type of the keys and the values can based on the dictionary literals
30 | var dayOfWeek4 = [0: "Sun", 1: "Mon", 2: "Tue"]
31 |
32 | print(dayOfWeek4)
33 | // Output: [0: "Sun", 1: "Mon", 2: "Tue"]
34 |
35 | // Type inference won't work if the type of the dictionary literals is not consistent
36 | // var mixedDict = [0: "Zero", 1: 1.0, "pi": 3.14] // Error: Heterogeneous collection literal could only be inferred to '[AnyHashable : Any]'; add explicit
37 | // AnyHashable can be used as the supertype for keys in heterogeneous dictionaries.
38 | var mixedMap3: [AnyHashable: Any] = [0: "Zero", 1: 1.0, "pi": 3.14]
39 |
40 | // We could also define the dictionary by wrapping the key values in AnyHashable instances and by explicitely declaring the values as type Any
41 | var mixedMap4 = [AnyHashable(0): "Zero" as Any,
42 | AnyHashable(1): 1.0 as Any,
43 | AnyHashable("pi"): 3.14 as Any]
44 |
45 | // This is just to illustrate what happens behind the scenes. The shorthand syntax is obviously shorter and more readable.
46 | let piWrapped = AnyHashable("pi")
47 | if let unwrappedPi = piWrapped.base as? String {
48 | print(unwrappedPi)
49 | }
50 | //: - Callout(Access and modify):
51 | //: Change and retrieve the contents of a Dictionary
52 | // Access using the subscript syntax
53 | var dayOfWeekx = [0: "Sun", 1: "Mon", 2: "Tue"]
54 | if let day = dayOfWeekx[2] {
55 | print(day)
56 | }
57 | // Prints: Tue
58 |
59 | // Iterating over the key-value pairs of a dictionary
60 | for (key, value) in dayOfWeek {
61 | print("\(key): \(value)")
62 | }
63 | // Prints: 2: Tue 0: Sun 1: Mon
64 |
65 | // We can also access the Dictionary's key property to retrieve its keys
66 | for key in dayOfWeek.keys {
67 | print(key)
68 | }
69 |
70 | // The dictionary value property will return its values:
71 | for value in dayOfWeek.values {
72 | print(value)
73 | }
74 |
75 | // Add a new value
76 | dayOfWeek[3] = "Wed"
77 | print(dayOfWeek)
78 | // Prints: [2: "Tue", 0: "Sun", 1: "Mon", 3: "Wed"]
79 |
80 | dayOfWeek[2] = "Mardi"
81 | print(dayOfWeek)
82 | // Prints: [2: "Mardi", 0: "Sun", 1: "Mon", 3: "Wed"]
83 |
84 | dayOfWeek.updateValue("Tue", forKey: 2)
85 | print(dayOfWeek)
86 | // Prints: [2: "Tue", 0: "Sun", 1: "Mon", 3: "Wed"]
87 |
88 | // Remove a value by assigning nil for its key
89 | dayOfWeek[1] = nil
90 | print(dayOfWeek)
91 | // Prints: [2: "Tue", 0: "Sun", 3: "Wed"]
92 |
93 | // You can achieve the same - yet with more typing - via the removeValue(forKey:) method
94 | dayOfWeek.removeValue(forKey: 2)
95 | print(dayOfWeek)
96 | // Prints: [0: "Sun", 3: "Wed"]
97 |
98 | // Wipe out the dictionary
99 | dayOfWeek.removeAll()
100 |
101 | print(dayOfWeek)
102 | // Output: [:]
103 |
104 | dayOfWeek = [0: "Zero", 1: "One", 10: "Ten"]
105 | dayOfWeek.removeAll(keepingCapacity: true)
106 |
107 | print("\(dayOfWeek), count: \(dayOfWeek.count) capacity: \(dayOfWeek.capacity)")
108 | // Output: [:], count: 0 capacity: 3
109 |
110 | //: [Previous: Hashable](@previous)
111 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/Pages/The Hashable Protocol.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Hashable
9 | //: We must adopt the Hashable protocol to ensure that the given value is unique.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | struct SimpleStruct: Hashable {
18 | var identifier: String
19 |
20 | // `hashValue` is deprecated as a `Hashable` requirement. To conform to `Hashable`, implement the `hash(into:)` requirement instead.
21 | // Hasher was introduced in Swift 4.2 and it provides a randomly seeded, universal hash function
22 | func hash(into hasher: inout Hasher) {
23 | hasher.combine(identifier)
24 | }
25 |
26 | public static func == (lhs: SimpleStruct, rhs: SimpleStruct) -> Bool {
27 | return lhs.identifier == rhs.identifier
28 | }
29 | }
30 |
31 | var array = [SimpleStruct]()
32 | array.append(SimpleStruct(identifier: "id"))
33 |
34 | var set = Set()
35 | //: [Previous: The Set](@previous) | [Next: The Dictionary](@next)
36 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/Pages/The Set.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## The Set
9 | //: In this tutorial, we'll take a closer look at the Set
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: - Callout(Sets):
19 | //: Unordered sequence of unique elements
20 |
21 | // intialize an empty Set
22 | let numbers = Set()
23 |
24 | // Initialize using array literals
25 | let numbers1: Set = [1, 2, 5, 3]
26 |
27 | // !!! This declares an Array!
28 | let numbers2 = [1, 2, 5, 3] // same as -> let numbers: Array = [1, 2, 5, 3]
29 |
30 | // must specify Set
31 | let numbers3: Set = [1, 2, 5, 3] // type inefrence works out the Int type for its values
32 |
33 | let doubles: Set = [1.5, 2.2, 5] // same as -> let doubles: Set = [1.5, 2.2, 5]
34 |
35 | //: - Callout(Set vs. Array):
36 | //: Let's clarify the main differences between Sets and Arrays
37 |
38 | // 1. Uniqueness of values for Sets
39 | let onesArray: Array = [1, 1, 1, 1]
40 | print(onesArray)
41 | // Output: [1, 1, 1, 1]
42 |
43 | let onesSet: Set = [1, 1, 1, 1]
44 | print(onesSet)
45 | // Output: [1]
46 |
47 | // 2. No defined ordering for elements of a Set
48 | let numbersArray: Array = [1, 2, 3, 4, 5]
49 | print(numbersArray)
50 | // Output: [1, 2, 3, 4, 5]
51 |
52 | let numbersSet: Set = [1, 2, 3, 4, 5]
53 | print(numbersSet)
54 | // Output: undefined order, e.g. [5, 2, 3, 1, 4]
55 | //: - Callout(Traversing the Set):
56 | //: We can iterate over the values in a set
57 | // for-in loop
58 | for value in numbersSet {
59 | print(value)
60 | }
61 | // Output: undefined order, e.g. 5, 2, 3, 1, 4
62 |
63 | // use set.sorted() if you need ordered output
64 | for value in numbers.sorted() {
65 | print(value)
66 | }
67 | // Output: 1, 2, 3, 4, 5
68 |
69 | // forEach
70 | numbers.forEach { value in
71 | print(value)
72 | }
73 | // Output: undefined order, e.g. 5, 2, 3, 1, 4
74 | //: - Callout(Accessing & Modifying the Set):
75 | //: Accessing and modifying the contents of a Set
76 | var mutableStringSet: Set = ["One", "Two", "Three"]
77 | let item = "Two"
78 |
79 | // set.contains()
80 | if mutableStringSet.contains(item) {
81 | print("\(item) found in the set")
82 | } else {
83 | print("\(item) not found in the set")
84 | }
85 | // Output: Two found in the set
86 |
87 | // set.isEmpty
88 | let strings = Set()
89 | if strings.isEmpty {
90 | print("Set is empty")
91 | }
92 | // Output: Set is empty
93 |
94 | // set.count
95 | let emptyStrings = Set()
96 | if emptyStrings.count == 0 {
97 | print("Set has no elements")
98 | }
99 | // Output: Set has no elements
100 |
101 | // set.insert(_:)
102 | mutableStringSet = ["One", "Two", "Three"]
103 | mutableStringSet.insert("Four")
104 |
105 | // set.remoce(_:)
106 | mutableStringSet.remove("Three")
107 |
108 | mutableStringSet = ["One", "Two", "Three"]
109 | if let removedElement = mutableStringSet.remove("Ten") {
110 | print("\(removedElement) was removed from the Set")
111 | } else {
112 | print("\"Ten\" not found in the Set")
113 | }
114 | // Output: "Ten" not found in the Set
115 |
116 | // set.removeAll()
117 | mutableStringSet.removeAll()
118 | // []
119 |
120 | // set.removeAll(keepingCapacity: true)
121 | var numbersSet2: Set = [1, 2, 5, 3, 1, 2]
122 | numbersSet2.removeAll(keepingCapacity: true)
123 | print("count: \(numbersSet2.count) capacity: \(numbersSet2.capacity)")
124 | // count: 0 capacity: 6
125 | //: - Callout(Set Operations):
126 | //: The Set exposes useful methods that let us perform fundamental operations.
127 | let primes: Set = [3, 5, 7, 11]
128 | let odds: Set = [1, 3, 5, 7]
129 |
130 | // set.union(otherSet)
131 | let union = primes.union(odds)
132 | print(union.sorted())
133 | // Output: [1, 3, 5, 7, 11]
134 |
135 | // set.intersection(otherSet)
136 | let intersection = primes.intersection(odds)
137 | print(intersection.sorted())
138 | // Output: [3, 5, 7]
139 |
140 | // set.subtract(otherSet)
141 | let subtract = primes.subtracting(odds)
142 | print(subtract.sorted())
143 | // Output: [11]
144 |
145 | // set.symmetricDifference(otherSet)
146 | let symmetricDiff = primes.symmetricDifference(odds)
147 | print(symmetricDiff.sorted())
148 | // Output: [1, 11]
149 | //: - Callout(Membership and Equality):
150 | //: Other useful Set methods
151 | // ==
152 | if primes == odds {
153 | print("\(primes) and \(odds) contain the same values")
154 | }
155 |
156 | // set.isSubset(of:_)
157 | let odds2: Set = [1, 3, 5]
158 | if odds2.isSubset(of: odds) {
159 | print("\(odds2.sorted()) is subset of \(odds.sorted())")
160 | }
161 | // Output: [1, 3, 5] is subset of [1, 3, 5, 7]
162 |
163 | // set.isSuperset(of:_)
164 | if odds.isSuperset(of: odds2) {
165 | print("\(odds.sorted()) is superset of \(odds2.sorted())")
166 | }
167 | // Output: [1, 3, 5, 7] is superset of [1, 3, 5]
168 |
169 | // set.isDisjoint(with:_)
170 | let primeNumbers: Set = [2, 3, 5]
171 | let otherPrimeNumbers: Set = [11, 13, 17]
172 |
173 | if primeNumbers.isDisjoint(with: otherPrimeNumbers) {
174 | print("\(primeNumbers.sorted()) has no values in common with \(otherPrimeNumbers.sorted())")
175 | }
176 | // Output: [2, 3, 5] has no values in common with [11, 13, 17]
177 |
178 | //: [Previous: The Array](@previous) | [Next: Hashable](@next)
179 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/collections/SwiftCollectionTypes.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/generics/Generics.playground/Pages/Generic Functions.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Generic Functions
9 | //: Create a generic function that compares two values
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: - Callout(A Generic Solution):
19 | //: We create a generic function that can work with any type
20 | func isEqual (left: T, right: T) -> Bool {
21 | return left == right
22 | }
23 |
24 | let stringsEqual = isEqual(left: "Me", right: "You")
25 |
26 | let date = Date()
27 | let datesEqual = isEqual(left: date, right: date)
28 | //: - Callout(Compare custom types):
29 | //: We create a custom Contact struct and use it with our isEqual(left: right:) function
30 | struct Contact: Equatable {
31 | let name: String
32 | let address: String
33 |
34 | init(_ name: String, address: String) {
35 | self.name = name
36 | self.address = address
37 | }
38 |
39 | static func == (lhs: Contact, rhs: Contact) -> Bool {
40 | return lhs.name == rhs.name && lhs.address == rhs.address
41 | }
42 | }
43 |
44 | let oldCampus = Contact("Old Apple Campus", address: "1 Infinite Loop, Cupertino, CA 95014")
45 | let newCampus = Contact("New Apple Campus", address: "19111 Pruneridge Ave, Cupertino, CA 95014")
46 |
47 | print(isEqual(left: oldCampus, right: newCampus))
48 |
49 | //: [Previous: isEqual Without Generics](@previous)
50 |
--------------------------------------------------------------------------------
/generics/Generics.playground/Pages/Generic Types.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Generic Pair Type
9 | //: Create a generic type which can hold pairs of different values.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: - Callout(A Generic Solution):
19 | //: We create one generic type
20 |
21 | struct Pair {
22 | var first: T1
23 | var second: T2
24 | }
25 | //: - Callout(Works with any type):
26 | //: Pair is generic, so we could get rid of all the specific pair types
27 | // Float - Float
28 | let floatFloatPair = Pair(first: 0.3, second: 0.5)
29 | // String - String
30 | let stringAndString = Pair(first: "First String", second: "Second String")
31 | // String - Double
32 | let stringAndDouble = Pair(first: "I'm a String", second: 99.99)
33 | // Int - Date
34 | let intAndDate = Pair(first: 42, second: Date())
35 | //: [Previous: Pair Without Generics](@previous) | [Next: isEqual without Generics](@next)
36 |
--------------------------------------------------------------------------------
/generics/Generics.playground/Pages/Pair Without Generics.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Pair Without Generics - A Naive Approach
9 | //: Create types which hold pairs of different values.
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: - Callout(A Naive Approach):
19 | //: We create dedicated structs for each type pair or combination of types
20 |
21 | // Pair holding two String values
22 | struct StringPair {
23 | var first: String
24 | var second: String
25 | }
26 |
27 | // Pair holding two Int values
28 | struct IntPair {
29 | var first: Int
30 | var second: Int
31 | }
32 |
33 | // Pair with two Float values
34 | struct FloatPair {
35 | var first: Float
36 | var second: Float
37 | }
38 |
39 | // Data Pair
40 | struct DataPair {
41 | var first: Data
42 | var second: Data
43 | }
44 |
45 | // String - Double
46 | struct StringDoublePair {
47 | var first: String
48 | var second: Double
49 | }
50 | //: - Callout(Type Explosion!):
51 | //: We end up having too many types. This is NOT the way to go!
52 | let pair = StringPair(first: "First", second: "Second")
53 | print(pair)
54 |
55 | let numberPair = IntPair(first: 1, second: 2)
56 | print(numberPair)
57 |
58 | let stringDoublePair = StringDoublePair(first: "First", second: 42.5)
59 | print(stringDoublePair)
60 | //: [Next: Generic Types](@next)
61 |
--------------------------------------------------------------------------------
/generics/Generics.playground/Pages/isEqual() Without Generics.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## isEqual() Function Without Generics - A Naive Approach
9 | //: Create a function that compares two values
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | import Foundation
18 | //: - Callout(A Naive Approach):
19 | //: We create a function for each type we compare
20 |
21 | // isEqual() for String
22 | func isEqual(left: String, right: String) -> Bool {
23 | return left == right
24 | }
25 |
26 | // isEqual() for Double
27 | func isEqual(left: Double, right: Double) -> Bool {
28 | return left == right
29 | }
30 |
31 | // isEqual() for Date
32 | func isEqual(left: Date, right: Date) -> Bool {
33 | return left == right
34 | }
35 |
36 | // isEqual() for Data
37 | func isEqual(left: Data, right: Data) -> Bool {
38 | return left == right
39 | }
40 | //: - Callout(Code Repetition!):
41 | //: Avoid code duplication. It is always a bad sign and it leads to bugs and maintenance problems.
42 | let stringsEqual = isEqual(left: "Me", right: "You")
43 |
44 | let date = Date()
45 | let datesEqual = isEqual(left: date, right: date)
46 | //: [Previous: Generic Types](@previous) | [Next: Generic Functions](@next)
47 |
48 |
--------------------------------------------------------------------------------
/generics/Generics.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/generics/Generics.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/Pages/Factorial with BigInt.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Recursive Functions
9 | //: Recursive factorial function with BigInt
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 | typealias BigInt = _BigInt
17 |
18 | /*
19 | Calculate n!
20 | This version works with values above 21.
21 | It relies on the BigInt prototype, which has not yet been released, but it is going to be part of the official Swift library. See https://github.com/apple/swift/blob/master/test/Prototypes/BigInt.swift
22 | */
23 |
24 | func factorial(n: BigInt) -> BigInt {
25 | return n < 2 ? 1 : n * factorial(n: n - 1)
26 | }
27 |
28 | print(UInt64.max)
29 | print(factorial(n: 32))
30 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/Pages/Factorial with BigInt.xcplaygroundpage/Sources/BigInt.swift:
--------------------------------------------------------------------------------
1 | //===--- BigInt.swift -----------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | // RUN: %empty-directory(%t)
14 | // RUN: %target-build-swift -swift-version 4 -o %t/a.out %s
15 | // RUN: %target-run %t/a.out
16 | // REQUIRES: executable_test
17 | // REQUIRES: CPU=x86_64
18 |
19 | // Requires swift-version 4
20 | // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic
21 | #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
22 | import Darwin
23 | #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
24 | import Glibc
25 | #elseif os(Windows)
26 | import MSVCRT
27 | #else
28 | #error("Unsupported platform")
29 | #endif
30 |
31 | extension FixedWidthInteger {
32 | /// Returns the high and low parts of a potentially overflowing addition.
33 | func addingFullWidth(_ other: Self) ->
34 | (high: Self, low: Self) {
35 | let sum = self.addingReportingOverflow(other)
36 | return (sum.overflow ? 1 : 0, sum.partialValue)
37 | }
38 |
39 | /// Returns the high and low parts of two seqeuential potentially overflowing
40 | /// additions.
41 | static func addingFullWidth(_ x: Self, _ y: Self, _ z: Self) ->
42 | (high: Self, low: Self) {
43 | let xy = x.addingReportingOverflow(y)
44 | let xyz = xy.partialValue.addingReportingOverflow(z)
45 | let high: Self = (xy.overflow ? 1 : 0) +
46 | (xyz.overflow ? 1 : 0)
47 | return (high, xyz.partialValue)
48 | }
49 |
50 | /// Returns a tuple containing the value that would be borrowed from a higher
51 | /// place and the partial difference of this value and `rhs`.
52 | func subtractingWithBorrow(_ rhs: Self) ->
53 | (borrow: Self, partialValue: Self) {
54 | let difference = subtractingReportingOverflow(rhs)
55 | return (difference.overflow ? 1 : 0, difference.partialValue)
56 | }
57 |
58 | /// Returns a tuple containing the value that would be borrowed from a higher
59 | /// place and the partial value of `x` and `y` subtracted from this value.
60 | func subtractingWithBorrow(_ x: Self, _ y: Self) ->
61 | (borrow: Self, partialValue: Self) {
62 | let firstDifference = subtractingReportingOverflow(x)
63 | let secondDifference =
64 | firstDifference.partialValue.subtractingReportingOverflow(y)
65 | let borrow: Self = (firstDifference.overflow ? 1 : 0) +
66 | (secondDifference.overflow ? 1 : 0)
67 | return (borrow, secondDifference.partialValue)
68 | }
69 | }
70 |
71 | //===--- BigInt -----------------------------------------------------------===//
72 | //===----------------------------------------------------------------------===//
73 |
74 | /// A dynamically-sized signed integer.
75 | ///
76 | /// The `_BigInt` type is fully generic on the size of its "word" -- the
77 | /// `BigInt` alias uses the system's word-sized `UInt` as its word type, but
78 | /// any word size should work properly.
79 | public struct _BigInt :
80 | BinaryInteger, SignedInteger, CustomStringConvertible,
81 | CustomDebugStringConvertible
82 | where Word.Magnitude == Word
83 | {
84 |
85 | /// The binary representation of the value's magnitude, with the least
86 | /// significant word at index `0`.
87 | ///
88 | /// - `_data` has no trailing zero elements
89 | /// - If `self == 0`, then `isNegative == false` and `_data == []`
90 | internal var _data: [Word] = []
91 |
92 | /// A Boolean value indicating whether this instance is negative.
93 | public private(set) var isNegative = false
94 |
95 | /// A Boolean value indicating whether this instance is equal to zero.
96 | public var isZero: Bool {
97 | return _data.count == 0
98 | }
99 |
100 | //===--- Numeric initializers -------------------------------------------===//
101 |
102 | /// Creates a new instance equal to zero.
103 | public init() { }
104 |
105 | /// Creates a new instance using `_data` as the data collection.
106 | init(_ _data: C) where C.Iterator.Element == Word {
107 | self._data = Array(_data)
108 | _standardize()
109 | }
110 |
111 | public init(integerLiteral value: Int) {
112 | self.init(value)
113 | }
114 |
115 | public init(_ source: T) {
116 | var source = source
117 | if source < 0 as T {
118 | if source.bitWidth <= UInt64.bitWidth {
119 | let sourceMag = Int(truncatingIfNeeded: source).magnitude
120 | self = _BigInt(sourceMag)
121 | self.isNegative = true
122 | return
123 | } else {
124 | // Have to kind of assume that we're working with another BigInt here
125 | self.isNegative = true
126 | source *= -1
127 | }
128 | }
129 |
130 | // FIXME: This is broken on 32-bit arch w/ Word = UInt64
131 | let wordRatio = UInt.bitWidth / Word.bitWidth
132 | assert(wordRatio != 0)
133 | for var sourceWord in source.words {
134 | for _ in 0..>= Word.bitWidth
137 | }
138 | }
139 | _standardize()
140 | }
141 |
142 | public init?(exactly source: T) {
143 | self.init(source)
144 | }
145 |
146 | public init(truncatingIfNeeded source: T) {
147 | self.init(source)
148 | }
149 |
150 | public init(clamping source: T) {
151 | self.init(source)
152 | }
153 |
154 | public init(_ source: T) {
155 | fatalError("Not implemented")
156 | }
157 |
158 | public init?(exactly source: T) {
159 | fatalError("Not implemented")
160 | }
161 |
162 | /// Returns a randomly-generated word.
163 | static func _randomWord() -> Word {
164 | // This handles up to a 64-bit word
165 | if Word.bitWidth > UInt32.bitWidth {
166 | return Word(UInt32.random(in: 0...UInt32.max)) << 32 | Word(UInt32.random(in: 0...UInt32.max))
167 | } else {
168 | return Word(truncatingIfNeeded: UInt32.random(in: 0...UInt32.max))
169 | }
170 | }
171 |
172 | /// Creates a new instance whose magnitude has `randomBits` bits of random
173 | /// data. The sign of the new value is randomly selected.
174 | public init(randomBits: Int) {
175 | let (words, extraBits) =
176 | randomBits.quotientAndRemainder(dividingBy: Word.bitWidth)
177 |
178 | // Get the bits for any full words.
179 | self._data = (0..> 1) == 0
190 |
191 | _standardize()
192 | }
193 |
194 | //===--- Private methods ------------------------------------------------===//
195 |
196 | /// Standardizes this instance after mutation, removing trailing zeros
197 | /// and making sure zero is nonnegative. Calling this method satisfies the
198 | /// two invariants.
199 | mutating func _standardize(source: String = #function) {
200 | defer { _checkInvariants(source: source + " >> _standardize()") }
201 | while _data.last == 0 {
202 | _data.removeLast()
203 | }
204 | // Zero is never negative.
205 | isNegative = isNegative && _data.count != 0
206 | }
207 |
208 | /// Checks and asserts on invariants -- all invariants must be satisfied
209 | /// at the end of every mutating method.
210 | ///
211 | /// - `_data` has no trailing zero elements
212 | /// - If `self == 0`, then `isNegative == false`
213 | func _checkInvariants(source: String = #function) {
214 | if _data.count == 0 {
215 | assert(isNegative == false,
216 | "\(source): isNegative with zero length _data")
217 | }
218 | assert(_data.last != 0, "\(source): extra zeroes on _data")
219 | }
220 |
221 | //===--- Word-based arithmetic ------------------------------------------===//
222 |
223 | mutating func _unsignedAdd(_ rhs: Word) {
224 | defer { _standardize() }
225 |
226 | // Quick return if `rhs == 0`
227 | guard rhs != 0 else { return }
228 |
229 | // Quick return if `self == 0`
230 | if isZero {
231 | _data.append(rhs)
232 | return
233 | }
234 |
235 | // Add `rhs` to the first word, catching any carry.
236 | var carry: Word
237 | (carry, _data[0]) = _data[0].addingFullWidth(rhs)
238 |
239 | // Handle any additional carries
240 | for i in 1..<_data.count {
241 | // No more action needed if there's nothing to carry
242 | if carry == 0 { break }
243 | (carry, _data[i]) = _data[i].addingFullWidth(carry)
244 | }
245 |
246 | // If there's any carry left, add it now
247 | if carry != 0 {
248 | _data.append(1)
249 | }
250 | }
251 |
252 | /// Subtracts `rhs` from this instance, ignoring the sign.
253 | ///
254 | /// - Precondition: `rhs <= self.magnitude`
255 | mutating func _unsignedSubtract(_ rhs: Word) {
256 | precondition(_data.count > 1 || _data[0] > rhs)
257 |
258 | // Quick return if `rhs == 0`
259 | guard rhs != 0 else { return }
260 |
261 | // If `isZero == true`, then `rhs` must also be zero.
262 | precondition(!isZero)
263 |
264 | var carry: Word
265 | (carry, _data[0]) = _data[0].subtractingWithBorrow(rhs)
266 |
267 | for i in 1..<_data.count {
268 | // No more action needed if there's nothing to carry
269 | if carry == 0 { break }
270 | (carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
271 | }
272 | assert(carry == 0)
273 |
274 | _standardize()
275 | }
276 |
277 | /// Adds `rhs` to this instance.
278 | mutating func add(_ rhs: Word) {
279 | if isNegative {
280 | // If _data only contains one word and `rhs` is greater, swap them,
281 | // make self positive and continue with unsigned subtraction.
282 | var rhs = rhs
283 | if _data.count == 1 && _data[0] < rhs {
284 | swap(&rhs, &_data[0])
285 | isNegative = false
286 | }
287 | _unsignedSubtract(rhs)
288 | } else { // positive or zero
289 | _unsignedAdd(rhs)
290 | }
291 | }
292 |
293 | /// Subtracts `rhs` from this instance.
294 | mutating func subtract(_ rhs: Word) {
295 | guard rhs != 0 else { return }
296 |
297 | if isNegative {
298 | _unsignedAdd(rhs)
299 | } else if isZero {
300 | isNegative = true
301 | _data.append(rhs)
302 | } else {
303 | var rhs = rhs
304 | if _data.count == 1 && _data[0] < rhs {
305 | swap(&rhs, &_data[0])
306 | isNegative = true
307 | }
308 | _unsignedSubtract(rhs)
309 | }
310 | }
311 |
312 | /// Multiplies this instance by `rhs`.
313 | mutating func multiply(by rhs: Word) {
314 | // If either `self` or `rhs` is zero, the result is zero.
315 | guard !isZero && rhs != 0 else {
316 | self = 0
317 | return
318 | }
319 |
320 | // If `rhs` is a power of two, can just left shift `self`.
321 | let rhsLSB = rhs.trailingZeroBitCount
322 | if rhs >> rhsLSB == 1 {
323 | self <<= rhsLSB
324 | return
325 | }
326 |
327 | var carry: Word = 0
328 | for i in 0..<_data.count {
329 | let product = _data[i].multipliedFullWidth(by: rhs)
330 | (carry, _data[i]) = product.low.addingFullWidth(carry)
331 | carry = carry &+ product.high
332 | }
333 |
334 | // Add the leftover carry
335 | if carry != 0 {
336 | _data.append(carry)
337 | }
338 | _standardize()
339 | }
340 |
341 | /// Divides this instance by `rhs`, returning the remainder.
342 | @discardableResult
343 | mutating func divide(by rhs: Word) -> Word {
344 | precondition(rhs != 0, "divide by zero")
345 |
346 | // No-op if `rhs == 1` or `self == 0`.
347 | if rhs == 1 || isZero {
348 | return 0
349 | }
350 |
351 | // If `rhs` is a power of two, can just right shift `self`.
352 | let rhsLSB = rhs.trailingZeroBitCount
353 | if rhs >> rhsLSB == 1 {
354 | defer { self >>= rhsLSB }
355 | return _data[0] & ~(~0 << rhsLSB)
356 | }
357 |
358 | var carry: Word = 0
359 | for i in (0..<_data.count).reversed() {
360 | let lhs = (high: carry, low: _data[i])
361 | (_data[i], carry) = rhs.dividingFullWidth(lhs)
362 | }
363 |
364 | _standardize()
365 | return carry
366 | }
367 |
368 | //===--- Numeric --------------------------------------------------------===//
369 |
370 | public typealias Magnitude = _BigInt
371 |
372 | public var magnitude: _BigInt {
373 | var result = self
374 | result.isNegative = false
375 | return result
376 | }
377 |
378 | /// Adds `rhs` to this instance, ignoring any signs.
379 | mutating func _unsignedAdd(_ rhs: _BigInt) {
380 | defer { _checkInvariants() }
381 |
382 | let commonCount = Swift.min(_data.count, rhs._data.count)
383 | let maxCount = Swift.max(_data.count, rhs._data.count)
384 | _data.reserveCapacity(maxCount)
385 |
386 | // Add the words up to the common count, carrying any overflows
387 | var carry: Word = 0
388 | for i in 0.. rhs._data.count {
394 | for i in commonCount.. rhs._data.count
486 | ? (lhs._data, rhs._data)
487 | : (rhs._data, lhs._data)
488 | assert(a.count >= b.count)
489 |
490 | var carry: Word = 0
491 | for ai in 0.. _BigInt {
542 | precondition(!rhs.isZero, "Divided by zero")
543 | defer { _checkInvariants() }
544 |
545 | // Handle quick cases that don't require division:
546 | // If `abs(self) < abs(rhs)`, the result is zero, remainder = self
547 | // If `abs(self) == abs(rhs)`, the result is 1 or -1, remainder = 0
548 | switch _compareMagnitude(to: rhs) {
549 | case .lessThan:
550 | defer { self = 0 }
551 | return self
552 | case .equal:
553 | self = isNegative != rhs.isNegative ? -1 : 1
554 | return 0
555 | default:
556 | break
557 | }
558 |
559 | var tempSelf = self.magnitude
560 | let n = tempSelf.bitWidth - rhs.magnitude.bitWidth
561 | var quotient: _BigInt = 0
562 | var tempRHS = rhs.magnitude << n
563 | var tempQuotient: _BigInt = 1 << n
564 |
565 | for _ in (0...n).reversed() {
566 | if tempRHS._compareMagnitude(to: tempSelf) != .greaterThan {
567 | tempSelf -= tempRHS
568 | quotient += tempQuotient
569 | }
570 | tempRHS >>= 1
571 | tempQuotient >>= 1
572 | }
573 |
574 | // `tempSelf` is the remainder - match sign of original `self`
575 | tempSelf.isNegative = self.isNegative
576 | tempSelf._standardize()
577 |
578 | quotient.isNegative = isNegative != rhs.isNegative
579 | self = quotient
580 | _standardize()
581 |
582 | return tempSelf
583 | }
584 |
585 | public static func /=(lhs: inout _BigInt, rhs: _BigInt) {
586 | lhs._internalDivide(by: rhs)
587 | }
588 |
589 | // FIXME: Remove once default implementations are provided:
590 |
591 | public static func +(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
592 | var lhs = lhs
593 | lhs += rhs
594 | return lhs
595 | }
596 |
597 | public static func -(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
598 | var lhs = lhs
599 | lhs -= rhs
600 | return lhs
601 | }
602 |
603 | public static func *(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
604 | var lhs = lhs
605 | lhs *= rhs
606 | return lhs
607 | }
608 |
609 | public static func /(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
610 | var lhs = lhs
611 | lhs /= rhs
612 | return lhs
613 | }
614 |
615 | public static func %(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
616 | var lhs = lhs
617 | lhs %= rhs
618 | return lhs
619 | }
620 |
621 | //===--- BinaryInteger --------------------------------------------------===//
622 |
623 | /// Creates a new instance using the given data array in two's complement
624 | /// representation.
625 | init(_twosComplementData: [Word]) {
626 | guard _twosComplementData.count > 0 else {
627 | self = 0
628 | return
629 | }
630 |
631 | // Is the highest bit set?
632 | isNegative = _twosComplementData.last!.leadingZeroBitCount == 0
633 | if isNegative {
634 | _data = _twosComplementData.map(~)
635 | self._unsignedAdd(1 as Word)
636 | } else {
637 | _data = _twosComplementData
638 | }
639 | _standardize()
640 | }
641 |
642 | /// Returns an array of the value's data using two's complement representation.
643 | func _dataAsTwosComplement() -> [Word] {
644 | // Special cases:
645 | // * Nonnegative values are already in 2's complement
646 | if !isNegative {
647 | // Positive values need to have a leading zero bit
648 | if _data.last?.leadingZeroBitCount == 0 {
649 | return _data + [0]
650 | } else {
651 | return _data
652 | }
653 | }
654 | // * -1 will get zeroed out below, easier to handle here
655 | if _data.count == 1 && _data.first == 1 { return [~0] }
656 |
657 | var x = self
658 | x._unsignedSubtract(1 as Word)
659 |
660 | if x._data.last!.leadingZeroBitCount == 0 {
661 | // The highest bit is set to 1, which moves to 0 after negation.
662 | // We need to add another word at the high end so the highest bit is 1.
663 | return x._data.map(~) + [Word.max]
664 | } else {
665 | // The highest bit is set to 0, which moves to 1 after negation.
666 | return x._data.map(~)
667 | }
668 | }
669 |
670 | public var words: [UInt] {
671 | assert(UInt.bitWidth % Word.bitWidth == 0)
672 | let twosComplementData = _dataAsTwosComplement()
673 | var words: [UInt] = []
674 | words.reserveCapacity((twosComplementData.count * Word.bitWidth
675 | + UInt.bitWidth - 1) / UInt.bitWidth)
676 | var word: UInt = 0
677 | var shift = 0
678 | for w in twosComplementData {
679 | word |= UInt(truncatingIfNeeded: w) << shift
680 | shift += Word.bitWidth
681 | if shift == UInt.bitWidth {
682 | words.append(word)
683 | word = 0
684 | shift = 0
685 | }
686 | }
687 | if shift != 0 {
688 | if isNegative {
689 | word |= ~((1 << shift) - 1)
690 | }
691 | words.append(word)
692 | }
693 | return words
694 | }
695 |
696 | /// The number of bits used for storage of this value. Always a multiple of
697 | /// `Word.bitWidth`.
698 | public var bitWidth: Int {
699 | if isZero {
700 | return 0
701 | } else {
702 | let twosComplementData = _dataAsTwosComplement()
703 |
704 | // If negative, it's okay to have 1s padded on high end
705 | if isNegative {
706 | return twosComplementData.count * Word.bitWidth
707 | }
708 |
709 | // If positive, need to make space for at least one zero on high end
710 | return twosComplementData.count * Word.bitWidth
711 | - twosComplementData.last!.leadingZeroBitCount + 1
712 | }
713 | }
714 |
715 | /// The number of sequential zeros in the least-significant position of this
716 | /// value's binary representation.
717 | ///
718 | /// The numbers 1 and zero have zero trailing zeros.
719 | public var trailingZeroBitCount: Int {
720 | guard !isZero else {
721 | return 0
722 | }
723 |
724 | let i = _data.firstIndex(where: { $0 != 0 })!
725 | assert(_data[i] != 0)
726 | return i * Word.bitWidth + _data[i].trailingZeroBitCount
727 | }
728 |
729 | public static func %=(lhs: inout _BigInt, rhs: _BigInt) {
730 | defer { lhs._checkInvariants() }
731 | lhs = lhs._internalDivide(by: rhs)
732 | }
733 |
734 | public func quotientAndRemainder(dividingBy rhs: _BigInt) ->
735 | (_BigInt, _BigInt)
736 | {
737 | var x = self
738 | let r = x._internalDivide(by: rhs)
739 | return (x, r)
740 | }
741 |
742 | public static func &=(lhs: inout _BigInt, rhs: _BigInt) {
743 | var lhsTemp = lhs._dataAsTwosComplement()
744 | let rhsTemp = rhs._dataAsTwosComplement()
745 |
746 | // If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
747 | // * If `rhs < 0`, length is extended with 1s
748 | // * If `rhs >= 0`, length is extended with 0s, which crops `lhsTemp`
749 | if lhsTemp.count > rhsTemp.count && !rhs.isNegative {
750 | lhsTemp.removeLast(lhsTemp.count - rhsTemp.count)
751 | }
752 |
753 | // If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
754 | // * If `lhs < 0`, length is extended with 1s, so `lhs` should get extra
755 | // bits from `rhs`
756 | // * If `lhs >= 0`, length is extended with 0s
757 | if lhsTemp.count < rhsTemp.count && lhs.isNegative {
758 | lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..= 0`, length is extended with 0s, which is a no-op
777 | if lhsTemp.count > rhsTemp.count && rhs.isNegative {
778 | lhsTemp.replaceSubrange(rhsTemp.count..= 0`, length is extended with 0s, so those bits should be
786 | // copied from rhs
787 | if lhsTemp.count < rhsTemp.count {
788 | if lhs.isNegative {
789 | lhsTemp.append(contentsOf:
790 | repeatElement(Word.max, count: rhsTemp.count - lhsTemp.count))
791 | } else {
792 | lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..= 0`, length is extended with 0s, which is a no-op
812 | if lhsTemp.count > rhsTemp.count && rhs.isNegative {
813 | for i in rhsTemp.count..= 0`, length is extended with 0s, so those bits should
822 | // be copied from rhs
823 | if lhsTemp.count < rhsTemp.count {
824 | if lhs.isNegative {
825 | lhsTemp += rhsTemp.suffix(from: lhsTemp.count).map(~)
826 | } else {
827 | lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count.. _BigInt {
840 | return -x - 1
841 | }
842 |
843 | //===--- SignedNumeric --------------------------------------------------===//
844 |
845 | public static prefix func -(x: inout _BigInt) {
846 | defer { x._checkInvariants() }
847 | guard x._data.count > 0 else { return }
848 | x.isNegative = !x.isNegative
849 | }
850 |
851 | //===--- Strideable -----------------------------------------------------===//
852 |
853 | public func distance(to other: _BigInt) -> _BigInt {
854 | return other - self
855 | }
856 |
857 | public func advanced(by n: _BigInt) -> _BigInt {
858 | return self + n
859 | }
860 |
861 | //===--- Other arithmetic -----------------------------------------------===//
862 |
863 | /// Returns the greatest common divisor for this value and `other`.
864 | public func greatestCommonDivisor(with other: _BigInt) -> _BigInt {
865 | // Quick return if either is zero
866 | if other.isZero {
867 | return magnitude
868 | }
869 | if isZero {
870 | return other.magnitude
871 | }
872 |
873 | var (x, y) = (self.magnitude, other.magnitude)
874 | let (xLSB, yLSB) = (x.trailingZeroBitCount, y.trailingZeroBitCount)
875 |
876 | // Remove any common factor of two
877 | let commonPower = Swift.min(xLSB, yLSB)
878 | x >>= commonPower
879 | y >>= commonPower
880 |
881 | // Remove any remaining factor of two
882 | if xLSB != commonPower {
883 | x >>= xLSB - commonPower
884 | }
885 | if yLSB != commonPower {
886 | y >>= yLSB - commonPower
887 | }
888 |
889 | while !x.isZero {
890 | // Swap values to ensure that `x >= y`.
891 | if x._compareMagnitude(to: y) == .lessThan {
892 | swap(&x, &y)
893 | }
894 |
895 | // Subtract smaller and remove any factors of two
896 | x._unsignedSubtract(y)
897 | x >>= x.trailingZeroBitCount
898 | }
899 |
900 | // Add original common factor of two back into result
901 | y <<= commonPower
902 | return y
903 | }
904 |
905 | /// Returns the lowest common multiple for this value and `other`.
906 | public func lowestCommonMultiple(with other: _BigInt) -> _BigInt {
907 | let gcd = greatestCommonDivisor(with: other)
908 | if _compareMagnitude(to: other) == .lessThan {
909 | return ((self / gcd) * other).magnitude
910 | } else {
911 | return ((other / gcd) * self).magnitude
912 | }
913 | }
914 |
915 | //===--- String methods ------------------------------------------------===//
916 |
917 | /// Creates a new instance from the given string.
918 | ///
919 | /// - Parameters:
920 | /// - source: The string to parse for the new instance's value. If a
921 | /// character in `source` is not in the range `0...9` or `a...z`, case
922 | /// insensitive, or is not less than `radix`, the result is `nil`.
923 | /// - radix: The radix to use when parsing `source`. `radix` must be in the
924 | /// range `2...36`. The default is `10`.
925 | public init?(_ source: String, radix: Int = 10) {
926 | assert(2...36 ~= radix, "radix must be in range 2...36")
927 | let radix = Word(radix)
928 |
929 | func valueForCodeUnit(_ unit: Unicode.UTF16.CodeUnit) -> Word? {
930 | switch unit {
931 | // "0"..."9"
932 | case 48...57: return Word(unit - 48)
933 | // "a"..."z"
934 | case 97...122: return Word(unit - 87)
935 | // "A"..."Z"
936 | case 65...90: return Word(unit - 55)
937 | // invalid character
938 | default: return nil
939 | }
940 | }
941 |
942 | var source = source
943 |
944 | // Check for a single prefixing hyphen
945 | let negative = source.hasPrefix("-")
946 | if negative {
947 | source = String(source.dropFirst())
948 | }
949 |
950 | // Loop through characters, multiplying
951 | for v in source.utf16.map(valueForCodeUnit) {
952 | // Character must be valid and less than radix
953 | guard let v = v else { return nil }
954 | guard v < radix else { return nil }
955 |
956 | self.multiply(by: radix)
957 | self.add(v)
958 | }
959 |
960 | self.isNegative = negative
961 | }
962 |
963 | /// Returns a string representation of this instance.
964 | ///
965 | /// - Parameters:
966 | /// - radix: The radix to use when converting this instance to a string.
967 | /// The value passed as `radix` must be in the range `2...36`. The
968 | /// default is `10`.
969 | /// - lowercase: Whether to use lowercase letters to represent digits
970 | /// greater than 10. The default is `true`.
971 | public func toString(radix: Int = 10, lowercase: Bool = true) -> String {
972 | assert(2...36 ~= radix, "radix must be in range 2...36")
973 |
974 | let digitsStart = ("0" as Unicode.Scalar).value
975 | let lettersStart = ((lowercase ? "a" : "A") as Unicode.Scalar).value - 10
976 | func toLetter(_ x: UInt32) -> Unicode.Scalar {
977 | return x < 10
978 | ? Unicode.Scalar(digitsStart + x)!
979 | : Unicode.Scalar(lettersStart + x)!
980 | }
981 |
982 | let radix = _BigInt(radix)
983 | var result: [Unicode.Scalar] = []
984 |
985 | var x = self.magnitude
986 | while !x.isZero {
987 | let remainder: _BigInt
988 | (x, remainder) = x.quotientAndRemainder(dividingBy: radix)
989 | result.append(toLetter(UInt32(remainder)))
990 | }
991 |
992 | let sign = isNegative ? "-" : ""
993 | let rest = result.count == 0
994 | ? "0"
995 | : String(String.UnicodeScalarView(result.reversed()))
996 | return sign + rest
997 | }
998 |
999 | public var description: String {
1000 | return decimalString
1001 | }
1002 |
1003 | public var debugDescription: String {
1004 | return "_BigInt(\(hexString), words: \(_data.count))"
1005 | }
1006 |
1007 | /// A string representation of this instance's value in base 2.
1008 | public var binaryString: String {
1009 | return toString(radix: 2)
1010 | }
1011 |
1012 | /// A string representation of this instance's value in base 10.
1013 | public var decimalString: String {
1014 | return toString(radix: 10)
1015 | }
1016 |
1017 | /// A string representation of this instance's value in base 16.
1018 | public var hexString: String {
1019 | return toString(radix: 16, lowercase: false)
1020 | }
1021 |
1022 | /// A string representation of this instance's value in base 36.
1023 | public var compactString: String {
1024 | return toString(radix: 36, lowercase: false)
1025 | }
1026 |
1027 | //===--- Comparable -----------------------------------------------------===//
1028 |
1029 | enum _ComparisonResult {
1030 | case lessThan, equal, greaterThan
1031 | }
1032 |
1033 | /// Returns whether this instance is less than, greather than, or equal to
1034 | /// the given value.
1035 | func _compare(to rhs: _BigInt) -> _ComparisonResult {
1036 | // Negative values are less than positive values
1037 | guard isNegative == rhs.isNegative else {
1038 | return isNegative ? .lessThan : .greaterThan
1039 | }
1040 |
1041 | switch _compareMagnitude(to: rhs) {
1042 | case .equal:
1043 | return .equal
1044 | case .lessThan:
1045 | return isNegative ? .greaterThan : .lessThan
1046 | case .greaterThan:
1047 | return isNegative ? .lessThan : .greaterThan
1048 | }
1049 | }
1050 |
1051 | /// Returns whether the magnitude of this instance is less than, greather
1052 | /// than, or equal to the magnitude of the given value.
1053 | func _compareMagnitude(to rhs: _BigInt) -> _ComparisonResult {
1054 | guard _data.count == rhs._data.count else {
1055 | return _data.count < rhs._data.count ? .lessThan : .greaterThan
1056 | }
1057 |
1058 | // Equal number of words: compare from most significant word
1059 | for i in (0..<_data.count).reversed() {
1060 | if _data[i] < rhs._data[i] { return .lessThan }
1061 | if _data[i] > rhs._data[i] { return .greaterThan }
1062 | }
1063 | return .equal
1064 | }
1065 |
1066 | public static func ==(lhs: _BigInt, rhs: _BigInt) -> Bool {
1067 | return lhs._compare(to: rhs) == .equal
1068 | }
1069 |
1070 | public static func < (lhs: _BigInt, rhs: _BigInt) -> Bool {
1071 | return lhs._compare(to: rhs) == .lessThan
1072 | }
1073 |
1074 | //===--- Hashable -------------------------------------------------------===//
1075 |
1076 | public func hash(into hasher: inout Hasher) {
1077 | hasher.combine(isNegative)
1078 | hasher.combine(_data)
1079 | }
1080 |
1081 | //===--- Bit shifting operators -----------------------------------------===//
1082 |
1083 | static func _shiftLeft(_ data: inout [Word], byWords words: Int) {
1084 | guard words > 0 else { return }
1085 | data.insert(contentsOf: repeatElement(0, count: words), at: 0)
1086 | }
1087 |
1088 | static func _shiftRight(_ data: inout [Word], byWords words: Int) {
1089 | guard words > 0 else { return }
1090 | data.removeFirst(Swift.min(data.count, words))
1091 | }
1092 |
1093 | public static func <<= (lhs: inout _BigInt, rhs: RHS) {
1094 | defer { lhs._checkInvariants() }
1095 | guard rhs != 0 else { return }
1096 | guard rhs > 0 else {
1097 | lhs >>= 0 - rhs
1098 | return
1099 | }
1100 |
1101 | let wordWidth = RHS(Word.bitWidth)
1102 |
1103 | // We can add `rhs / bits` extra words full of zero at the low end.
1104 | let extraWords = Int(rhs / wordWidth)
1105 | lhs._data.reserveCapacity(lhs._data.count + extraWords + 1)
1106 | _BigInt._shiftLeft(&lhs._data, byWords: extraWords)
1107 |
1108 | // Each existing word will need to be shifted left by `rhs % bits`.
1109 | // For each pair of words, we'll use the high `offset` bits of the
1110 | // lower word and the low `Word.bitWidth - offset` bits of the higher
1111 | // word.
1112 | let highOffset = Int(rhs % wordWidth)
1113 | let lowOffset = Word.bitWidth - highOffset
1114 |
1115 | // If there's no offset, we're finished, as `rhs` was a multiple of
1116 | // `Word.bitWidth`.
1117 | guard highOffset != 0 else { return }
1118 |
1119 | // Add new word at the end, then shift everything left by `offset` bits.
1120 | lhs._data.append(0)
1121 | for i in ((extraWords + 1)..> lowOffset
1124 | }
1125 |
1126 | // Finally, shift the lowest word.
1127 | lhs._data[extraWords] = lhs._data[extraWords] << highOffset
1128 | lhs._standardize()
1129 | }
1130 |
1131 | public static func >>= (lhs: inout _BigInt, rhs: RHS) {
1132 | defer { lhs._checkInvariants() }
1133 | guard rhs != 0 else { return }
1134 | guard rhs > 0 else {
1135 | lhs <<= 0 - rhs
1136 | return
1137 | }
1138 |
1139 | var tempData = lhs._dataAsTwosComplement()
1140 |
1141 | let wordWidth = RHS(Word.bitWidth)
1142 | // We can remove `rhs / bits` full words at the low end.
1143 | // If that removes the entirety of `_data`, we're done.
1144 | let wordsToRemove = Int(rhs / wordWidth)
1145 | _BigInt._shiftRight(&tempData, byWords: wordsToRemove)
1146 | guard tempData.count != 0 else {
1147 | lhs = lhs.isNegative ? -1 : 0
1148 | return
1149 | }
1150 |
1151 | // Each existing word will need to be shifted right by `rhs % bits`.
1152 | // For each pair of words, we'll use the low `offset` bits of the
1153 | // higher word and the high `_BigInt.Word.bitWidth - offset` bits of
1154 | // the lower word.
1155 | let lowOffset = Int(rhs % wordWidth)
1156 | let highOffset = Word.bitWidth - lowOffset
1157 |
1158 | // If there's no offset, we're finished, as `rhs` was a multiple of
1159 | // `Word.bitWidth`.
1160 | guard lowOffset != 0 else {
1161 | lhs = _BigInt(_twosComplementData: tempData)
1162 | return
1163 | }
1164 |
1165 | // Shift everything right by `offset` bits.
1166 | for i in 0..<(tempData.count - 1) {
1167 | tempData[i] = tempData[i] >> lowOffset |
1168 | tempData[i + 1] << highOffset
1169 | }
1170 |
1171 | // Finally, shift the highest word and standardize the result.
1172 | tempData[tempData.count - 1] >>= lowOffset
1173 | lhs = _BigInt(_twosComplementData: tempData)
1174 | }
1175 | }
1176 |
1177 | //===--- Bit --------------------------------------------------------------===//
1178 | //===----------------------------------------------------------------------===//
1179 |
1180 | /// A one-bit fixed width integer.
1181 | struct Bit : FixedWidthInteger, UnsignedInteger {
1182 | typealias Magnitude = Bit
1183 |
1184 | var value: UInt8 = 0
1185 |
1186 | // Initializers
1187 |
1188 | init(integerLiteral value: Int) {
1189 | self = Bit(value)
1190 | }
1191 |
1192 | init(bigEndian value: Bit) {
1193 | self = value
1194 | }
1195 |
1196 | init(littleEndian value: Bit) {
1197 | self = value
1198 | }
1199 |
1200 | init?(exactly source: T) {
1201 | switch source {
1202 | case T(0): value = 0
1203 | case T(1): value = 1
1204 | default:
1205 | return nil
1206 | }
1207 | }
1208 |
1209 | init(_ source: T) {
1210 | self = Bit(exactly: source.rounded(.down))!
1211 | }
1212 |
1213 | init(_ source: T) {
1214 | switch source {
1215 | case 0: value = 0
1216 | case 1: value = 1
1217 | default:
1218 | fatalError("Can't represent \(source) as a Bit")
1219 | }
1220 | }
1221 |
1222 | init(truncatingIfNeeded source: T) {
1223 | value = UInt8(source & 1)
1224 | }
1225 |
1226 | init(_truncatingBits bits: UInt) {
1227 | value = UInt8(bits & 1)
1228 | }
1229 |
1230 | init(clamping source: T) {
1231 | value = source >= 1 ? 1 : 0
1232 | }
1233 |
1234 | // FixedWidthInteger, BinaryInteger
1235 |
1236 | static var bitWidth: Int {
1237 | return 1
1238 | }
1239 |
1240 | var bitWidth: Int {
1241 | return 1
1242 | }
1243 |
1244 | var trailingZeroBitCount: Int {
1245 | return Int(~value & 1)
1246 | }
1247 |
1248 | static var max: Bit {
1249 | return 1
1250 | }
1251 |
1252 | static var min: Bit {
1253 | return 0
1254 | }
1255 |
1256 | static var isSigned: Bool {
1257 | return false
1258 | }
1259 |
1260 | var nonzeroBitCount: Int {
1261 | return value.nonzeroBitCount
1262 | }
1263 |
1264 | var leadingZeroBitCount: Int {
1265 | return Int(~value & 1)
1266 | }
1267 |
1268 | var bigEndian: Bit {
1269 | return self
1270 | }
1271 |
1272 | var littleEndian: Bit {
1273 | return self
1274 | }
1275 |
1276 | var byteSwapped: Bit {
1277 | return self
1278 | }
1279 |
1280 | var words: UInt.Words {
1281 | return UInt(value).words
1282 | }
1283 |
1284 | // Hashable, CustomStringConvertible
1285 |
1286 | func hash(into hasher: inout Hasher) {
1287 | hasher.combine(value)
1288 | }
1289 |
1290 | var description: String {
1291 | return "\(value)"
1292 | }
1293 |
1294 | // Arithmetic Operations / Operators
1295 |
1296 | func _checkOverflow(_ v: UInt8) -> Bool {
1297 | let mask: UInt8 = ~0 << 1
1298 | return v & mask != 0
1299 | }
1300 |
1301 | func addingReportingOverflow(_ rhs: Bit) ->
1302 | (partialValue: Bit, overflow: Bool) {
1303 | let result = value &+ rhs.value
1304 | return (Bit(result & 1), _checkOverflow(result))
1305 | }
1306 |
1307 | func subtractingReportingOverflow(_ rhs: Bit) ->
1308 | (partialValue: Bit, overflow: Bool) {
1309 | let result = value &- rhs.value
1310 | return (Bit(result & 1), _checkOverflow(result))
1311 | }
1312 |
1313 | func multipliedReportingOverflow(by rhs: Bit) ->
1314 | (partialValue: Bit, overflow: Bool) {
1315 | let result = value &* rhs.value
1316 | return (Bit(result), false)
1317 | }
1318 |
1319 | func dividedReportingOverflow(by rhs: Bit) ->
1320 | (partialValue: Bit, overflow: Bool) {
1321 | return (self, rhs != 0)
1322 | }
1323 |
1324 | func remainderReportingOverflow(dividingBy rhs: Bit) ->
1325 | (partialValue: Bit, overflow: Bool) {
1326 | fatalError()
1327 | }
1328 |
1329 | static func +=(lhs: inout Bit, rhs: Bit) {
1330 | let result = lhs.addingReportingOverflow(rhs)
1331 | assert(!result.overflow, "Addition overflow")
1332 | lhs = result.partialValue
1333 | }
1334 |
1335 | static func -=(lhs: inout Bit, rhs: Bit) {
1336 | let result = lhs.subtractingReportingOverflow(rhs)
1337 | assert(!result.overflow, "Subtraction overflow")
1338 | lhs = result.partialValue
1339 | }
1340 |
1341 | static func *=(lhs: inout Bit, rhs: Bit) {
1342 | let result = lhs.multipliedReportingOverflow(by: rhs)
1343 | assert(!result.overflow, "Multiplication overflow")
1344 | lhs = result.partialValue
1345 | }
1346 |
1347 | static func /=(lhs: inout Bit, rhs: Bit) {
1348 | let result = lhs.dividedReportingOverflow(by: rhs)
1349 | assert(!result.overflow, "Division overflow")
1350 | lhs = result.partialValue
1351 | }
1352 |
1353 | static func %=(lhs: inout Bit, rhs: Bit) {
1354 | assert(rhs != 0, "Modulo sum overflow")
1355 | lhs.value = 0 // No remainders with bit division!
1356 | }
1357 |
1358 | func multipliedFullWidth(by other: Bit) -> (high: Bit, low: Bit) {
1359 | return (0, self * other)
1360 | }
1361 |
1362 | func dividingFullWidth(_ dividend: (high: Bit, low: Bit)) ->
1363 | (quotient: Bit, remainder: Bit) {
1364 | assert(self != 0, "Division overflow")
1365 | assert(dividend.high == 0, "Quotient overflow")
1366 | return (dividend.low, 0)
1367 | }
1368 |
1369 | // FIXME: Remove once default implementations are provided:
1370 |
1371 | public static func +(_ lhs: Bit, _ rhs: Bit) -> Bit {
1372 | var lhs = lhs
1373 | lhs += rhs
1374 | return lhs
1375 | }
1376 |
1377 | public static func -(_ lhs: Bit, _ rhs: Bit) -> Bit {
1378 | var lhs = lhs
1379 | lhs -= rhs
1380 | return lhs
1381 | }
1382 |
1383 | public static func *(_ lhs: Bit, _ rhs: Bit) -> Bit {
1384 | var lhs = lhs
1385 | lhs *= rhs
1386 | return lhs
1387 | }
1388 |
1389 | public static func /(_ lhs: Bit, _ rhs: Bit) -> Bit {
1390 | var lhs = lhs
1391 | lhs /= rhs
1392 | return lhs
1393 | }
1394 |
1395 | public static func %(_ lhs: Bit, _ rhs: Bit) -> Bit {
1396 | var lhs = lhs
1397 | lhs %= rhs
1398 | return lhs
1399 | }
1400 |
1401 | // Bitwise operators
1402 |
1403 | static prefix func ~(x: Bit) -> Bit {
1404 | return Bit(~x.value & 1)
1405 | }
1406 |
1407 | // Why doesn't the type checker complain about these being missing?
1408 | static func &=(lhs: inout Bit, rhs: Bit) {
1409 | lhs.value &= rhs.value
1410 | }
1411 |
1412 | static func |=(lhs: inout Bit, rhs: Bit) {
1413 | lhs.value |= rhs.value
1414 | }
1415 |
1416 | static func ^=(lhs: inout Bit, rhs: Bit) {
1417 | lhs.value ^= rhs.value
1418 | }
1419 |
1420 | static func ==(lhs: Bit, rhs: Bit) -> Bool {
1421 | return lhs.value == rhs.value
1422 | }
1423 |
1424 | static func <(lhs: Bit, rhs: Bit) -> Bool {
1425 | return lhs.value < rhs.value
1426 | }
1427 |
1428 | static func <<(lhs: Bit, rhs: Bit) -> Bit {
1429 | return rhs == 0 ? lhs : 0
1430 | }
1431 |
1432 | static func >>(lhs: Bit, rhs: Bit) -> Bit {
1433 | return rhs == 0 ? lhs : 0
1434 | }
1435 |
1436 | static func <<=(lhs: inout Bit, rhs: Bit) {
1437 | if rhs != 0 {
1438 | lhs = 0
1439 | }
1440 | }
1441 |
1442 | static func >>=(lhs: inout Bit, rhs: Bit) {
1443 | if rhs != 0 {
1444 | lhs = 0
1445 | }
1446 | }
1447 | }
1448 |
1449 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/Pages/Factorial.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Recursive Functions
9 | //: Recursive factorial function
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | /*
18 | Calculate n!
19 | This version works with values below 21.
20 | The biggest number we can represent using UInt64 is 18446744073709551615. And 21! is bigger than that.
21 | */
22 | func factorial(n: UInt64) -> UInt64 {
23 | return n < 2 ? 1 : n * factorial(n: n - 1)
24 | }
25 |
26 | print(UInt64.max)
27 | print(factorial(n: 20))
28 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/Pages/Infinite Recursion.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Recursive Functions
9 | //: Infinite recursion example
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 | /*
17 | I implement a function which calculates the sum of the first n positive integers.
18 | I call the function badSum, to make it clear that it's not the right approach to solve this problem. I'll show you the right solution that relies on a simple formula in an upcoming lesson.
19 | */
20 | //: - Callout(Infinite Loop!):
21 | //: Just for demonstration purposes, *don't* use it in real code!
22 | func badSum(n: Int) -> Int {
23 | if n <= 0 {
24 | return 0
25 | }
26 | guard n > 0 else {
27 | return 0
28 | }
29 |
30 | //print(n)
31 | return n + badSum(n: (n - 1))
32 | }
33 |
34 | let res = badSum(n: 3)
35 | print(res)
36 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/Pages/Node.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | //: **Introduction to Algorithms and Data Structures in Swift 5** - Source Code
2 | //:
3 | //: Get the course **[on Udemy using this discounted coupon](https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=BESTPRICE)**
4 | //:
5 | //: The book version is available **[on iTunes](http://itunes.apple.com/us/book/id1345964250)** and **[Amazon](https://www.amazon.com/Introduction-Algorithms-Data-Structures-Swift-ebook/dp/B077D8MQ31)**
6 | //:
7 | //: _ _ _
8 | //: ## Recursive Data Structures
9 | //: Recursive Node class
10 | //:
11 | //: - Callout(Interested in Swift programming?):
12 | //: Check out my **[Youtube channel](https://www.youtube.com/c/swiftprogrammingtutorials)**
13 | //: my courses on **[Udemy](https://www.udemy.com/user/karolynyisztor/)**, **[Lynda](https://www.lynda.com/Karoly-Nyisztor/9655357-1.html)** and **[Pluralsight](https://www.pluralsight.com/profile/author/karoly-nyisztor)**.
14 | //: Website **[www.leakka.com](http://www.leakka.com)**
15 | //: ---
16 |
17 | // A simple Node class. Each Node can link to the next node through the next property.
18 | class Node {
19 | var next: Node?
20 | var value: String
21 |
22 | init(value: String) {
23 | self.value = value
24 | }
25 | }
26 |
27 |
28 | // Now that we have our Node type, let's build a linked list.
29 | let node1 = Node(value: "node1")
30 | let node2 = Node(value: "node2")
31 | node1.next = node2
32 | let node3 = Node(value: "node3")
33 | node2.next = node3
34 | node3.next = nil
35 |
36 | // Traverses the linked list and prints the value in each node.
37 | func parseNodes(from node: Node?) {
38 | guard let validNode = node else {
39 | return
40 | }
41 | print(validNode.value)
42 | parseNodes(from: validNode.next)
43 | }
44 |
45 | parseNodes(from: node1)
46 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/Pages/Node.xcplaygroundpage/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/recursion/Recursion.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------