Download Engineering Computation & Algorithmic Thinking Exam and more Exams Engineering in PDF only on Docsity!
ENGR 103
Engineering
Computation &
Algorithmic Thinking
COMPLETED EXAM
- What is the difference between a recursive and an iterative algorithm? Give an example of each and explain the advantages and disadvantages of using them. Answer: A recursive algorithm is one that calls itself repeatedly until a base case is reached, while an iterative algorithm is one that uses a loop to repeat a set of instructions until a termination condition is met. An example of a recursive algorithm is the factorial function, which computes n! by calling itself with n-1 as the argument until n reaches 0. An example of an iterative algorithm is the linear search, which scans an array from left to right until the target element is found or the end of the array is reached. The advantages of using recursive algorithms are that they can be more elegant, concise and intuitive than iterative ones, and that they can handle problems that have a recursive structure, such as tree traversal or backtracking. The disadvantages of using recursive algorithms are that they can be less efficient, more memory-intensive and harder to debug than iterative ones, and that they can cause stack overflow if the recursion depth is too high.
- What is the difference between a greedy and a dynamic programming algorithm? Give an example of each and explain when and why they are used. Answer: A greedy algorithm is one that makes the locally optimal choice at each step, hoping to find the globally optimal solution, while a dynamic programming algorithm is one that breaks down a complex problem into smaller subproblems, and stores and reuses the solutions to these subproblems to avoid recomputation. An example of a greedy algorithm is the coin change problem, which tries to make change for a given amount using the fewest number of coins of different denominations by choosing the largest coin available at each step. An example of a dynamic programming algorithm is the longest common subsequence problem, which tries to find the longest subsequence that is common to two given sequences by computing and storing the lengths of the common subsequences for all prefixes of the sequences, and then constructing the final solution by tracing back from the end. The advantage of using greedy algorithms is that they are simple, fast and easy to implement, but the disadvantage is that they do not always guarantee the optimal solution, and may fail for some instances of the problem. The advantage of using dynamic programming algorithms is that they can guarantee the optimal solution for problems that have optimal substructure and overlapping subproblems, but the disadvantage is that they can be more complex, slower and more memory-intensive than greedy ones.
- What is an NP-complete problem? Give an example of one and explain why it is NP-complete. Answer: An NP-complete problem is one that belongs to the class NP (nondeterministic polynomial time), which means that it can be solved in polynomial time by a nondeterministic machine (a hypothetical machine that can guess correctly at every step), and that it is also NP-hard, which means that every other problem in NP can be reduced to it in polynomial time (a transformation that preserves the yes/no answer). An example of an NP-complete problem is the traveling salesman problem (TSP), which asks for the shortest tour that visits every city in a given set exactly once and returns to the starting city. The TSP is NP- complete because it can be solved in polynomial time by a nondeterministic machine that guesses the next city to visit at every step, and because every other problem in NP can be reduced to it in polynomial time by encoding its input as a set of cities and distances, such that finding a solution to the original problem corresponds to finding a tour of length less than or equal to some threshold.
- What is the difference between a divide-and-conquer and a backtracking algorithm? Give an example of a problem that can be solved by both methods and explain how they differ in their implementation and performance. Answer: A divide-and-conquer algorithm is one that divides a large problem into smaller subproblems, solves them recursively or iteratively, and combines their solutions to obtain the final solution, while a backtracking algorithm is one that explores all possible paths or choices to find a solution, and backtracks or discards a path if it leads to a dead end or violates some constraints. An example of a problem that can be solved by both methods is finding all permutations of a given set of elements. The divide-and-conquer method would split the set into two subsets, find all permutations of each subset, and then merge them by inserting each element from one subset into every possible position in each permutation from the other subset. The backtracking method would start with an empty permutation, and then add one element at a time from the set, checking if it violates any constraints (such as duplicates), and then remove it if it does or continue with the next element if it does not. The divide-and-conquer method has a time complexity of O(n!) and a space complexity of O(n), while the backtracking method has a time complexity of O(n!) and a space complexity of O(n^2).
. What is the difference between a greedy algorithm and a dynamic programming algorithm? Give an example of a problem that can be solved by both methods and explain how they differ in their approach and performance. Answer: A greedy algorithm makes a locally optimal choice at each step, hoping to find a global optimum. A dynamic programming algorithm breaks down a problem into smaller subproblems and stores the optimal solutions for each subproblem, avoiding repeated computations. An example of a problem that can be solved by both methods is the knapsack problem, where we have to choose a subset of items with maximum value that fits in a given capacity. A greedy algorithm would sort the items by their value-to-weight ratio and pick the most valuable ones until the capacity is reached or exceeded. A dynamic programming algorithm would create a table with rows corresponding to items and columns corresponding to capacities, and fill each cell with the maximum value that can be obtained by using or not using the current item. The optimal solution is then found by tracing back from the bottom-right cell. The greedy algorithm is faster but may not find the optimal solution, while the dynamic programming algorithm is guaranteed to find the optimal solution but requires more time and space. What is the difference between a divide-and-conquer algorithm and a recursive algorithm? Give an example of a problem that can be solved by both methods and explain how they differ in their approach and performance. Answer: A divide-and-conquer algorithm splits a problem into smaller subproblems of the same type, solves them recursively, and combines their solutions to obtain the solution for the original problem. A recursive algorithm calls itself with smaller or simpler inputs until it reaches a base case, where it returns a simple value or performs a simple action. An example of a problem that can be solved by both methods is the merge sort algorithm, where we have to sort an array of elements. A divide-and-conquer algorithm would divide the array into two halves, sort them recursively, and merge them in linear time. A recursive algorithm
would sort the first element, sort the rest of the array recursively, and insert the first element into its correct position in the sorted array. The divide-and-conquer algorithm is more efficient as it has a time complexity of O(n log n), while the recursive algorithm has a time complexity of O(n^2). What is the difference between a deterministic algorithm and a randomized algorithm? Give an example of a problem that can be solved by both methods and explain how they differ in their approach and performance. Answer: A deterministic algorithm always produces the same output for a given input, following a fixed set of rules or steps. A randomized algorithm uses some form of randomness or probability in its logic, which may result in different outputs for the same input. An example of a problem that can be solved by both methods is the quicksort algorithm, where we have to sort an array of elements by choosing a pivot element and partitioning the array around it. A deterministic algorithm would choose a fixed pivot element, such as the first, last, or middle element of the array. A randomized algorithm would choose a random pivot element from the array. The deterministic algorithm may perform poorly if the pivot element is chosen such that it creates unbalanced partitions, leading to a time complexity of O(n^2). The randomized algorithm has an expected time complexity of (n log n), regardless of the input distribution. What is an approximation algorithm? Give an example of a problem that requires an approximation algorithm and explain why it is necessary and how it works. Answer: An approximation algorithm is an algorithm that finds a near-optimal solution for an optimization problem that is hard to solve exactly in polynomial time, such as NP-hard problems. An example of a problem that requires an approximation algorithm is the traveling salesman problem (TSP), where we have to find the shortest tour that visits every city in a given set exactly once and returns to the starting point. It is necessary because finding the optimal solution for TSP is NP-hard, meaning that there is no known polynomial-time algorithm that can solve it. An approximation algorithm works by finding a solution that is within some factor of the optimal solution, such as 2-approximation or 1.5-approximation. For example, one possible 2-approximation algorithm for TSP is to find a minimum spanning tree (MST) of the cities, duplicate every edge in the MST, and traverse it in depth-first order to obtain a tour. The length of this tour is at most twice as long as the optimal tour. What is an online algorithm? Give an example of a problem that requires an online algorithm and explain why it is necessary and how it works. Answer: An online algorithm is an algorithm that processes its input piece-by-piece in a serial fashion, without having access to all of it beforehand. An example of a problem that requires an online algorithm is the paging problem, where we have to manage a cache of limited size that stores pages from a larger memory. It is necessary because we do not know the sequence of page requests in advance, and we have to decide which pages to keep or evict from the cache as they arrive. An online algorithm works by using some
it may destroy the original data structure, and that it may not be stable, meaning that it may change the relative order of equal elements. What is an adaptive algorithm? Give an example of an adaptive algorithm and explain how it works and what are its benefits and drawbacks. Answer: An adaptive algorithm is an algorithm that changes its behavior or performance based on some characteristic or property of its input data structure, such as its size, distribution, or order. An example of an adaptive algorithm is the insertion sort algorithm, which works by inserting each element in the unsorted part of the array into its correct position in the sorted part, until the whole array is sorted. The benefits of an adaptive algorithm are that it can take advantage of some special cases or features of the input data structure, such as being already sorted or nearly sorted, and achieve better time complexity or efficiency. The drawbacks of an adaptive algorithm are that it may have different worst-case and average-case time complexities, and that it may be difficult to analyze or predict its performance. What is the difference between universal design and accessibility? Explain with examples.
- Universal design is a proactive approach that aims to design products or services that can be used by everyone from the beginning, without the need for adaptations or accommodations. Accessibility is a reactive approach that focuses on making products or services compatible with assistive technologies or providing alternatives for people with disabilities. For example, a website that follows universal design principles would have clear and consistent navigation, high contrast colors, adjustable font size, captions for audio and video content, and keyboard accessibility. A website that only focuses on accessibility would have a separate version for screen reader users or provide a text-only option. What are the benefits of applying universal design principles to programming? List at least three benefits and explain how they can improve the quality of your code and user experience.
- Some benefits of applying universal design principles to programming are:
- It can increase the usability and functionality of your code by making it adaptable to different devices, platforms, languages, and user preferences.
- It can enhance the maintainability and scalability of your code by reducing the complexity and redundancy of your code and making it easier to update and modify.
- It can promote the inclusivity and diversity of your code by ensuring that it can be used by people with different abilities, backgrounds, cultures, and contexts.
- What are some universal design principles that are relevant to programming? Name at least four principles and describe how they can be applied to your code.
- Some universal design principles that are relevant to programming are:
- Equitable use: Your code should provide the same functionality and experience for all users, regardless of their abilities or preferences. For example, you should avoid using color alone to convey information or using hard-coded values that may not suit all users.
- Flexibility in use: Your code should accommodate a wide range of individual preferences and situations, such as different input methods, output formats, languages, or environments. For example, you should use relative units instead of absolute units for layout, provide multiple ways to interact with your code, such as keyboard shortcuts, mouse clicks, or voice commands, and support internationalization and localization of your code.
- Simple and intuitive use: Your code should be easy to understand and use, without requiring unnecessary effort or prior knowledge. For example, you should use meaningful and consistent names for your variables, functions, and classes, provide clear and concise comments and documentation for your code, and follow coding standards and conventions.
- Perceptible information: Your code should communicate necessary information effectively to the user, regardless of their sensory abilities or environmental conditions. For example, you should use appropriate fonts, colors, contrast, spacing, and alignment for your text output, provide audio feedback or visual cues for your interactive elements, and use error messages that are informative and helpful.
- What are some tools or techniques that can help you implement universal design principles in your programming? Name at least three tools or techniques and explain how they can assist you in creating more accessible and usable code.
- Some tools or techniques that can help you implement universal design principles in your programming are:
- Code editors or IDEs: These are software applications that provide features such as syntax highlighting, auto-completion, debugging, testing, refactoring, formatting, linting, etc., that can help you write more readable, error-free, and consistent code.
- Code analyzers or validators: These are software applications or online services that check your code for errors, bugs, vulnerabilities, performance issues, accessibility issues, etc., that can help you improve the quality, security, efficiency, and compatibility of your code.
- User testing or feedback: These are methods of collecting data from real or potential users of your code, such as surveys, interviews, observations, usability tests, etc., that can help you evaluate the usability, functionality, satisfaction, and accessibility of your code.
tutorials, etc., by taking courses, workshops, webinars, etc., by joining communities, forums, groups, etc., by following experts, mentors, peers, etc., and by staying updated with the latest trends, developments, standards, guidelines, etc., in programming and universal design.
- What are some examples of programming languages or frameworks that support or facilitate universal design principles? Name at least two examples and explain how they support or facilitate universal design principles.
- Some examples of programming languages or frameworks that support or facilitate universal design principles are:
- Python: Python is a high-level, interpreted, general-purpose programming language that has a simple, clear, and expressive syntax, a large and comprehensive standard library, a rich and diverse set of third-party modules, packages, and libraries, and a supportive and active community. Python supports or facilitates universal design principles such as equitable use, flexibility in use, simple and intuitive use, perceptible information, etc., by providing features such as multiple paradigms (object-oriented, procedural, functional, etc.), multiple data types (numbers, strings, lists, tuples, dictionaries, sets, etc.), multiple input/output methods (console, file, network, database, etc.), multiple formatting options (print, f-string, format, etc.), multiple error handling mechanisms (try-except-finally-else-raise-assert-logging-debugging-testing-etc.), multiple internationalization/localization options (unicode, encoding/decoding, locale, gettext, etc.), etc.
- Bootstrap: Bootstrap is a free and open-source front-end web development framework that provides a collection of HTML, CSS, and JavaScript components, templates, utilities, and themes for creating responsive, mobile-first, accessible, and user-friendly web pages and applications. Bootstrap supports or facilitates universal design principles such as equitable use, flexibility in use, simple and intuitive use, perceptible information, etc., by providing features such as a grid system (for creating flexible layouts), a typography system (for creating readable texts), a color system (for creating contrasted colors), a component system (for creating interactive elements), a utility system (for creating customized styles), a theme system (for creating consistent appearances), an accessibility system (for creating accessible elements), etc.
- What are some common mistakes or pitfalls that programmers should avoid when applying universal design principles to their code? Name at least two common mistakes or pitfalls and explain how they can negatively affect your code or user experience.
- Some common mistakes or pitfalls that programmers should avoid when applying universal design principles to their code are:
- Assuming or generalizing: You should not assume or generalize the needs, preferences, abilities, or contexts of your users based on your own experience or perspective. You should not rely on stereotypes or biases when designing or coding your products or services. You should not ignore the diversity and variability of your users. You should not exclude or marginalize any user groups. You should not create one-size-fits-all solutions. You should respect the individuality and uniqueness of your users.
- Overlooking or neglecting: You should not overlook or neglect any aspects of universal design principles when coding your products or services. You should not focus on only one principle or feature at the expense of others. You should not prioritize form over function or vice versa. You should not compromise quality for quantity or speed. You should not skip testing or evaluation. You should not settle for good enough. You should strive for excellence
- in every aspect of your code.