31,19 €
C# is a multi-paradigm programming language. The Modern C# Challenge covers with aspects of the .NET Framework such as the Task Parallel Library (TPL) and CryptoAPI. It also encourages you to explore important programming trade-offs such as time versus space or simplicity. There may be many ways to solve a problem and there is often no single right way, but some solutions are definitely better than others. This book has combined these solutions to help you solve real-world problems with C#.
In addition to describing programming trade-offs, The Modern C# Challenge will help you build a useful toolkit of techniques such as value caching, statistical analysis, and geometric algorithms.
By the end of this book, you will have walked through challenges in C# and explored the .NET Framework in order to develop program logic for real-world applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 437
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Pavan RamchandaniAcquisition Editor: Sandeep MishraContent Development Editor: Akshada IyerTechnical Editor: Adhithya HaridasCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jisha ChirayilProduction Coordinator: Shraddha Falebhai
First published: October 2018
Production reference: 2021118
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78953-542-6
www.packt.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Rod Stephens has been a software developer, consultant, instructor, and author. He has written more than 30 books and 250 magazine articles covering such topics as three-dimensional graphics, algorithms, database design, software engineering, interview puzzles, C#, and Visual Basic.
Rod's popular C# Helper and VB Helper websites receive millions of hits per year and contain thousands of tips, tricks, and example programs for C# and Visual Basic developers. Some of his most recent books include:
WPF 3d
:
Three-Dimensional Graphics with WPF and C#
Interview Puzzles Dissected
:
Solving and Understanding Interview Puzzles
Beginning Software Engineering
Essential Algorithms
:
A Practical Approach to Computer Algorithms
Luis Felipe is a software developer with a degree in software analysis and development, and he is studying for a specialization in software engineering. The main technologies he works with are ASP.NET Core, Angular (2+), SQL Server databases and MongoDB. He has been studying the C# language for almost 10 years and has passed the Microsoft 70-483 certification exam Programming with C#.
He currently works for the public ministry, working with the developing team to build the most important software for the institution of the last years. He also worked as a freelance developer, working on desktop and web applications using C#.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
The Modern C# Challenge
Dedication
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Mathematics
Problems
1. Statistical functions
2. Permutations
3. Combinations
4. Factorials
5. Fibonacci numbers
6. Binomial coefficients
7. Pascal's triangle
8. Greatest common divisors
9. Least common multiples
10. Sums of multiples
11. Primality testing
12. Prime table
13. Prime factors
14. Unique prime factors
15. Prime tuples
16. Proper divisors
17. Amicable numbers
18. Perfect numbers
19. Armstrong numbers
Solutions
1. Statistical functions
2. Permutations
3. Combinations
4. Factorials
5. Fibonacci numbers
6. Binomial coefficients
7. Pascal's triangle
8. Greatest common divisors
9. Least common multiples
10. Sums of multiples
11. Primality testing
12. Prime table
13. Prime factors
14. Unique prime factors
15. Prime tuples
16. Proper divisors
17. Amicable numbers
18. Perfect numbers
19. Armstrong numbers
Geometry
Problems
20. Monte Carlo π
21. Newton's π
22. Bisection root-finding
23. Newton's method
24. Gaussian elimination
25. Monte Carlo integration
26. Rectangle rule integration
27. Trapezoid rule integration
28. Arrowheads
29. Line-line intersection
30. Point-line distance
31. Point-segment distance
32. Segment-segment distance
33. Circle selection
34. Line-circle intersection
35. Circle-circle intersection
36. Circle-line tangents
37. Polygon area
38. Point in a polygon
39. Convexity testing
40. Stars
Solutions
20. Monte Carlo π
21. Newton's π
22. Bisection root-finding
23. Newton's method
24. Gaussian elimination
25. Monte Carlo integration
26. Rectangle rule integration
27. Trapezoid rule integration
28. Arrowheads
29. Line-line intersection
30. Point-line distance
31. Point-segment distance
32. Segment-segment distance
33. Circle selection
34. Line-circle intersection
35. Circle-circle intersection
36. Circle-line tangents
37. Polygon area
38. Point in a polygon
39. Convexity testing
40. Stars
Dates and Times
Problems
41. Days of the week
42. Date and time picker
43. Time zone chart
44. Scheduling meetings
45. Time zone clocks
46. Local time zone clocks
47. Calculating duration
48. Calculating age
Solutions
41. Days of the week
42. Date and time picker
43. Time zone chart
44. Scheduling meetings
45. Time zone clocks
46. Local time zone clocks
47. Calculating duration
48. Calculating age
Randomization
Problems
49. Random doubles
50. Random items
51. Randomize items
52. Random groups
53. Choose items with probabilities
54. Random passwords
55. Random walks
Solutions
49. Random doubles
50. Random items
51. Randomize items
52. Random groups
53. Choose items with probabilities
54. Random passwords
55. Random walks
Strings
Problems
56. Roman numerals
57. Bytes to hex
58. Removing punctuation
59. Palindromic substrings
60. Validating passwords
61. Edit distance
62. Soundex
63. Longest common substring
Solutions
56. Roman numerals
57. Bytes to hex
58. Removing punctuation
59. Palindromic substrings
60. Validating passwords
61. Edit distance
62. Soundex
63. Longest common substring
Files and Directories
Problems
64. Removing blank lines
65. Directory size
66. Finding duplicate files
67. Thumbnails
68. Thumbnail web page
69. Find files
70. Find and Replace
71. Saving images
72. Compressing images
Solutions
64. Removing blank lines
65. Directory size
66. Finding duplicate files
67. Thumbnails
68. Thumbnail web page
69. Find files
70. Find and Replace
71. Saving images
72. Compressing images
Advanced C# and .NET Features
Problems
73. Directory size, LINQ style
74. Directory size, PLINQ style
75. Find files, LINQ style
76. Parallel primes table
77. Parallel prime tuples
78. Parallel Monte Carlo π
79. Yielding primes
80. Yielding Fibonacci numbers
81. Complex numbers
Solutions
73. Directory size, LINQ style
74. Directory size, PLINQ style
75. Find files, LINQ style
76. Parallel primes table
77. Parallel primes tuple
78. Parallel Monte Carlo π
79. Yielding primes
80. Yielding Fibonacci numbers
81. Complex numbers
Simulations
Problems
82. Dawkins' weasel
83. Hailstone sequence
84. Hailstone sequence, Redux
85. Langton's Ant
86. Life
87. Sharks and Fish
88. Slingshot
89. Slingshot refinements
90. Space Force
Solutions
82. Dawkins' weasel
83. Hailstone sequence
84. Hailstone Sequence, Redux
85. Langton's Ant
86. Life
87. Sharks and Fish
88. Slingshot
Projectile motion
Example solution
89. Slingshot refinements
90. Space Force
Sprite classes
Bubble
Ship
Keyboard events
Other details
Cryptography
Problems
91. Caesar cipher
92. Vigenère cipher
93. Cryptographic pseudorandom numbers
94. Primality testing, redux
95. Find primes
96. Hash files
97. Steganography
98. Encrypt and decrypt strings
99. Encrypt and decrypt files
100. CryptoPad
Solutions
91. Caesar cipher
92. Vigenère cipher
93. Cryptographic random numbers
94. Primality testing, redux
95. Find primes
96. Hash files
97. Steganography
98. Encrypt and decrypt strings
99. Encrypt and decrypt files
100. CryptoPad
Other Books You May Enjoy
Leave a review - let other readers know what you think
So you've read an introductory book and perhaps one or two more advanced books. You've worked with C# for a while and now you're ready for something that wasn't written for idiots or dummies. This book may be just the thing!
This book includes 100 problems (with solutions) that you can use to test and hone your C# programming skills. They cover an eclectic assortment of topics, such as mathematical calculations, geometry, dates and times, the filesystem, simulations, and cryptography. These problems won't make you an expert in those fields, but they will give you some experience with a wide variety of useful topics.
As with many skills, the best way to learn programming is to practice. Most programming books cover roughly the same topics, so they don't give you the opportunity to practice skills that fall into the programming nooks and crannies that those books miss. They do a good job of covering basic topics, such as forms, controls, classes, and for loops. More advanced books also cover more specialized topics, such as algorithms (I've written a few algorithms books), databases, web programming, and phone apps. Few books have room for more specialized topics, such as mathematical calculations, simulations, and cryptography. You'll get a brief introduction to those topics here.
In addition to giving you practice with some of programming's less heavily-trodden byways, many of the examples in this book demonstrate important C# programming concepts. They show how to protect your programs from integer and floating point overflow, avoid exhausting stack memory, know when LINQ or PLINQ might hurt performance, handle times in multiple time zones, and use the yield statement.
Two things that this book does not cover are console applications and WPF. The example solutions use Windows Forms programs because they are easy to write, and that lets you focus on the concepts behind the user interface instead of spending time fiddling with WPF issues.
Before I get to the problems themselves, the following sections explain some of the details of the book's layout, how to get the most out of the book, and how you can get in touch with the publisher. After you skim that material, find a comfortable chair, possibly in your favorite coffee shop or tea house with a caffeinated beverage and a scone, open your laptop, and get ready to give your brain a workout!
This book is intended for C# programmers. It does not explain basic C# concepts, so you should have some familiarity with C# programming before you read it. The book does not assume that you are an expert C# developer, however. If you know basic techniques such as creating classes, writing methods, and working with arrays and lists, then you should be able to work through the problems and understand their solutions.
This book includes 100 problems to challenge you and help you develop your C# programming skills. The solutions rely on general programming methods rather than C# language minutiae, so you should have a chance to solve them even if you haven't been programming for decades. They demonstrate useful techniques, not the answers to trivia questions.
Many of the examples also demonstrate important development concepts, such as comparing floating point values, handling integer overflow, avoiding unnecessary recursion, working across time zones, and building simulations. Some examples also show how to use specific advanced C# and .NET Framework tools such as the yield statement, the Transact Parallel Library (TPL), and .NET cryptography classes.
The following paragraphs describe the book's chapters in some detail:
Chapter 1, Mathematics, describes problems that ask you to perform mathematical tasks. These include numerical tasks such as calculating statistical functions, factorials, and binomial coefficients. They also include some combinatorial tasks such as finding all of the permutations or combinations from a set of items.
Chapter 2, Geometry, presents problems that perform geometric calculations. These ask you to find values such as the roots of equations, the points where lines and circles intersect, and the areas of polygons. Many of these problems ask you to draw shapes such as lines, circles, arrowheads, polygons, and stars.
Chapter 3, Dates and Times, includes problems that deal with dates and times. They pay special attention to programs that include multiple time zones or that include times when daylight saving time (or the equivalent in other countries) starts or ends.
Chapter 4, Randomization, poses problems that use randomization to produce various kinds of randomized data. For example, they ask you to generate random floating point numbers within a range, pick random items from a list or array, and generate random passwords.
Chapter 5, Strings, describes problems that manipulate strings. For example, they require you to convert between numbers and roman numerals and between bytes and hexadecimal strings, detect palindromic substrings, validate passwords for correctness, and use the Soundex algorithm to represent word's sound.
Chapter 6, Files and Directories, covers problems that deal with the filesystem. Its problems ask you to remove blank lines from a file, calculate a directory's total size, detect duplicate files, and generate thumbnails for image files in a directory.
Chapter 7, Advanced C# and .NET Features, includes problems that deal with more advanced features such as Language Integrated Query (LINQ), Parallel LINQ (PLINQ), Transact Parallel Library (TPL), and the yield statement.
Chapter 8, Simulations, asks you to write programs that perform simulations. Those range from simple numeric or text-based simulations (such as Dawkins' weasel and finding hailstone sequences), to positional simulations (such as Langton's ant and Life), to simulations that model gravitational force and acceleration.
Chapter 9, Cryptography, describes cryptographic problems. Some, such as the problems that deal with Caesar and Vigenère ciphers, are interesting mostly for fun and historical perspective. Others, such as those that deal with prime numbers, hashing, and string encryption, demonstrate strong, modern cryptographic methods.
You may not learn something new fromeveryproblem in the book, but hopefully you'll learn something from many of them.
Programming is best learned by doing rather than by reading, so I strongly encourage you to try to solve a problem before you look at my example solution later in the book. I've tried to include all of the information that you need to solve each problem in its description, so you should be able to take a crack at it before you look at my solution.
Even if you get stuck on a problem, the beginning of the solution's description may help you figure out how to solve it. If you experience an Ah ha! moment while you're reading about the solution, stop and give it another try.
Keep in mind that there are always multiple ways to solve any particular problem. Some solutions may be better than others, but most problems can be solved by several different approaches, so don't think your solution is wrong just because it's different from mine. In fact, yours may be better than mine.
The easiest way to read this book is from front to back, tackling each problem in order. The chapters are arranged so the less confusing topics come first. Similarly, the problems within each chapter are arranged with the less demanding first. Some of the material described in one problem's solution may also be used in a later solution, so reading the problems and their solutions in order makes sense.
However, the problems and their example solutions are described separately, so you can jump around if you like. For example, if you are particularly interested in steganography, you can jump straight to Chapter 9, Cryptography. The worst that will happen is that an example solution may refer you to an earlier solution for some of its details. You can then go back and read the earlier solution for further details.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/The-Modern-CSharp-Challenge. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789535426_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
This chapter includes mathematical problems. Some let you calculate useful values such as factorials and statistical functions. Others demonstrate useful programming techniques for managing recursion, value caching, and protecting applications against calculation errors. Finally, some of these problems are just plain fun and interesting.
Use the following problems to test your mathematical programming prowess. I strongly encourage you to give each problem a try before you turn to the solutions and download the example programs.
Create a StatisticsExtensions class that defines extension methods to calculate statistical functions for arrays or lists of numbers. LINQ provides the Average, Max, and Min extension methods to calculate some statistical functions, so you don't need to implement those.
The following list summarizes the statistical functions that you should provide:
Truncated mean:
This is the mean (average) after removing an indicated number or percentage of the largest and smallest values. For example, if the values are {1, 1, 3, 5, 7, 7, 9} and you want to remove the two largest and smallest values, the remaining values are {3, 5, 7}.
Median
:
This is the middlemost value. For example, if the values are {1, 1, 3, 5, 7, 7, 9}, then the median is 5 because half of the values are less than 5 and half are greater. If the set includes an even number of values, the median is the average of the two middlemost values.
Mode
:
This is the value that occurs most often. In the set {1, 2, 3, 3, 7}, the mode is 3 because it appears twice. If there's a tie, return all of the modes in a list.
Sample standard deviation
:
This is a measure of how widely spread the values are. The sample standard deviation is defined by
the
following formula:
Population standard deviation:
This is similar to the sample standard deviation except you divide by
N
instead of
N – 1
in the equation.
In the standard deviation equation:
The lowercase Greek sigma, σ, represents the standard deviation
N is the number of items in the set
The uppercase Greek sigma, ∑, means to add up the values to its right (in this case, the sums of the squares of the differences between the x
i
values and
μ
) as i ranges from 1 to N
The lowercase Greek mu, μ, is the mean (average) of the values
Write a program similar to the one shown in the following screenshot to test your extension methods. This program generates the indicated number of values and displays statistics about them. Each value is the sum of two random values between 1 and 6, so the values give a bell curve. (The shape is more obvious if you generate more than 100 values.):
The example solution uses labels to build the histogram, showing the numbers' frequencies.
A permutation is an ordering of a selection of objects from a set. For example, suppose the set is {apple, banana, cherry}, then the permutations containing two items are all of the orderings of two items selected from that set. Those permutations are {apple, banana}, {apple, cherry}, {banana, apple}, {banana, cherry}, {cherry, apple}, and {cherry, banana}. Notice that {apple, banana} and {banana, apple} contain the same items in different orders.
Write an extension method that returns a List<List<T>>, holding the permutations of a specified length from an array of items. If the specified length is omitted, return all permutations of all lengths.
Write a program similar to the one shown in the following screenshot to test your method:
A combination is an unordered selection of objects from a set. For example, if the set is {apple, banana, cherry}, then the combinations containing two items are all of the subsets containing two items in any order. Those combinations are {apple, banana}, {apple, cherry}, and {banana, cherry}. This time, {apple, banana} and {banana, apple} are considered the same, so the combinations only include one of those subsets.
Write an extension method that returns a List<List<T>>, holding the combinations of a specified length from an array of items. If the specified length is zero, return all combinations of all lengths.
Write a program similar to the one shown in the following screenshot to test your method:
The following equations define Fibonacci numbers recursively:
The last equation applies when N > 1. For example, the first ten Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
Write a program that calculates Fibonacci numbers recursively, non-recursively, and via a cache table holding Fibonacci values.
The binomial coefficient of N and K gives the number of ways that you can pick N values from a set of K values. The binomial coefficient is usually written as and is pronounced N choose K.
For example, suppose you have a set of four values, {A, B, C, D}. The possible ways to select two of those values are {A, B}, {A, C}, {A, D}, {B, C}, {B, D}, and {C, D}. There are six possible ways to select two items from the original set of four items, so =6.
You can use the following formula to calculate binomial coefficients:
For the example where we select two items out of four, the formula gives the following:
Write a program that calculates binomial coefficients. Test your program by verifying the following values:
Pascal's triangle is a triangle of numbers (you probably guessed that from its name) where each row begins and ends with 1 and every other value is the sum of the two numbers above it. The following diagram shows the first six rows of Pascal's triangle:
Write a program that displays Pascal's triangle as simple text. For a bigger challenge, display the values graphically centered over each other, as shown in the preceding figure.
Write a program that builds an array of Booleans that indicates which values up to a specified maximum are prime. For example, if you call the array Primes, then Primes[i] should be true if i is prime. After it builds the table, the program should use it to display the largest prime that it found.
A number's unique prime factors are the set of the number's prime factors with duplicates removed. For example, the prime factors of 360 are {2, 2, 2, 3, 3, 5}. Its unique prime factors are {2, 3, 5}.
Write a program that finds a number's unique prime factors.
Mathematicians like playing with prime numbers, so they have come up with several different names for groupings of related primes:
Twin primes
are primes {p, p + 2} that differ by two, such as {3, 5}. (Primes that differ by only 1 are not very interesting because 2 and 3 are the only primes that differ by 1.)
Cousin primes
are primes {p, p + 4} that differ by 4, such as {3, 7}.
Sexy primes
are primes {p, p + 6} that differ by 6, such as {5, 11}. (The name
sexy primes
is a pun because
sex
is Latin for
six
.)
You can also look for different numbers of primes with various spacings. For example, you can look for sexy pairs, sexy triples such as {7, 13, 19}, and so forth.
Write a program that checks numbers up to a maximum value, looking for primes with a given spacing and quantity. For example, the user might set the spacing to six and the number to 3 to look for groups of three primes that are each six apart, such as {5, 11, 17}.
Use your program to see what's special about groups of three or four primes that differ by 6, 12, 18, and other multiples of 3.
A divisor of a number N is any number that divides evenly into N. For example, the divisors of 12 are {1, 2, 4, 6, 12}.
The proper divisors of a number N are N's divisors, not including N itself. For example, the proper divisors of 12 are {1, 2, 4, 6}.
Write a program that finds a number's proper divisors.
The following sections describe solutions to the preceding problems. Remember that there usually isn't a single correct way to solve a particular problem. Also remember that the explanations shown here include only the most interesting and important details needed to solve the problems. Download the example solutions to see additional details and to experiment with the programs at https://github.com/PacktPublishing/The-Modern-CSharp-Challenge/tree/master/Chapter01.